/
server.go
78 lines (69 loc) · 1.9 KB
/
server.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"io"
"net/http"
"strings"
"github.com/vipnode/vipnode/v2/jsonrpc2"
"github.com/vipnode/vipnode/v2/jsonrpc2/ws"
)
type wsHandler interface {
Upgrade(*http.Request, http.ResponseWriter, http.Header) (jsonrpc2.Codec, error)
}
type server struct {
jsonrpc2.HTTPServer
ws ws.Upgrader
debugLog bool
header http.Header
onDisconnect func(remote jsonrpc2.Service) error
healthCheck func(w io.Writer) error
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/health") {
if s.healthCheck == nil {
http.Error(w, "detailed health check disabled", http.StatusOK)
} else if err := s.healthCheck(w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
switch r.Method {
case http.MethodPost:
// Assume RPC over HTTP
for k, values := range s.header {
for _, v := range values {
w.Header().Set(k, v)
}
}
s.HTTPServer.ServeHTTP(w, r)
case http.MethodGet:
// Assume WebSocket upgrade request
codec, err := s.ws.Upgrade(r, w, nil)
if err != nil {
logger.Debugf("websocket upgrade error from %s: %s", r.RemoteAddr, err)
http.Error(w, fmt.Sprintf("incorrect vipnode websocket api handshake: %s", err), http.StatusBadRequest)
return
}
if s.debugLog {
codec = jsonrpc2.DebugCodec(r.RemoteAddr, codec)
}
defer codec.Close()
remote := &jsonrpc2.Remote{
Codec: codec,
Server: &s.HTTPServer.Server,
Client: &jsonrpc2.Client{},
PendingLimit: 50,
PendingDiscard: 10,
}
if err := remote.Serve(); err != nil && err != io.EOF {
logger.Warningf("jsonrpc2.Remote.Serve() error: %s", err)
}
if s.onDisconnect != nil {
if err := s.onDisconnect(remote); err != nil {
logger.Warningf("jsonrpc2.Service disconnect error: %s", err)
}
}
default:
http.Error(w, "unsupported method", http.StatusUnsupportedMediaType)
}
}