-
Notifications
You must be signed in to change notification settings - Fork 0
/
restful_relayer.go
74 lines (64 loc) · 1.59 KB
/
restful_relayer.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
package server
import (
"bytes"
"context"
"io"
"net/http"
"regexp"
"github.com/superisaac/nodemux/core"
)
// REST Handler
type RESTRelayer struct {
rootCtx context.Context
regex *regexp.Regexp
acc *Acc
}
func NewRESTRelayer(rootCtx context.Context) *RESTRelayer {
return &RESTRelayer{
rootCtx: rootCtx,
regex: regexp.MustCompile(`^/rest/([^/]+/[^/]+/[^/]+)/(.*)$`),
}
}
func (self *RESTRelayer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
acc := self.acc
method := r.URL.Path
if acc == nil {
acc = AccFromContext(r.Context())
if acc == nil {
w.WriteHeader(404)
w.Write([]byte("acc not found"))
return
}
matches := self.regex.FindStringSubmatch(r.URL.Path)
if len(matches) < 3 {
requestLog(r).Warnf("http url pattern failed")
w.WriteHeader(404)
w.Write([]byte("not found"))
return
}
method = "/" + matches[2]
}
m := nodemuxcore.GetMultiplexer()
delegator := nodemuxcore.GetDelegatorFactory().GetRESTDelegator(acc.Chain.Namespace)
if delegator == nil {
w.WriteHeader(404)
w.Write([]byte("backend not found"))
return
}
if r.Method == http.MethodPost || r.Method == http.MethodPut {
body, err := io.ReadAll(r.Body)
if err != nil {
requestLog(r).Warnf("error reading request body %#v", err)
w.WriteHeader(400)
w.Write([]byte("bad request"))
return
}
r.Body = io.NopCloser(bytes.NewBuffer(body))
}
err := delegator.DelegateREST(self.rootCtx, m, acc.Chain, method, w, r)
if err != nil {
requestLog(r).Warnf("error delegate rest %s", err)
w.WriteHeader(500)
w.Write([]byte("server error"))
}
} // RESTRelayer.ServeHTTP