-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
82 lines (54 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package happyngine
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
type Router struct {
Routes []*Route
}
func (this *Router) AddRoute(route *Route) {
this.Routes = append(this.Routes, route)
}
func getMimeType(req *http.Request) string {
return req.Header.Get("Content-Type")
}
func parseJsonBody(req *http.Request) {
body, _ := ioutil.ReadAll(req.Body)
bodyMap := make(map[string]interface{})
json.Unmarshal(body, &bodyMap)
for k, v := range bodyMap {
req.Form.Add(k, fmt.Sprintf("%v", v))
}
}
func (this *Router) parseRequestParams(req *http.Request, route *Route, matches []string) {
// This will create the req.Form object
req.ParseForm()
mime := getMimeType(req)
// Handle json input data
if strings.Index(mime, "application/json") != -1 {
parseJsonBody(req)
}
if len(matches) > 0 && matches[0] == req.URL.Path {
for i, name := range route.Path.SubexpNames() {
if len(name) > 0 {
req.Form.Add(name, matches[i])
}
}
}
}
func (this *Router) FindRoute(req *http.Request) (*Route, error) {
for _, r := range this.Routes {
if r.Method == req.Method {
matches := r.Path.FindStringSubmatch(req.URL.Path)
if matches != nil {
this.parseRequestParams(req, r, matches)
return r, nil
}
}
}
return nil, errors.New("No route")
}