// This example listens on port :80 serving a web page. Multiple clients // may connect and be serviced at the same time. IPv4 only. HTTP only. // // $ curl http://10.0.0.2 // // Note: It may be necessary to increase the stack size when using "net/http". // Use the -stack-size=4KB command line option. //go:build ninafw || wioterminal package main import ( "fmt" "log" "machine" "net/http" "strconv" "time" "tinygo.org/x/drivers/netlink" "tinygo.org/x/drivers/netlink/probe" ) var ( ssid string pass string port string = ":80" ) var led = machine.LED func main() { // wait a bit for serial time.Sleep(2 * time.Second) led.Configure(machine.PinConfig{Mode: machine.PinOutput}) link, _ := probe.Probe() err := link.NetConnect(&netlink.ConnectParams{ Ssid: ssid, Passphrase: pass, }) if err != nil { log.Fatal(err) } http.HandleFunc("/", root) http.HandleFunc("/hello", hello) http.HandleFunc("/cnt", cnt) http.HandleFunc("/6", sixlines) http.HandleFunc("/off", LED_OFF) http.HandleFunc("/on", LED_ON) err = http.ListenAndServe(port, nil) for err != nil { fmt.Printf("error: %s\r\n", err.Error()) time.Sleep(5 * time.Second) } } func root(w http.ResponseWriter, r *http.Request) { access := 1 cookie, err := r.Cookie("access") if err != nil { if err == http.ErrNoCookie { cookie = &http.Cookie{ Name: "access", Value: "1", } } else { http.Error(w, fmt.Sprintf("%s", err.Error()), http.StatusBadRequest) return } } else { v, err := strconv.ParseInt(cookie.Value, 10, 0) if err != nil { http.Error(w, fmt.Sprintf("invalid cookie.Value : %s", cookie.Value), http.StatusBadRequest) return } cookie.Value = fmt.Sprintf("%d", v+1) access = int(v) + 1 } http.SetCookie(w, cookie) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, ` TinyGo HTTP Server
TinyGo HTTP Server

access: %d

/hello
/6

LED
/on
/off

/cnt
cnt:
incrCnt()

`, access) } func sixlines(w http.ResponseWriter, r *http.Request) { // https://fukuno.jig.jp/3267 fmt.Fprint(w, ``) } func LED_ON(w http.ResponseWriter, r *http.Request) { led.High() w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`) fmt.Fprintf(w, "led.High()") } func LED_OFF(w http.ResponseWriter, r *http.Request) { led.Low() w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`) fmt.Fprintf(w, "led.Low()") } func hello(w http.ResponseWriter, r *http.Request) { w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`) fmt.Fprintf(w, "hello") } var counter int func cnt(w http.ResponseWriter, r *http.Request) { r.ParseForm() if r.Method == "POST" { c := r.Form.Get("cnt") if c != "" { i64, _ := strconv.ParseInt(c, 0, 0) counter = int(i64) } } w.Header().Set(`Content-Type`, `application/json`) fmt.Fprintf(w, `{"cnt": %d}`, counter) }