forked from snowmerak/lux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlux.go
234 lines (207 loc) · 6.26 KB
/
lux.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package lux
import (
ctx "context"
"encoding/json"
"github.com/rs/zerolog"
"github.com/serve-it-yourself/lux/bean"
"net/http"
"os"
"path/filepath"
"time"
"github.com/caddyserver/certmagic"
"github.com/julienschmidt/httprouter"
"github.com/serve-it-yourself/lux/context"
"github.com/serve-it-yourself/lux/handler"
"github.com/serve-it-yourself/lux/middleware"
"github.com/serve-it-yourself/lux/router"
"github.com/serve-it-yourself/lux/session"
"github.com/serve-it-yourself/lux/swagger"
"golang.org/x/net/http2"
)
type Lux struct {
routers []*router.RouterGroup
logger *zerolog.Logger
server *http.Server
middlewares []middleware.Set
builtRouter *httprouter.Router
swagger *swagger.Swagger
session *session.Local
jwtConfig *context.JWTConfig
container *bean.Container
ctx ctx.Context
}
func New(swaggerInfo *swagger.Info, logger *zerolog.Logger, middlewares ...middleware.Set) *Lux {
swg := new(swagger.Swagger)
if swaggerInfo != nil {
swg.Info = *swaggerInfo
}
swg.SwaggerVersion = "2.0"
localSession := session.NewLocal()
session.StartGC(localSession)
return &Lux{
routers: []*router.RouterGroup{},
logger: logger,
server: new(http.Server),
middlewares: middlewares,
builtRouter: httprouter.New(),
swagger: swg,
session: localSession,
container: bean.NewContainer(),
}
}
func (l *Lux) Container() *bean.Container {
return l.container
}
func (l *Lux) SetLogger(logger *zerolog.Logger) {
l.logger = logger
}
func (l *Lux) SetReadHeaderTimeout(duration time.Duration) {
l.server.ReadHeaderTimeout = duration
}
func (l *Lux) SetReadTimeout(duration time.Duration) {
l.server.ReadTimeout = duration
}
func (l *Lux) SetWriteTimeout(duration time.Duration) {
l.server.WriteTimeout = duration
}
func (l *Lux) SetIdleTimeout(duration time.Duration) {
l.server.IdleTimeout = duration
}
func (l *Lux) SetMaxHeaderBytes(n int) {
l.server.MaxHeaderBytes = n
}
func (l *Lux) SetInfoEmail(email string) {
l.swagger.Info.Contact.Email = email
}
func (l *Lux) SetInfoLicense(name, link string) {
l.swagger.Info.License.Name = name
l.swagger.Info.License.URL = link
}
func (l *Lux) SetJWTConfig(cfg *context.JWTConfig) {
l.jwtConfig = cfg
}
func (l *Lux) ShowSwagger(path string, middlewares ...middleware.Set) {
swaggerjson, err := json.Marshal(l.swagger)
if err != nil {
panic(err)
}
f, err := os.Create(filepath.Join(".", "swagger", "dist", "swagger.json"))
if err != nil {
panic(err)
}
f.Write(swaggerjson)
f.Close()
rg := l.NewRouterGroup(path, middlewares...)
rg.Statics("/", filepath.Join(".", "swagger", "dist"))
l.logger.Warn().Str("path", path).Msg("Swagger is available")
}
func (l *Lux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
luxCtx := new(context.LuxContext)
luxCtx.LocalSession = l.session
luxCtx.Request = r
luxCtx.Response = context.NewResponse()
luxCtx.JWTConfig = l.jwtConfig
luxCtx.Logger = l.logger
luxCtx.Container = l.container
defer func() {
for key, values := range luxCtx.Response.Headers {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(luxCtx.Response.StatusCode)
w.Write(luxCtx.Response.Body)
}()
if rs := middleware.ApplyRequests(luxCtx, l.middlewares); rs != "" {
l.logger.Error().Str("error", rs).Msg("request middleware error")
return
}
l.builtRouter.ServeHTTP(luxCtx.Response, luxCtx.Request)
if !luxCtx.IsOk() {
return
}
if rs := middleware.ApplyResponses(luxCtx, l.middlewares); rs != "" {
l.logger.Error().Str("error", rs).Msg("response middleware error")
return
}
}
func (l *Lux) buildServer(ctx ctx.Context, addr string) {
l.server.Addr = addr
l.server.Handler = l
l.builtRouter = new(httprouter.Router)
for _, routerGroup := range l.routers {
for path, routerMap := range routerGroup.Routers {
for method, router := range routerMap {
l.builtRouter.Handle(method, path, handler.Wrap(ctx, l.logger, l.jwtConfig, l.container, router.Handler))
}
}
}
l.routers = nil
l.logger.Info().Str("addr", addr).Msg("Server is ready to serve")
}
func (l *Lux) ListenAndServe1(ctx ctx.Context, addr string) error {
l.buildServer(ctx, addr)
if err := l.server.ListenAndServe(); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Listen and serve error")
return err
}
return nil
}
func (l *Lux) ListenAndServe1TLS(ctx ctx.Context, addr string, certFile string, keyFile string) error {
l.buildServer(ctx, addr)
if err := l.server.ListenAndServeTLS(certFile, keyFile); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Listen and serve TLS error")
return err
}
return nil
}
func (l *Lux) ListenAndServe1AutoTLS(ctx ctx.Context, addr []string) error {
if len(addr) == 0 {
addr = []string{"localhost:443"}
}
l.buildServer(ctx, addr[0])
if err := certmagic.HTTPS(addr, l.builtRouter); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Listen and serve Auto TLS error")
return err
}
return nil
}
func (l *Lux) ListenAndServe2(ctx ctx.Context, addr string) error {
l.buildServer(ctx, addr)
if err := http2.ConfigureServer(l.server, nil); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Http2 configuration error")
return err
}
if err := l.server.ListenAndServe(); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Listen and serve http2 error")
return err
}
return nil
}
func (l *Lux) ListenAndServe2TLS(ctx ctx.Context, addr string, certFile string, keyFile string) error {
l.buildServer(ctx, addr)
if err := http2.ConfigureServer(l.server, nil); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Http2 configuration error")
return err
}
if err := l.server.ListenAndServeTLS(certFile, keyFile); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Listen and serve http2 TLS error")
return err
}
return nil
}
func (l *Lux) ListenAndServe2AutoTLS(ctx ctx.Context, addr []string) error {
if len(addr) == 0 {
addr = []string{"localhost:443"}
}
l.buildServer(ctx, addr[0])
if err := http2.ConfigureServer(l.server, nil); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Http2 configuration error")
return err
}
if err := certmagic.HTTPS(addr, l.builtRouter); err != nil {
l.logger.Fatal().Str("error", err.Error()).Msg("Listen and serve http2 Auto TLS error")
return err
}
return nil
}