good morning!!!!

Skip to content
Snippets Groups Projects
handler.go 1.34 KiB
Newer Older
Garet Halliday's avatar
Garet Halliday committed
package websocket

import (
	"net/http"

a's avatar
a committed
	"gfx.cafe/open/websocket"
Garet Halliday's avatar
Garet Halliday committed

	"gfx.cafe/open/jrpc/pkg/server"
)

type Server struct {
	Server *server.Server
}

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.Server == nil {
		http.Error(w, "no server set", http.StatusInternalServerError)
		return
	}
	conn, err := websocket.Accept(w, r, nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
a's avatar
ok  
a committed
	c := newWebsocketCodec(r.Context(), conn, "", r)
a's avatar
a committed
	err = s.Server.ServeCodec(r.Context(), c)
	if err != nil {
a's avatar
ok  
a committed
		//slog.Error("codec err", "error", err)
a's avatar
a committed
	}
Garet Halliday's avatar
Garet Halliday committed
}

// WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
//
// allowedOrigins should be a comma-separated list of allowed origin URLs.
// To allow connections with any origin, pass "*".
func WebsocketHandler(s *server.Server, allowedOrigins []string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
			OriginPatterns:       allowedOrigins,
			CompressionMode:      websocket.CompressionContextTakeover,
			CompressionThreshold: 4096,
		})
		if err != nil {
			return
		}
a's avatar
ok  
a committed
		codec := newWebsocketCodec(r.Context(), conn, r.Host, r)
a's avatar
a committed
		err = s.ServeCodec(r.Context(), codec)
		if err != nil {
Garet Halliday's avatar
Garet Halliday committed
			// slog.Error("codec err", "error", err)
a's avatar
a committed
		}