forked from zhiduoke/gapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
164 lines (146 loc) · 3.5 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package gapi
import (
"fmt"
"net/http"
"sync"
"sync/atomic"
"github.com/julienschmidt/httprouter"
"github.com/zhiduoke/gapi/metadata"
"google.golang.org/grpc"
)
type CallHandler interface {
HandleRequest(call *metadata.Call, ctx *Context) ([]byte, error)
WriteResponse(call *metadata.Call, ctx *Context, data []byte) error
}
type HandleFunc func(ctx *Context) error
type Server struct {
router atomic.Value
ctxpool sync.Pool
routeLock sync.Mutex
clients map[string]*grpc.ClientConn
middlewares struct {
sync.RWMutex
inner map[string]HandleFunc
}
callHandlers struct {
sync.RWMutex
inner map[string]CallHandler
}
globalUses []HandleFunc
Dial func(string) (*grpc.ClientConn, error)
NotFound http.Handler
}
func (s *Server) getCallHandler(name string) CallHandler {
s.callHandlers.RLock()
h := s.callHandlers.inner[name]
s.callHandlers.RUnlock()
return h
}
func (s *Server) RegisterHandler(name string, h CallHandler) {
s.callHandlers.Lock()
s.callHandlers.inner[name] = h
s.callHandlers.Unlock()
}
func (s *Server) Use(handle HandleFunc) {
s.globalUses = append(s.globalUses, handle)
}
func (s *Server) generateMiddlewareChain(mws []string, exec HandleFunc) ([]HandleFunc, error) {
n := len(mws) + 1
hs := make([]HandleFunc, 0, n+len(s.globalUses))
if len(s.globalUses) > 0 {
hs = append(hs, s.globalUses...)
}
s.middlewares.RLock()
for _, name := range mws {
mw := s.middlewares.inner[name]
if mw == nil {
s.middlewares.RUnlock()
return nil, fmt.Errorf("no such middleware: %s", name)
}
hs = append(hs, mw)
}
s.middlewares.RUnlock()
hs = append(hs, exec)
return hs, nil
}
func (s *Server) RegisterMiddleware(name string, h HandleFunc) {
s.middlewares.Lock()
s.middlewares.inner[name] = h
s.middlewares.Unlock()
}
func (s *Server) UpdateRoute(md *metadata.Metadata) error {
s.routeLock.Lock()
defer s.routeLock.Unlock()
old := s.clients
clients := map[string]*grpc.ClientConn{}
defer func() {
// close new connections when error occurred
for server, cc := range clients {
if old[server] == nil {
cc.Close()
}
}
}()
dial := s.Dial
if dial == nil {
dial = defaultDial
}
// register routes from metadata
router := httprouter.New()
for _, route := range md.Routes {
ch := s.getCallHandler(route.Call.Handler)
if ch == nil {
return fmt.Errorf("no such handler: %s", route.Call.Handler)
}
// reuse existed connection
client := old[route.Call.Server]
if client == nil {
var err error
client, err = dial(route.Call.Server)
if err != nil {
return err
}
}
clients[route.Call.Server] = client
rh := &routeHandler{
s: s,
call: route.Call,
ch: ch,
client: client,
}
chain, err := s.generateMiddlewareChain(route.Options.Middlewares, rh.invoke)
if err != nil {
return err
}
rh.chain = chain
router.Handle(route.Method, route.Path, rh.handle)
}
router.NotFound = s.NotFound
s.router.Store(router)
s.clients = clients
for server, cc := range old {
if clients[server] == nil {
cc.Close()
}
}
// don't clean conns
clients = nil
return nil
}
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.router.Load().(*httprouter.Router).ServeHTTP(w, req)
}
func NewServer() *Server {
s := &Server{
ctxpool: sync.Pool{
New: func() interface{} {
return &Context{}
},
},
NotFound: http.NotFoundHandler(),
}
s.router.Store(httprouter.New())
s.middlewares.inner = map[string]HandleFunc{}
s.callHandlers.inner = map[string]CallHandler{}
return s
}