-
Notifications
You must be signed in to change notification settings - Fork 0
/
tupa.go
325 lines (271 loc) · 8.79 KB
/
tupa.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package tupa
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
type (
Context interface {
Request() *http.Request
Response() http.ResponseWriter
SendString(s string) error
Param(param string) string
QueryParam(param string) string
QueryParams() map[string][]string
SetRequest(r *http.Request)
SetResponse(w http.ResponseWriter)
GetCtx() context.Context
SetContext(ctx context.Context)
Context() context.Context
CtxWithValue(key, value interface{}) *TupaContext
CtxValue(key interface{}) interface{}
NewTupaContext(req **http.Request, resp http.ResponseWriter, ctx context.Context) *TupaContext
}
TupaContext struct {
Req *http.Request
Resp http.ResponseWriter
Ctx context.Context
}
)
type APIFunc func(*TupaContext) error
type MiddlewareFuncCtx func(APIFunc) *TupaContext
type APIServer struct {
listenAddr string
server *http.Server
globalMiddlewares MiddlewareChain
globalAfterMiddlewares MiddlewareChain
router *mux.Router
routeManager RouteManager
}
const (
MethodGet HTTPMethod = http.MethodGet
MethodPost HTTPMethod = http.MethodPost
MethodPut HTTPMethod = http.MethodPut
MethodDelete HTTPMethod = http.MethodDelete
MethodPatch HTTPMethod = http.MethodPatch
MethodOptions HTTPMethod = http.MethodOptions
)
var AllowedMethods = map[HTTPMethod]bool{
MethodGet: true,
MethodPost: true,
MethodPut: true,
MethodDelete: true,
MethodPatch: true,
MethodOptions: true,
}
var allRoutes []RouteInfo
func (a *APIServer) New() {
if a.routeManager == nil {
defaultRouteManager()
} else {
a.routeManager()
}
a.RegisterRoutes(GetRoutes())
c := cors.New(cors.Options{
AllowedHeaders: []string{
"Authorization", "authorization", "Accept", "Content-Type", "X-Requested-With", "X-Frame-Options",
"X-XSS-Protection", "X-Content-Type-Options", "X-Permitted-Cross-Domain-Policies", "Referrer-Policy", "Expect-CT",
"Feature-Policy", "Content-Security-Policy", "Content-Security-Policy-Report-Only", "Strict-Transport-Security",
"Public-Key-Pins", "Public-Key-Pins-Report-Only", "Access-Control-Allow-Origin", "Access-Control-Allow-Methods",
"Access-Control-Allow-Headers", "Access-Control-Allow-Credentials", "X-Forwarded-For", "X-Real-IP",
"X-Csrf-Token", "X-HTTP-Method-Override",
},
AllowCredentials: true,
})
serverHandler := c.Handler(a.router)
a.server = &http.Server{
Addr: a.listenAddr,
Handler: serverHandler,
}
fmt.Println(FmtBlue("Servidor iniciado na porta: " + a.listenAddr))
go func() {
if err := a.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(FmtRed("Erro ao iniciar servidor: "), err)
}
log.Println(FmtYellow("Servidor parou de receber novas conexões"))
}()
signchan := make(chan os.Signal, 1)
signal.Notify(signchan, syscall.SIGINT, syscall.SIGTERM)
<-signchan // vai esperar um comando que encerra o servidor
ctx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownRelease()
if err := a.server.Shutdown(ctx); err != nil {
log.Fatal(FmtRed("Erro ao desligar servidor: "), err)
}
fmt.Println(FmtYellow("Servidor encerrado na porta: " + a.listenAddr))
}
func NewAPIServer(listenAddr string, routeManager RouteManager) *APIServer {
router := mux.NewRouter()
return &APIServer{
listenAddr: listenAddr,
router: router,
globalMiddlewares: MiddlewareChain{},
routeManager: routeManager,
}
}
func defaultRouteManager() {
AddRoutes(nil, func() []RouteInfo {
return []RouteInfo{
{
Path: "/",
Method: MethodGet,
Handler: func(tc *TupaContext) error {
WriteJSONHelper(tc.Resp, http.StatusOK, "Seja bem vindo ao Tupã framework!")
return nil
},
},
}
})
}
func (a *APIServer) RegisterRoutes(routeInfos []RouteInfo) {
for _, routeInfo := range routeInfos {
if !AllowedMethods[routeInfo.Method] {
log.Fatalf(fmt.Sprintf(FmtRed("Método HTTP não permitido: "), "%s\nVeja como criar um novo método na documentação", routeInfo.Method))
}
handler := a.MakeHTTPHandlerFuncHelper(routeInfo)
a.router.HandleFunc(routeInfo.Path, handler).Methods(string(routeInfo.Method))
}
}
func WriteJSONHelper(w http.ResponseWriter, status int, v any) error {
if w == nil {
return errors.New("Response writer passado está nulo")
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(v)
}
func (a *APIServer) MakeHTTPHandlerFuncHelper(routeInfo RouteInfo) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := &TupaContext{
Req: r,
Resp: w,
Ctx: r.Context(),
}
// Combina middlewares globais com os especificos de rota
allMiddlewares := MiddlewareChain{}
allMiddlewares = append(allMiddlewares, a.globalMiddlewares...)
allMiddlewares = append(allMiddlewares, routeInfo.Middlewares...)
doneCh := a.executeMiddlewaresAsync(ctx, allMiddlewares)
errorsSlice := <-doneCh // espera até que algum valor seja recebido. Continua no primeiro erro recebido ( se houver ) ou se não houver nenhum erro
if len(errorsSlice) > 0 {
err := errorsSlice[0]
if apiErr, ok := err.(APIHandlerErr); ok {
slog.Error("API Error", "err:", apiErr, "status:", apiErr.Status)
WriteJSONHelper(w, apiErr.Status, APIError{Error: apiErr.Error()})
} else {
slog.Error("API Error", "err:", apiErr, "status:", apiErr.Status)
WriteJSONHelper(w, http.StatusInternalServerError, APIError{Error: err.Error()})
}
return
}
if r.Method == string(routeInfo.Method) {
err := routeInfo.Handler(ctx)
if err != nil {
if apiErr, ok := err.(APIHandlerErr); ok {
slog.Error("API Error", "err:", apiErr, "status:", apiErr.Status)
WriteJSONHelper(w, apiErr.Status, APIError{Error: apiErr.Error()})
} else {
WriteJSONHelper(w, http.StatusInternalServerError, APIError{Error: err.Error()})
}
}
} else {
WriteJSONHelper(w, http.StatusMethodNotAllowed, APIError{Error: "Método HTTP não permitido"})
}
allAfterMiddlewares := MiddlewareChain{}
allAfterMiddlewares = append(allAfterMiddlewares, routeInfo.AfterMiddlewares...)
allAfterMiddlewares = append(allAfterMiddlewares, a.globalAfterMiddlewares...)
doneCh = a.executeMiddlewaresAsync(ctx, allAfterMiddlewares)
errorsSlice = <-doneCh
if len(errorsSlice) > 0 {
err := errorsSlice[0]
if apiErr, ok := err.(APIHandlerErr); ok {
slog.Error("API Error", "err:", apiErr, "status:", apiErr.Status)
WriteJSONHelper(w, apiErr.Status, APIError{Error: apiErr.Error()})
} else {
slog.Error("API Error", "err:", apiErr, "status:", apiErr.Status)
WriteJSONHelper(w, http.StatusInternalServerError, APIError{Error: err.Error()})
}
return
}
}
}
func AddRoutes(groupMiddlewares MiddlewareChain, routeFuncs ...func() []RouteInfo) {
for _, routeFunc := range routeFuncs {
routes := routeFunc()
for i := range routes {
allMiddlewares := append(MiddlewareChain(nil), groupMiddlewares...)
routes[i].Middlewares = append(allMiddlewares, routes[i].Middlewares...)
}
allRoutes = append(allRoutes, routes...)
}
}
func GetRoutes() []RouteInfo {
routesCopy := make([]RouteInfo, len(allRoutes))
copy(routesCopy, allRoutes)
return routesCopy
}
func (tc *TupaContext) Request() *http.Request {
return tc.Req
}
func (tc *TupaContext) Response() http.ResponseWriter {
return tc.Resp
}
func (tc *TupaContext) SendString(s string) error {
_, err := tc.Resp.Write([]byte(s))
return err
}
func (tc *TupaContext) SetRequest(r *http.Request) {
tc.Req = r
}
func (tc *TupaContext) SetResponse(w http.ResponseWriter) {
tc.Resp = w
}
func (tc *TupaContext) Param(param string) string {
return mux.Vars(tc.Req)[param]
}
func (tc *TupaContext) QueryParam(param string) string {
return tc.Request().URL.Query().Get(param)
}
func (tc *TupaContext) QueryParams() map[string][]string {
return tc.Request().URL.Query()
}
func (tc *TupaContext) Params() map[string]string {
return mux.Vars(tc.Request())
}
func (tc *TupaContext) GetCtx() context.Context {
return tc.Ctx
}
func (tc *TupaContext) SetContext(ctx context.Context) {
tc.Ctx = ctx
}
func NewTupaContextWithContext(w http.ResponseWriter, r *http.Request, ctx context.Context) *TupaContext {
return &TupaContext{
Req: r,
Resp: w,
Ctx: ctx,
}
}
func (tc *TupaContext) CtxWithValue(key, value interface{}) *TupaContext {
newCtx := context.WithValue(tc.Ctx, key, value)
return NewTupaContextWithContext(tc.Resp, tc.Req, newCtx)
}
func (tc *TupaContext) CtxValue(key interface{}) interface{} {
return tc.Ctx.Value(key)
}
func NewTupaContext(req **http.Request, resp http.ResponseWriter, ctx context.Context) *TupaContext {
return &TupaContext{
Req: *req,
Resp: resp,
Ctx: ctx,
}
}