-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux.go
66 lines (53 loc) · 1.36 KB
/
mux.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
package routers
import (
"context"
"net/http"
"reflect"
"strings"
"github.com/KejawenLab/bima/v3/loggers"
"github.com/KejawenLab/bima/v3/routes"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
)
type MuxRouter struct {
Debug bool
routes []routes.Route
}
func (m *MuxRouter) Register(muxs []routes.Route) {
for _, mux := range muxs {
m.Add(mux)
}
}
func (m *MuxRouter) Add(route routes.Route) {
m.routes = append(m.routes, route)
}
func (m *MuxRouter) Handle(context context.Context, server *runtime.ServeMux, client *grpc.ClientConn) {
for _, v := range m.routes {
route := v
route.SetClient(client)
server.HandlePath(route.Method(), route.Path(), func(w http.ResponseWriter, r *http.Request, params map[string]string) {
if !m.Debug {
for _, middleware := range route.Middlewares() {
if stop := middleware.Attach(r, w); stop {
return
}
}
route.Handle(w, r, params)
return
}
for _, middleware := range route.Middlewares() {
if stop := middleware.Attach(r, w); stop {
var stopper strings.Builder
stopper.WriteString("middleware stopped by: ")
stopper.WriteString(reflect.TypeOf(middleware).Elem().Name())
loggers.Logger.Debug(context, stopper.String())
return
}
}
route.Handle(w, r, params)
})
}
}
func (m *MuxRouter) Priority() int {
return -255
}