瀏覽代碼

fix: websocket implementation not working because of the CORS headers

master
Blaz Smehov 2 天之前
父節點
當前提交
8c14b77ba8
共有 2 個文件被更改,包括 28 次插入8 次删除
  1. +26
    -8
      cmd/server/main.go
  2. +2
    -0
      scripts/testAPI.sh

+ 26
- 8
cmd/server/main.go 查看文件

@@ -7,6 +7,7 @@ import (
"log"
"net/http"
"os/signal"
"strings"
"sync"
"syscall"
"time"
@@ -71,11 +72,20 @@ func main() {
r.HandleFunc("/api/settings", controller.SettingsListController(appState, client, ctx)).Methods("GET")
r.HandleFunc("/api/settings", controller.SettingsEditController(settingsWriter, appState, client, ctx)).Methods("POST")

// r.HandleFunc("/api/beacons/ws", serveWs(appState, ctx))
wsHandler := http.HandlerFunc(serveWs(appState, ctx))
restApiHandler := handlers.CORS(originsOk, headersOk, methodsOk)(r)
mainHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/beacons/ws") {
wsHandler.ServeHTTP(w, r)
return
}

restApiHandler.ServeHTTP(w, r)
})

server := http.Server{
Addr: cfg.HTTPAddr,
Handler: handlers.CORS(originsOk, headersOk, methodsOk)(r),
Handler: mainHandler,
}

go server.ListenAndServe()
@@ -119,9 +129,9 @@ func serveWs(appstate *appcontext.AppState, ctx context.Context) http.HandlerFun
}
return
}
wg.Add(1)
wg.Add(2)
go writer(ws, appstate, ctx)
reader(ws)
go reader(ws, ctx)
}
}

@@ -161,17 +171,25 @@ func writer(ws *websocket.Conn, appstate *appcontext.AppState, ctx context.Conte
}
}

func reader(ws *websocket.Conn) {
func reader(ws *websocket.Conn, ctx context.Context) {
defer func() {
ws.Close()
wg.Done()
}()
ws.SetReadLimit(512)
ws.SetReadDeadline(time.Now().Add((60 * 9) / 10 * time.Second))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add((60 * 9) / 10 * time.Second)); return nil })
for {
_, _, err := ws.ReadMessage()
if err != nil {
break
fmt.Println("this is called")
select {
case <-ctx.Done():
fmt.Println("closing websocket reader")
return
default:
_, _, err := ws.ReadMessage()
if err != nil {
return
}
}
}
}

+ 2
- 0
scripts/testAPI.sh 查看文件

@@ -8,6 +8,8 @@ curl -s -X POST $URL \
-d '{"Beacon_id":"'"$BEACON_ID"'","Name":"Beacon1","tx_power":-59,"rssi":-70}'
echo -e "\n"

sleep 1

curl -X GET $URL

sleep 1

Loading…
取消
儲存