-
Notifications
You must be signed in to change notification settings - Fork 6
/
http_transport.go
191 lines (144 loc) · 3.99 KB
/
http_transport.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package httptransport
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"sort"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/go-courier/logr"
"github.com/go-courier/courier"
"github.com/go-courier/httptransport/handlers"
"github.com/go-courier/httptransport/transformers"
"github.com/go-courier/httptransport/validator"
"github.com/julienschmidt/httprouter"
)
func MiddlewareChain(mw ...HttpMiddleware) HttpMiddleware {
return func(final http.Handler) http.Handler {
last := final
for i := len(mw) - 1; i >= 0; i-- {
last = mw[i](last)
}
return last
}
}
type HttpMiddleware func(http.Handler) http.Handler
func NewHttpTransport(serverModifiers ...ServerModifier) *HttpTransport {
return &HttpTransport{
ServerModifiers: serverModifiers,
}
}
type HttpTransport struct {
ServiceMeta
Port int
// for modifying http.Server
ServerModifiers []ServerModifier
// Middlewares
// can use https://github.com/gorilla/handlers
Middlewares []HttpMiddleware
// validator mgr for parameter validating
ValidatorMgr validator.ValidatorMgr
// transformer mgr for parameter transforming
TransformerMgr transformers.TransformerMgr
CertFile string
KeyFile string
httpRouter *httprouter.Router
}
type ServerModifier func(server *http.Server) error
func (t *HttpTransport) SetDefaults() {
t.ServiceMeta.SetDefaults()
if t.ValidatorMgr == nil {
t.ValidatorMgr = validator.ValidatorMgrDefault
}
if t.TransformerMgr == nil {
t.TransformerMgr = transformers.TransformerMgrDefault
}
if t.Middlewares == nil {
t.Middlewares = []HttpMiddleware{handlers.LogHandler()}
}
if t.Port == 0 {
t.Port = 80
}
}
func (t *HttpTransport) ServeHTTP(w http.ResponseWriter, req *http.Request) {
t.httpRouter.ServeHTTP(w, req)
}
func courierPrintln(format string, args ...interface{}) {
fmt.Printf(`[Courier] `+format+"\n", args...)
}
func (t *HttpTransport) Serve(router *courier.Router) error {
return t.ServeContext(context.Background(), router)
}
func (t *HttpTransport) ServeContext(ctx context.Context, router *courier.Router) error {
t.SetDefaults()
l := logr.FromContext(ctx)
t.httpRouter = t.convertRouterToHttpRouter(router)
srv := &http.Server{}
srv.Addr = fmt.Sprintf(":%d", t.Port)
srv.Handler = MiddlewareChain(t.Middlewares...)(t)
for i := range t.ServerModifiers {
if err := t.ServerModifiers[i](srv); err != nil {
l.Error(err)
}
}
go func() {
courierPrintln("%s listen on %s", t.ServiceMeta, srv.Addr)
if t.CertFile != "" && t.KeyFile != "" {
if err := srv.ListenAndServeTLS(t.CertFile, t.KeyFile); err != nil {
l.Error(err)
}
return
}
if err := srv.ListenAndServe(); err != nil {
l.Error(err)
}
}()
stopCh := make(chan os.Signal, 1)
signal.Notify(stopCh, os.Interrupt, syscall.SIGTERM)
<-stopCh
timeout := 10 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
l.Info("shutdowning in %s", timeout)
return srv.Shutdown(ctx)
}
func (t *HttpTransport) convertRouterToHttpRouter(router *courier.Router) *httprouter.Router {
routes := router.Routes()
if len(routes) == 0 {
panic(errors.Errorf("need to register Operator to Router %#v before serve", router))
}
routeMetas := make([]*HttpRouteMeta, len(routes))
for i := range routes {
routeMetas[i] = NewHttpRouteMeta(routes[i])
}
httpRouter := httprouter.New()
sort.Slice(routeMetas, func(i, j int) bool {
return routeMetas[i].Key() < routeMetas[j].Key()
})
for i := range routeMetas {
httpRoute := routeMetas[i]
httpRoute.Log()
if err := tryCatch(func() {
httpRouter.HandlerFunc(
httpRoute.Method(),
httpRoute.Path(),
NewHttpRouteHandler(&t.ServiceMeta, httpRoute, NewRequestTransformerMgr(t.TransformerMgr, t.ValidatorMgr)).ServeHTTP,
)
}); err != nil {
panic(errors.Errorf("register http route `%s` failed: %s", httpRoute, err))
}
}
return httpRouter
}
func tryCatch(fn func()) (err error) {
defer func() {
if e := recover(); e != nil {
err = errors.Errorf("%+v", e)
}
}()
fn()
return nil
}