go-emlid/cmd/fake-reach/endpoints.go

102 lines
2.8 KiB
Go

package main
import (
_ "embed"
"encoding/json"
"io"
"log/slog"
"net/http"
socketio "github.com/googollee/go-socket.io"
"github.com/googollee/go-socket.io/engineio"
"github.com/googollee/go-socket.io/engineio/transport"
"github.com/googollee/go-socket.io/engineio/transport/polling"
"github.com/googollee/go-socket.io/engineio/transport/websocket"
"github.com/pkg/errors"
)
//go:embed data/info.json
var info []byte
//go:embed data/configuration.json
var configuration []byte
func GetInfo(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
if _, err := w.Write(info); err != nil {
slog.Error("could not write info", slog.Any("error", errors.WithStack(err)))
}
}
func GetConfiguration(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
if _, err := w.Write(configuration); err != nil {
slog.Error("could not write configuration", slog.Any("error", errors.WithStack(err)))
}
}
func PostJSON(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
slog.Error("could not read body", slog.Any("error", errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer r.Body.Close()
var payload any
if err := json.Unmarshal(body, &payload); err != nil {
slog.Error("could not unmarshal payload", slog.Any("error", errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
formatted, err := json.MarshalIndent(payload, "", " ")
if err != nil {
slog.Error("could not marshal payload", slog.Any("error", errors.WithStack(err)))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
slog.Info("received payload", slog.Any("payload", string(formatted)))
if _, err := w.Write(formatted); err != nil {
slog.Error("could not write payload", slog.Any("error", errors.WithStack(err)))
}
}
var allowOriginFunc = func(r *http.Request) bool {
return true
}
func NewSocketIOServer() *socketio.Server {
server := socketio.NewServer(&engineio.Options{
Transports: []transport.Transport{
&polling.Transport{
CheckOrigin: allowOriginFunc,
},
&websocket.Transport{
CheckOrigin: allowOriginFunc,
},
},
})
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
slog.Info("connected", slog.Any("id", s.ID()))
return nil
})
server.OnError("/", func(s socketio.Conn, err error) {
slog.Info("socketio error", slog.Any("id", s.ID()), slog.Any("error", errors.WithStack(err)))
})
server.OnDisconnect("/", func(s socketio.Conn, reason string) {
slog.Info("disconnected", slog.Any("id", s.ID()), slog.Any("reason", reason))
})
return server
}