-
Notifications
You must be signed in to change notification settings - Fork 12
/
ripple.go
345 lines (288 loc) · 8.21 KB
/
ripple.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package ripple
import (
"encoding/json"
"log"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
)
// A context holds information about the current request and response.
// An object of type Context is passed to methods of a controller.
type Context struct {
// The parameters matched in the current URL. A parameter is defined
// in a route by prefixing it with a ":". For example, ":id", ":name".
Params map[string]string
// The actual HTTP request.
Request *http.Request
// The response object.
Response *Response
}
// Build a new context object.
func NewContext() *Context {
output := new(Context)
output.Params = make(map[string]string)
output.Response = NewResponse()
return output
}
// A Ripple application. Use NewApplication() to build it.
type Application struct {
controllers map[string]interface{}
routes []Route
contentType string
baseUrl string
parsedBaseUrl *url.URL
}
// Build a new application object.
func NewApplication() *Application {
output := new(Application)
output.controllers = make(map[string]interface{})
output.contentType = "application/json"
output.SetBaseUrl("/")
return output
}
// A route maps a URL pattern to a controller and action.
// See README.md for more information on the format of the pattern.
type Route struct {
Pattern string
Controller string
Action string
}
// Holds information about the HTTP response.
type Response struct {
// HTTP code (200, 404, etc.). Use the constants of the http package.
Status int
// The response body. It will be serialized automatically
// by the Ripple application before being sent to the client.
Body interface{}
}
// Build a new response object.
func NewResponse() *Response {
output := new(Response)
output.Body = nil
return output
}
// Helper struct used by `prepareServeHttpResponseData()`
type serveHttpResponseData struct {
Status int
Body string
}
func defaultHttpStatus(method string) int {
output := http.StatusOK
if method == "POST" {
output = http.StatusCreated
}
return output
}
// Sets the base URL (default to "/"). The base URL will
// be stripped from the beginning of the request URL. For
// instance if the base URL is "/api/" and the client does
// a request on "/api/images/1", the application will dispatch
// "images/1". Specifying the full URL (with domain, etc.) is
// not necessary.
func (this *Application) SetBaseUrl(v string) {
this.baseUrl = v
var err error
this.parsedBaseUrl, err = url.Parse(this.baseUrl)
if err != nil {
log.Panicf("Invalid base URL: %s", this.baseUrl)
}
}
// Returns the base URL.
func (this *Application) BaseUrl() string {
return this.baseUrl
}
// Helper function to prepare the response writter data for `ServeHTTP()`
func (this *Application) prepareServeHttpResponseData(context *Context) serveHttpResponseData {
var statusCode int
var body string
var err error
if context == nil {
statusCode = http.StatusNotFound
} else {
statusCode = context.Response.Status
}
if context != nil {
body, err = this.serializeResponseBody(context.Response.Body)
if err != nil {
statusCode = http.StatusInternalServerError
}
}
var output serveHttpResponseData
output.Status = statusCode
output.Body = body
return output
}
// Serves an HTTP request - implementation of net.http.ServeHTTP
func (this *Application) ServeHTTP(writter http.ResponseWriter, request *http.Request) {
context := this.Dispatch(request)
r := this.prepareServeHttpResponseData(context)
writter.Header().Set("Content-Type", this.contentType)
writter.WriteHeader(r.Status)
writter.Write([]byte(r.Body))
}
func (this *Application) serializeResponseBody(body interface{}) (string, error) {
if body == nil {
return "", nil
}
var output string
var err error
err = nil
switch body.(type) {
case string:
output = body.(string)
case int, int8, int16, int32, int64:
output = strconv.Itoa(body.(int))
case uint, uint8, uint16, uint32, uint64:
output = strconv.FormatUint(body.(uint64), 10)
case float32, float64:
output = strconv.FormatFloat(body.(float64), 'f', -1, 64)
case bool:
if body.(bool) {
output = "true"
} else {
output = "false"
}
default:
contentType := this.contentType
if contentType != "application/json" { // Currently, only JSON is supported
log.Printf("Unsupported content type: %s! Defaulting to application/json.", this.contentType)
contentType = "application/json"
}
if contentType == "application/json" {
var b []byte
b, err = json.Marshal(body)
output = string(b)
}
}
return output, err
}
func (this *Application) checkRoute(route Route) {
if route.Controller != "" {
_, exists := this.controllers[route.Controller]
if !exists {
log.Panicf("\"%s\" controller does not exist.\n", route.Controller)
}
}
}
// Registers a controller. The name should be the same as in the URL path. For example
// if the URL is "users/1", the name should be "users". The controller itself can be
// any struct that implements HTTP method handlers. See README.md and the demo for more
// details on the structure of a controller.
func (this *Application) RegisterController(name string, controller interface{}) {
this.controllers[name] = controller
}
// Add a route to the application.
func (this *Application) AddRoute(route Route) {
this.checkRoute(route)
this.routes = append(this.routes, route)
}
func splitPath(path string) []string {
var output []string
if len(path) == 0 {
return output
}
if path[0] == '/' {
path = path[1:]
}
pathTokens := strings.Split(path, "/")
for i := 0; i < len(pathTokens); i++ {
e := pathTokens[i]
if len(e) > 0 {
output = append(output, e)
}
}
return output
}
func makeMethodName(requestMethod string, actionName string) string {
return strings.Title(strings.ToLower(requestMethod)) + strings.Title(actionName)
}
// Provided for debugging/testing purposes only.
type MatchRequestResult struct {
Success bool
ControllerName string
ActionName string
ControllerValue reflect.Value
ControllerMethod reflect.Value
MatchedRoute Route
Params map[string]string
}
func (this *Application) matchRequest(request *http.Request) MatchRequestResult {
var output MatchRequestResult
output.Success = false
path := request.URL.Path
path = path[len(this.parsedBaseUrl.Path):len(path)]
pathTokens := splitPath(path)
for routeIndex := 0; routeIndex < len(this.routes); routeIndex++ {
route := this.routes[routeIndex]
patternTokens := splitPath(route.Pattern)
if len(patternTokens) != len(pathTokens) {
continue
}
var controller interface{}
var exists bool
controllerName := ""
actionName := ""
notMatched := false
params := make(map[string]string)
for i := 0; i < len(patternTokens); i++ {
patternToken := patternTokens[i]
pathToken := pathTokens[i]
if patternToken == ":_controller" {
controllerName = pathToken
} else if patternToken == ":_action" {
actionName = pathToken
} else if patternToken == pathToken {
} else if patternToken[0] == ':' {
params[patternToken[1:]] = pathToken
} else {
notMatched = true
break
}
}
if notMatched {
continue
}
if controllerName == "" {
controllerName = route.Controller
}
if actionName == "" {
actionName = route.Action
}
controller, exists = this.controllers[controllerName]
if !exists {
continue
}
methodName := makeMethodName(request.Method, actionName)
controllerVal := reflect.ValueOf(controller)
controllerMethod := controllerVal.MethodByName(methodName)
if !controllerMethod.IsValid() {
continue
}
output.Success = true
output.ControllerName = controllerName
output.ActionName = actionName
output.ControllerValue = controllerVal
output.ControllerMethod = controllerMethod
output.MatchedRoute = route
output.Params = params
}
return output
}
// Provided for debugging/testing purposes only.
func (this *Application) Dispatch(request *http.Request) *Context {
r := this.matchRequest(request)
if !r.Success {
log.Printf("No match for: %s %s\n", request.Method, request.URL)
return nil
}
ctx := NewContext()
ctx.Request = request
ctx.Params = r.Params
ctx.Response.Status = defaultHttpStatus(request.Method)
var args []reflect.Value
args = append(args, reflect.ValueOf(ctx))
r.ControllerMethod.Call(args)
return ctx
}