-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkernel.go
executable file
·69 lines (59 loc) · 1.56 KB
/
kernel.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
package pig
import (
"fmt"
"github.com/gorilla-go/pig/di"
"github.com/gorilla-go/pig/foundation/constant"
"log"
"net/http"
"runtime/debug"
)
type Kernel struct {
middleware []IMiddleware
router IRouter
context *Context
}
func NewKernel(r IRouter) *Kernel {
return &Kernel{
router: r,
context: NewContext(),
}
}
func (k *Kernel) Through(middleware []IMiddleware) *Kernel {
k.middleware = middleware
return k
}
func (k *Kernel) Handle(w http.ResponseWriter, req *http.Request) {
defer func() {
if errno := recover(); errno != nil {
errorHandler, err := di.Invoke[IHttpErrorHandler](k.context.Container())
if err != nil {
log.Println(fmt.Sprintf("%s\n\r%s", errno, string(debug.Stack())))
w.WriteHeader(http.StatusInternalServerError)
return
}
errorHandler.Handle(errno, k.context)
return
}
}()
if k.router == nil {
panic("router unset.")
}
controllerAction, routerParams, cusMiddleware := k.router.Route(req.URL.Path, constant.RequestMethod(req.Method))
if controllerAction == nil {
w.WriteHeader(http.StatusNotFound)
return
}
if cusMiddleware != nil {
k.middleware = cusMiddleware
}
container := k.context.Container()
di.ProvideValue[*Context](container, k.context)
di.ProvideValue[IRouter](container, k.router)
di.ProvideValue[*Request](container, NewRequest(req, routerParams))
di.ProvideValue[*Response](container, NewResponse(w, req))
pipeline := NewPipeline[*Context]().Send(k.context)
for _, middleware := range k.middleware {
pipeline.Through(middleware.Handle)
}
pipeline.Then(controllerAction)
}