-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorest.go
331 lines (293 loc) · 8.91 KB
/
gorest.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//Copyright 2011 Siyabonga Dlamini ([email protected]). All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
//THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
//IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
//OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
//OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
//ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package gorest
import (
"log"
"net/http"
"net/url"
"runtime/debug"
"strconv"
"strings"
)
type GoRestService interface {
ResponseBuilder() *ResponseBuilder
}
const (
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
PATCH = "PATCH"
)
type endPointStruct struct {
name string
requestMethod string
signiture string
muxRoot string
root string
nonParamPathPart map[int]string
params []param //path parameter name and position
queryParams []param
signitureLen int
paramLen int
inputMime string
outputType string
outputTypeIsArray bool
outputTypeIsMap bool
postdataType string
postdataTypeIsArray bool
postdataTypeIsMap bool
isVariableLength bool
parentTypeName string
methodNumberInParent int
role string
}
type restStatus struct {
httpCode int
reason string //Especially for code in range 4XX to 5XX
}
func (err restStatus) String() string {
return err.reason
}
type serviceMetaData struct {
template interface{}
consumesMime string
producesMime string
root string
realm string
}
var restManager *manager
var handlerInitialised bool
type manager struct {
serviceTypes map[string]serviceMetaData
endpoints map[string]endPointStruct
}
func newManager() *manager {
man := new(manager)
man.serviceTypes = make(map[string]serviceMetaData, 0)
man.endpoints = make(map[string]endPointStruct, 0)
return man
}
func init() {
RegisterMarshaller(Application_Json, NewJSONMarshaller())
}
//Registeres a service on the rootpath.
//See example below:
//
// package main
// import (
// "code.google.com/p/gorest"
// "http"
// )
// func main() {
// gorest.RegisterService(new(HelloService)) //Register our service
// http.Handle("/",gorest.Handle())
// http.ListenAndServe(":8787",nil)
// }
//
// //Service Definition
// type HelloService struct {
// gorest.RestService `root:"/tutorial/"`
// helloWorld gorest.EndPoint `method:"GET" path:"/hello-world/" output:"string"`
// sayHello gorest.EndPoint `method:"GET" path:"/hello/{name:string}" output:"string"`
// }
// func(serv HelloService) HelloWorld() string{
// return "Hello World"
// }
// func(serv HelloService) SayHello(name string) string{
// return "Hello " + name
// }
func RegisterService(h interface{}) {
RegisterServiceOnPath("", h)
}
//Registeres a service under the specified path.
//See example below:
//
// package main
// import (
// "code.google.com/p/gorest"
// "http"
// )
// func main() {
// gorest.RegisterServiceOnPath("/rest/",new(HelloService)) //Register our service
// http.Handle("/",gorest.Handle())
// http.ListenAndServe(":8787",nil)
// }
//
// //Service Definition
// type HelloService struct {
// gorest.RestService `root:"/tutorial/"`
// helloWorld gorest.EndPoint `method:"GET" path:"/hello-world/" output:"string"`
// sayHello gorest.EndPoint `method:"GET" path:"/hello/{name:string}" output:"string"`
// }
// func(serv HelloService) HelloWorld() string{
// return "Hello World"
// }
// func(serv HelloService) SayHello(name string) string{
// return "Hello " + name
// }
func RegisterServiceOnPath(root string, h interface{}) {
//We only initialise the handler management once we know gorest is being used to hanlde request as well, not just client.
if !handlerInitialised {
restManager = newManager()
handlerInitialised = true
}
if root == "/" {
root = ""
}
if root != "" {
root = strings.Trim(root, "/")
root = "/" + root
}
registerService(root, h)
}
//ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.
func (_ manager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
url_, err := url.QueryUnescape(r.URL.RequestURI())
defer func() {
if rec := recover(); rec != nil {
//log.Println("Internal Server Error: Could not serve page: ", r.Method, url_)
log.Println(rec)
log.Printf("%s", debug.Stack())
w.WriteHeader(http.StatusInternalServerError)
}
}()
if err != nil {
//log.Println("Could not serve page: ", r.Method, r.URL.RequestURI(), "Error:", err)
w.WriteHeader(400)
w.Write([]byte("Client sent bad request."))
return
}
if ep, args, queryArgs, xsrft, found := getEndPointByUrl(r.Method, url_); found {
ctx := new(Context)
ctx.writer = w
ctx.request = r
ctx.args = args
ctx.queryArgs = queryArgs
ctx.xsrftoken = xsrft
data, state := prepareServe(ctx, ep)
if state.httpCode == http.StatusOK {
switch ep.requestMethod {
case POST, PUT, DELETE, HEAD, OPTIONS, PATCH:
{
if ctx.responseCode == 0 {
w.WriteHeader(getDefaultResponseCode(ep.requestMethod))
} else {
if !ctx.dataHasBeenWritten {
w.WriteHeader(ctx.responseCode)
}
}
}
case GET:
{
if ctx.responseCode == 0 {
if !ctx.responseMimeSet {
w.Header().Set("Content-Type", _manager().getType(ep.parentTypeName).producesMime)
}
w.WriteHeader(getDefaultResponseCode(ep.requestMethod))
} else {
if !ctx.dataHasBeenWritten {
if !ctx.responseMimeSet {
w.Header().Set("Content-Type", _manager().getType(ep.parentTypeName).producesMime)
}
w.WriteHeader(ctx.responseCode)
}
}
if !ctx.overide {
w.Write(data)
}
}
}
} else {
//log.Println("Problem with request. Error:", r.Method, state.httpCode, state.reason, "; Request: ", r.URL.RequestURI())
w.WriteHeader(state.httpCode)
w.Write([]byte(state.reason))
}
} else {
//log.Println("Could not serve page, path not found: ", r.Method, url_)
// println("Could not serve page, path not found: ", r.Method, url_)
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("The resource in the requested path could not be found."))
}
}
func (man *manager) getType(name string) serviceMetaData {
return man.serviceTypes[name]
}
func (man *manager) addType(name string, i serviceMetaData) string {
for str, _ := range man.serviceTypes {
if name == str {
return str
}
}
man.serviceTypes[name] = i
return name
}
func (man *manager) addEndPoint(ep endPointStruct) {
man.endpoints[ep.requestMethod+":"+ep.signiture] = ep
}
//Registeres the function to be used for handling all requests directed to gorest.
func HandleFunc(w http.ResponseWriter, r *http.Request) {
//log.Println("Serving URL : ", r.Method, r.URL.RequestURI())
defer func() {
if rec := recover(); rec != nil {
log.Println("Internal Server Error: Could not serve page: ", r.Method, r.RequestURI)
log.Println(rec)
log.Printf("%s", debug.Stack())
w.WriteHeader(http.StatusInternalServerError)
}
}()
restManager.ServeHTTP(w, r)
}
//Runs the default "net/http" DefaultServeMux on the specified port.
//All requests are handled using gorest.HandleFunc()
func ServeStandAlone(port int) {
http.HandleFunc("/", HandleFunc)
http.ListenAndServe(":"+strconv.Itoa(port), nil)
}
func _manager() *manager {
return restManager
}
func Handle() manager {
return *restManager
}
func getDefaultResponseCode(method string) int {
switch method {
case GET, PUT, DELETE, PATCH:
{
return 200
}
case POST:
{
return 202
}
default:
{
return 200
}
}
return 200
}