-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.go
65 lines (53 loc) · 1.31 KB
/
router.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
package ming
import (
"log"
"strings"
"github.com/valyala/fasthttp"
)
var (
DefaultContentType = []byte("text/plain; charset=utf-8")
)
type Router struct {
trees *Tree
PanicHandler func(*fasthttp.RequestCtx, interface{})
NotFound fasthttp.RequestHandler
MethodNotAllowed fasthttp.RequestHandler
}
func New() *Router {
tree := new(Tree)
return &Router{
trees: tree,
}
}
type HostSwitch map[string]fasthttp.RequestHandler
func (hs HostSwitch) CheckHost(ctx *fasthttp.RequestCtx) {
if handler := hs[string(ctx.Host())]; handler != nil {
handler(ctx)
} else {
ctx.Error("Forbidden", fasthttp.StatusForbidden)
}
}
func (r *Router) Run(addr string) {
if strings.HasPrefix(addr, ":") {
log.Fatal(fasthttp.ListenAndServe(addr, r.Handler))
} else {
port := ":" + strings.Split(addr, ":")[1]
hs := make(HostSwitch)
hs[addr] = r.Handler
log.Fatal(fasthttp.ListenAndServe(port, hs.CheckHost))
}
}
func Query(ctx *fasthttp.RequestCtx, str string) []byte {
return ctx.QueryArgs().Peek(str)
}
func SetHeader(ctx *fasthttp.RequestCtx, key string, value string) {
ctx.Response.Header.Set(key, value)
}
func Body(ctx *fasthttp.RequestCtx) []byte {
return ctx.Request.Body()
}
func (r *Router) recv(ctx *fasthttp.RequestCtx) {
if rcv := recover(); rcv != nil {
r.PanicHandler(ctx, rcv)
}
}