-
Notifications
You must be signed in to change notification settings - Fork 5
/
http_rest.go
91 lines (79 loc) · 2.13 KB
/
http_rest.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
package nimo
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
const (
HttpGet = "GET"
HttpPost = "POST"
HttpUpdate = "UPDATE"
)
type HttpRestProvider struct {
controller map[HttpURL][]HandlerFunc
port int
serverMux *http.ServeMux
}
type HandlerFunc func(body []byte) interface{}
type HttpURL struct {
Uri string
Method string
}
func NewHttpRestProvider(port int) *HttpRestProvider {
return &HttpRestProvider{
controller: make(map[HttpURL][]HandlerFunc, 512),
port: port,
serverMux: http.NewServeMux(),
}
}
func (rest *HttpRestProvider) Listen() error {
for web, handlerList := range rest.controller {
rest.register(web, handlerList)
}
// list overall registered http resource and uri
rest.register(HttpURL{"/", HttpGet}, []HandlerFunc{func(body []byte) interface{} {
var maps []HttpURL
for contr := range rest.controller {
maps = append(maps, contr)
}
return maps
}})
return http.ListenAndServe(fmt.Sprintf(":%d", rest.port), rest.serverMux)
}
func (rest *HttpRestProvider) RegisterAPI(url string, method string, handler func(body []byte) interface{}) {
// http root url is responsible for show registered handlers
if len(url) == 0 || url == "/" {
return
}
identifier := HttpURL{Uri: url, Method: method}
if _, exist := rest.controller[identifier]; exist {
rest.controller[identifier] = append(rest.controller[identifier], handler)
} else {
rest.controller[identifier] = []HandlerFunc{handler}
}
}
func (rest *HttpRestProvider) register(web HttpURL, handlerList []HandlerFunc) {
rest.serverMux.HandleFunc(web.Uri, func(w http.ResponseWriter, req *http.Request) {
if strings.ToUpper(req.Method) != strings.ToUpper(web.Method) {
return
}
// read full body content
body, _ := ioutil.ReadAll(req.Body)
var v []byte
var response interface{}
if len(handlerList) == 1 {
response = handlerList[0](body)
} else {
var results []interface{}
// aggregate all results if multi-controller register
for _, handler := range handlerList {
results = append(results, handler(body))
}
response = results
}
v, _ = json.Marshal(response)
w.Write(v)
})
}