-
Notifications
You must be signed in to change notification settings - Fork 5
/
server-http.go
60 lines (52 loc) · 1.18 KB
/
server-http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package srpc
import (
"context"
"io"
"net/http"
"nhooyr.io/websocket"
)
// HTTPServer implements the SRPC server.
type HTTPServer struct {
mux Mux
srpc *Server
path string
}
// NewHTTPServer builds a http server / handler.
// if path is empty, serves on all routes.
func NewHTTPServer(mux Mux, path string) (*HTTPServer, error) {
return &HTTPServer{
mux: mux,
srpc: NewServer(mux),
path: path,
}, nil
}
func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if s.path != "" && r.URL.Path != s.path {
return
}
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{})
if err != nil {
w.WriteHeader(500)
_, _ = w.Write([]byte(err.Error() + "\n"))
return
}
defer c.Close(websocket.StatusInternalError, "closed")
ctx := r.Context()
wsConn, err := NewWebSocketConn(ctx, c, true, nil)
if err != nil {
c.Close(websocket.StatusInternalError, err.Error())
return
}
// handle incoming streams
for {
strm, err := wsConn.AcceptStream()
if err != nil {
if err != io.EOF && err != context.Canceled {
// TODO: handle / log error?
c.Close(websocket.StatusInternalError, err.Error())
}
return
}
go s.srpc.HandleStream(ctx, strm)
}
}