-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeegin.go
53 lines (43 loc) · 1.07 KB
/
beegin.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
package beegin
import (
"fmt"
"net/http"
)
type (
HandlerFunc func(*Context) error
routerMap map[string]HandlerFunc
Engine struct {
router *router
DefaultErrorHandlerFunc HandlerFunc
}
)
func New() *Engine {
return &Engine{
router: newRouter(),
DefaultErrorHandlerFunc:
defaultErrorHandlerFunc,
}
}
func defaultErrorHandlerFunc(c *Context) error {
return c.String(http.StatusNotFound, fmt.Errorf("404 Not Found"))
}
func (e *Engine) GET(pattern string, h HandlerFunc) {
e.router.addRoute(http.MethodGet, pattern, h)
}
func (e *Engine) POST(pattern string, h HandlerFunc) {
e.router.addRoute(http.MethodPost, pattern, h)
}
func (e *Engine) Run(ip string, port int) error {
fmt.Printf("=> listen on %s port %d\n", ip, port)
return http.ListenAndServe(fmt.Sprintf("%s:%d", ip, port), e)
}
func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
c := newContext(w, req)
e.router.handle(c)
}
func (e *Engine) WrapHandler(h http.Handler) HandlerFunc {
return func(c *Context) error {
h.ServeHTTP(c.Writer, c.Req)
return nil
}
}