summaryrefslogtreecommitdiff
path: root/engine.go
blob: 4d44fa17128a470ed927b60f5cfae1bdf70c909f (plain)
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
package growel

import (
	"net/http"
)

// create API engine

func New() *Engine {
	var a Engine
	a.router = NewRouter()
	return &a
}

// add routes

func (api *Engine) GET(path string, h Handler) {
	api.router.Add("GET", path, h)
}

func (api *Engine) POST(path string, h Handler) {
	api.router.Add("POST", path, h)
}

func (api *Engine) PUT(path string, h Handler) {
	api.router.Add("PUT", path, h)
}

func (api *Engine) DELETE(path string, h Handler) {
	api.router.Add("DELETE", path, h)
}

// serve and start

func (a *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	handler, params := a.router.Find(req.Method, req.URL.Path)
	if handler == nil {
		http.NotFound(w, req)
		return
	}

	err := req.ParseForm()
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	handler(&Context{
		W:      w,
		R:      req,
		Params: params,
		Querys: req.URL.Query(),
		Form:   req.Form,
	})
}

func (api *Engine) Start(port string) {
	http.ListenAndServe(port, api)
}