-
Notifications
You must be signed in to change notification settings - Fork 12
/
hera.go
118 lines (95 loc) · 2.46 KB
/
hera.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
package hera
import (
"fmt"
"net/http"
"runtime"
)
type Handler interface {
ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}
type HandlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
func (h HandlerFunc) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
h(rw, r, next)
}
type middleware struct {
handler Handler
next *middleware
}
func (m middleware) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
m.handler.ServeHTTP(rw, r, m.next.ServeHTTP)
}
func Wrap(handler http.Handler) Handler {
return HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
handler.ServeHTTP(rw, r)
next(rw, r)
})
}
type hera struct {
middleware middleware
handlers []Handler
}
func New(handlers ...Handler) *hera {
return &hera{
handlers: handlers,
middleware: build(handlers),
}
}
func classic() *hera {
return New(NewRecovery(), Logger)
}
func Run(confPath string) {
fmt.Println("hera start runing")
initEnv(confPath)
startServ()
}
func initEnv(confPath string) {
config := NewConfig(confPath)
MakeServerVar(config)
NewLogger(SERVER["PRJ_NAME"], 1)
}
func startServ() {
runtime.GOMAXPROCS(runtime.NumCPU())
n := classic()
n.Run(SERVER["SVC_PORT"])
}
func (n *hera) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
n.middleware.ServeHTTP(NewResponseWriter(rw), r)
}
func (n *hera) Use(handler Handler) {
n.handlers = append(n.handlers, handler)
n.middleware = build(n.handlers)
}
func (n *hera) UseFunc(handlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {
n.Use(HandlerFunc(handlerFunc))
}
func (n *hera) UseHandler(handler http.Handler) {
n.Use(Wrap(handler))
}
func (n *hera) UseHandlerFunc(handlerFunc func(rw http.ResponseWriter, r *http.Request)) {
n.UseHandler(http.HandlerFunc(handlerFunc))
}
func (n *hera) Run(addr string) {
n.UseHandler(NewRouter())
Logger.Info(fmt.Sprintf("listening on %v", addr))
http.ListenAndServe(addr, n)
}
func (n *hera) Handlers() []Handler {
return n.handlers
}
func build(handlers []Handler) middleware {
var next middleware
if len(handlers) == 0 {
return voidMiddleware()
} else if len(handlers) > 1 {
next = build(handlers[1:])
} else {
next = voidMiddleware()
}
return middleware{handlers[0], &next}
}
func voidMiddleware() middleware {
return middleware{
HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {}),
&middleware{},
}
}