Implement controller and viewer communication using WebSockets
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/gorilla/websocket"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
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)
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
})
|
||||
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)
|
||||
}
|
||||
for n := range nudges {
|
||||
log.Println(n)
|
||||
err := con.WriteJSON(n)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
log.Println(http.ListenAndServe("127.0.0.1:8081", mux))
|
||||
}
|
||||
Reference in New Issue
Block a user