/
minirest.go
169 lines (142 loc) · 4.13 KB
/
minirest.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package minirest
import (
"log"
"net/http"
"reflect"
"strings"
"github.com/julienschmidt/httprouter"
)
// Minirest is singleton for Minirest framework
type Minirest struct {
services map[string]Service
controllers map[string]Controller
router *httprouter.Router
port string
ip string
}
type keyVal struct {
key string
val string
}
// New initiate new Minirest
func New() *Minirest {
return &Minirest{
services: make(map[string]Service),
controllers: make(map[string]Controller),
router: httprouter.New(),
}
}
// RunServer run http server
func (mn *Minirest) RunServer() {
var addr string
if mn.ip != "" {
addr += mn.ip
}
if mn.port != "" {
addr += ":" + mn.port
}
log.Fatal(http.ListenAndServe(addr, mn.router))
}
// ServeIP set http server IP
func (mn *Minirest) ServeIP(ip string) {
mn.ip = ip
}
// ServePort set http server port
func (mn *Minirest) ServePort(port string) {
mn.port = port
}
// AddService add service.
// Service must be pointer to struct
func (mn *Minirest) AddService(service Service) {
val := reflect.ValueOf(service)
service.Init()
servName := strings.Split(val.Type().String(), ".")
mn.services[servName[len(servName)-1]] = service
}
// AddController add controller.
// You can link services srv into controller, see Controller and AddService for more information.
// If service is not registered, it will automatically register it
func (mn *Minirest) AddController(controller Controller, srv ...Service) {
val := reflect.ValueOf(controller)
if val.Kind() == reflect.Ptr {
val = val.Elem()
} else {
val = reflect.New(val.Type()).Elem()
}
// if srv not nil, link services to controller
if srv != nil || len(srv) != 0 {
for _, s := range srv {
sname := strings.Split(reflect.ValueOf(s).Type().String(), ".")
snamestr := sname[len(sname)-1]
f := val.FieldByName(snamestr)
if !f.IsValid() {
panic(snamestr + " cannot be linked to controller: no match field exist")
}
if regsrv, ok := mn.services[snamestr]; ok {
f.Set(reflect.ValueOf(regsrv))
} else {
s.Init()
f.Set(reflect.ValueOf(s))
mn.AddService(s)
}
}
}
// call controller.Endpoints and register all endpoints
endpoints := controller.Endpoints()
for _, endpoint := range endpoints.endpoints {
method := strings.ToLower(endpoint.method)
var handle httprouter.Handle
if method == "get" || method == "delete" {
if endpoints.middleware != nil {
handle = endpoints.middleware.handleChain(handleWithoutBody(endpoint.callback))
} else {
handle = handleWithoutBody(endpoint.callback)
}
mn.router.Handle(endpoint.method, endpoints.basePath+endpoint.path, handle)
}
if method == "post" || method == "put" || method == "patch" {
if endpoints.middleware != nil {
handle = endpoints.middleware.handleChain(handleWithBody(endpoint.callback))
} else {
handle = handleWithBody(endpoint.callback)
}
mn.router.Handle(endpoint.method, endpoints.basePath+endpoint.path, handle)
}
}
ctrlName := strings.Split(val.Type().String(), ".")
mn.controllers[ctrlName[len(ctrlName)-1]] = controller
}
// CORS set CORS
func (mn *Minirest) CORS(opt CORSOption) {
mn.router.HandleMethodNotAllowed = true
mn.router.HandleOPTIONS = true
mn.router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Access-Control-Request-Method") != "" {
header := w.Header()
if opt.AllowOrigin != "" {
header.Add("Access-Control-Allow-Origin", opt.AllowOrigin)
}
if opt.AllowCredentials != "" {
header.Add("Access-Control-Allow-Credentials", opt.AllowCredentials)
}
if opt.ExposeHeaders != "" {
header.Add("Access-Control-Expose-Headers", opt.ExposeHeaders)
}
if opt.AllowHeaders != "" {
header.Add("Access-Control-Allow-Headers", opt.AllowHeaders)
}
if opt.AllowMethods != "" {
header.Add("Access-Control-Allow-Methods", opt.AllowMethods)
}
}
w.WriteHeader(http.StatusNoContent)
})
}
// CORSOption set options for CORS headers
type CORSOption struct {
AllowOrigin string
AllowCredentials string
ExposeHeaders string
AllowHeaders string
AllowMethods string
}