@@ -20,13 +20,14 @@ import (
20
20
21
21
// Server is json-rpc server with an optional basic auth
22
22
type Server struct {
23
- API string
24
- AuthUser string
25
- AuthPasswd string
26
- Version string
27
- AppName string
28
- Logger L
29
- funcs struct {
23
+ API string // url path, i.e. "/command" or "/rpc" etc.
24
+ AuthUser string // basic auth user name, should match Client.AuthUser, optional
25
+ AuthPasswd string // basic auth password, should match Client.AuthPasswd, optional
26
+ Version string // server version, injected from main and used for informational headers only
27
+ AppName string // plugin name, injected from main and used for informational headers only
28
+ Logger L // logger, if nil will default to NoOpLogger
29
+
30
+ funcs struct {
30
31
m map [string ]ServerFn
31
32
once sync.Once
32
33
}
@@ -37,11 +38,8 @@ type Server struct {
37
38
}
38
39
}
39
40
40
- // Encoder is a function to encode call's result to Response
41
- type Encoder func (id uint64 , resp interface {}, e error ) (Response , error )
42
-
43
- // ServerFn handler registered for each method with Add
44
- // Implementations provided by consumer and define response logic.
41
+ // ServerFn handler registered for each method with Add or Group.
42
+ // Implementations provided by consumer and defines response logic.
45
43
type ServerFn func (id uint64 , params json.RawMessage ) Response
46
44
47
45
// Run http server on given port
@@ -92,7 +90,7 @@ func (s *Server) Shutdown() error {
92
90
return s .httpServer .Shutdown (ctx )
93
91
}
94
92
95
- // Add method handler
93
+ // Add method handler. Handler will be called on matching method (Request.Method)
96
94
func (s * Server ) Add (method string , fn ServerFn ) {
97
95
s .httpServer .Lock ()
98
96
defer s .httpServer .Unlock ()
@@ -112,13 +110,14 @@ func (s *Server) Add(method string, fn ServerFn) {
112
110
// HandlersGroup alias for map of handlers
113
111
type HandlersGroup map [string ]ServerFn
114
112
115
- // Group of handlers with common prefix
113
+ // Group of handlers with common prefix, match on group.method
116
114
func (s * Server ) Group (prefix string , m HandlersGroup ) {
117
115
for k , v := range m {
118
116
s .Add (prefix + "." + k , v )
119
117
}
120
118
}
121
119
120
+ // handler is http handler multiplexing calls by req.Method
122
121
func (s * Server ) handler (w http.ResponseWriter , r * http.Request ) {
123
122
req := struct {
124
123
ID uint64 `json:"id"`
@@ -144,6 +143,7 @@ func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
144
143
render .JSON (w , r , fn (req .ID , params ))
145
144
}
146
145
146
+ // basicAuth middleware. enabled only if both AuthUser and AuthPasswd defined.
147
147
func (s * Server ) basicAuth (h http.Handler ) http.Handler {
148
148
return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
149
149
0 commit comments