forked from hoisie/web
/
web.go
283 lines (234 loc) · 7.62 KB
/
web.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
package web
import (
"bytes"
"http"
"io"
"io/ioutil"
"log"
"os"
"path"
"reflect"
"regexp"
"strings"
"template"
)
type Request http.Request
func (r *Request) ParseForm() (err os.Error) {
req := (*http.Request)(r)
return req.ParseForm()
}
type Response struct {
Status string
StatusCode int
Header map[string]string
Body io.Reader
}
func newResponse(statusCode int, body string) *Response {
text := statusText[statusCode]
resp := Response{StatusCode: statusCode,
Status: text,
Header: map[string]string{"Content-Type": "text/plain; charset=utf-8"},
}
if len(body) == 0 {
resp.Body = bytes.NewBufferString(text)
} else {
resp.Body = bytes.NewBufferString(body)
}
return &resp
}
type Context struct {
*Request
*Response
}
type Conn interface {
StartResponse(status int) os.Error
SetHeader(hdr string, val string) os.Error
WriteString(content string) os.Error
Close() os.Error
}
func (ctx *Context) Abort(code int, message string) {
ctx.Response = newResponse(code, message)
}
var contextType reflect.Type
var templateDir string
var staticDir string
func init() {
contextType = reflect.Typeof(Context{})
cwd := os.Getenv("PWD")
templateDir = path.Join(cwd, "templates")
staticDir = path.Join(cwd, "static")
}
type route struct {
r string
cr *regexp.Regexp
method string
handler *reflect.FuncValue
}
var routes = make(map[*regexp.Regexp]route)
func addRoute(r string, method string, handler interface{}) {
cr, err := regexp.Compile(r)
if err != nil {
log.Stderrf("Error in route regex %q\n", r)
return
}
fv := reflect.NewValue(handler).(*reflect.FuncValue)
routes[cr] = route{r, cr, method, fv}
}
func httpHandler(c *http.Conn, req *http.Request) {
path := req.URL.Path
//try to serve a static file
if strings.HasPrefix(path, "/static/") {
staticFile := path[8:]
if len(staticFile) > 0 {
http.ServeFile(c, req, "static/"+staticFile)
return
}
}
req.ParseForm()
resp := routeHandler((*Request)(req))
c.WriteHeader(resp.StatusCode)
if resp.Body != nil {
body, _ := ioutil.ReadAll(resp.Body)
c.Write(body)
}
}
func routeHandler(req *Request) *Response {
log.Stdout(req.RawURL)
path := req.URL.Path
ctx := Context{req, newResponse(200, "")}
for cr, route := range routes {
if !cr.MatchString(path) {
continue
}
match := cr.MatchStrings(path)
if len(match) > 0 {
if len(match[0]) != len(path) {
continue
}
if req.Method != route.method {
continue
}
ai := 0
handlerType := route.handler.Type().(*reflect.FuncType)
expectedIn := handlerType.NumIn()
args := make([]reflect.Value, expectedIn)
if expectedIn > 0 {
a0 := handlerType.In(0)
ptyp, ok := a0.(*reflect.PtrType)
if ok {
typ := ptyp.Elem()
if typ == contextType {
args[ai] = reflect.NewValue(&ctx)
ai += 1
expectedIn -= 1
}
}
}
actualIn := len(match) - 1
if expectedIn != actualIn {
log.Stderrf("Incorrect number of arguments for %s\n", path)
return newResponse(500, "")
}
for _, arg := range match[1:] {
args[ai] = reflect.NewValue(arg)
}
ret := route.handler.Call(args)[0].(*reflect.StringValue).Get()
var buf bytes.Buffer
buf.WriteString(ret)
resp := ctx.Response
resp.Body = &buf
return resp
}
}
return newResponse(404, "")
}
func render(tmplString string, context interface{}) (string, os.Error) {
var tmpl *template.Template
var err os.Error
if tmpl, err = template.Parse(tmplString, nil); err != nil {
return "", err
}
var buf bytes.Buffer
tmpl.Execute(context, &buf)
return buf.String(), nil
}
func Render(filename string, context interface{}) (string, os.Error) {
var templateBytes []uint8
var err os.Error
if !strings.HasPrefix(filename, "/") {
filename = path.Join(templateDir, filename)
}
if templateBytes, err = ioutil.ReadFile(filename); err != nil {
return "", err
}
return render(string(templateBytes), context)
}
func RenderString(tmplString string, context interface{}) (string, os.Error) {
return render(tmplString, context)
}
func Run(addr string) {
http.Handle("/", http.HandlerFunc(httpHandler))
log.Stdoutf("web.go serving %s", addr)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Exit("ListenAndServe:", err)
}
}
func RunScgi(addr string) {
log.Stdoutf("web.go serving scgi %s", addr)
listenAndServeScgi(addr)
}
func RunFcgi(addr string) {
log.Stdoutf("web.go serving fcgi %s", addr)
listenAndServeFcgi(addr)
}
func Get(route string, handler interface{}) { addRoute(route, "GET", handler) }
func Post(route string, handler interface{}) { addRoute(route, "POST", handler) }
func Head(route string, handler interface{}) { addRoute(route, "HEAD", handler) }
func Put(route string, handler interface{}) { addRoute(route, "PUT", handler) }
func Delete(route string, handler interface{}) {
addRoute(route, "DELETE", handler)
}
//copied from go's http package, because it's not public
var statusText = map[int]string{
http.StatusContinue: "Continue",
http.StatusSwitchingProtocols: "Switching Protocols",
http.StatusOK: "OK",
http.StatusCreated: "Created",
http.StatusAccepted: "Accepted",
http.StatusNonAuthoritativeInfo: "Non-Authoritative Information",
http.StatusNoContent: "No Content",
http.StatusResetContent: "Reset Content",
http.StatusPartialContent: "Partial Content",
http.StatusMultipleChoices: "Multiple Choices",
http.StatusMovedPermanently: "Moved Permanently",
http.StatusFound: "Found",
http.StatusSeeOther: "See Other",
http.StatusNotModified: "Not Modified",
http.StatusUseProxy: "Use Proxy",
http.StatusTemporaryRedirect: "Temporary Redirect",
http.StatusBadRequest: "Bad Request",
http.StatusUnauthorized: "Unauthorized",
http.StatusPaymentRequired: "Payment Required",
http.StatusForbidden: "Forbidden",
http.StatusNotFound: "Not Found",
http.StatusMethodNotAllowed: "Method Not Allowed",
http.StatusNotAcceptable: "Not Acceptable",
http.StatusProxyAuthRequired: "Proxy Authentication Required",
http.StatusRequestTimeout: "Request Timeout",
http.StatusConflict: "Conflict",
http.StatusGone: "Gone",
http.StatusLengthRequired: "Length Required",
http.StatusPreconditionFailed: "Precondition Failed",
http.StatusRequestEntityTooLarge: "Request Entity Too Large",
http.StatusRequestURITooLong: "Request URI Too Long",
http.StatusUnsupportedMediaType: "Unsupported Media Type",
http.StatusRequestedRangeNotSatisfiable: "Requested Range Not Satisfiable",
http.StatusExpectationFailed: "Expectation Failed",
http.StatusInternalServerError: "Internal Server Error",
http.StatusNotImplemented: "Not Implemented",
http.StatusBadGateway: "Bad Gateway",
http.StatusServiceUnavailable: "Service Unavailable",
http.StatusGatewayTimeout: "Gateway Timeout",
http.StatusHTTPVersionNotSupported: "HTTP Version Not Supported",
}