104 lines
2.4 KiB
Go
104 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"github.com/gorilla/websocket"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
WriteBufferSize: 4096,
|
|
ReadBufferSize: 0,
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
return true
|
|
},
|
|
}
|
|
|
|
func main() {
|
|
var nudges = make(chan [2]int)
|
|
|
|
go func() {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Add("Access-Control-Allow-Origin", "*")
|
|
w.Header().Add("Access-Control-Allow-Headers", "*")
|
|
w.Header().Add("Access-Control-Allow-Methods", "*")
|
|
switch r.Method {
|
|
case "OPTIONS":
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
case "POST":
|
|
var nudge [2]int
|
|
switch r.Header.Get("Content-Type") {
|
|
case "application/json":
|
|
var decoder = json.NewDecoder(r.Body)
|
|
if err := decoder.Decode(&nudge); err != nil {
|
|
log.Println(err)
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
default:
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
nudges <- nudge
|
|
w.WriteHeader(http.StatusNoContent)
|
|
case "GET":
|
|
w.Header().Add("Content-Type", "text/html")
|
|
w.WriteHeader(http.StatusOK)
|
|
file, _ := os.Open("./controller/controller.html")
|
|
defer file.Close()
|
|
io.Copy(w, file)
|
|
default:
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
}
|
|
})
|
|
mux.HandleFunc("/main.css", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Add("Content-Type", "text/css")
|
|
w.WriteHeader(http.StatusOK)
|
|
file, _ := os.Open("./main.css")
|
|
defer file.Close()
|
|
io.Copy(w, file)
|
|
})
|
|
mux.HandleFunc("/controller.js", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Add("Content-Type", "application/javascript")
|
|
w.WriteHeader(http.StatusOK)
|
|
file, _ := os.Open("./controller/controller.js")
|
|
defer file.Close()
|
|
io.Copy(w, file)
|
|
})
|
|
log.Println(http.ListenAndServe(":8080", mux))
|
|
}()
|
|
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
con, err := upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
var quit = make(chan bool)
|
|
con.SetCloseHandler(func(code int, text string) error {
|
|
quit <- true
|
|
return nil
|
|
})
|
|
for {
|
|
select {
|
|
case <-quit:
|
|
return
|
|
case n := <-nudges:
|
|
log.Println(n)
|
|
err := con.WriteJSON(n)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
})
|
|
log.Println(http.ListenAndServe("127.0.0.1:8081", mux))
|
|
}
|