-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
327 lines (281 loc) · 7.38 KB
/
server.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
package goweb
import (
"bytes"
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"net/http/pprof"
"os"
"path"
"reflect"
"regexp"
"runtime"
"strconv"
"time"
)
type ServerConfig struct {
StaticDir string
CookieDomain string
CookieSecret string
RecoverPanic bool
Profiler bool
}
type Server struct {
Config *ServerConfig
routes []route
Logger *log.Logger
Env map[string]interface{}
l net.Listener
}
func NewServer(config *Config) *Server {
return &Server{
Config: &ServerConfig{
StaticDir: config.GetString("staticdir", ""),
CookieDomain: config.GetString("cookiedomain", ""),
CookieSecret: config.GetString("cookiesecret", ""),
RecoverPanic: config.GetBool("recoverpanic", true),
Profiler: config.GetBool("profiler", false),
},
Logger: log.New(os.Stdout, "", log.Ldate|log.Ltime),
Env: map[string]interface{}{},
}
}
func (s *Server) initServer() {
runtime.GOMAXPROCS(runtime.NumCPU())
if s.Config == nil {
s.Config = &ServerConfig{}
}
if s.Logger == nil {
s.Logger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
}
}
type route struct {
r string
cr *regexp.Regexp
method string
handler reflect.Value
}
func (s *Server) addRoute(r string, method string, handler interface{}) {
cr, err := regexp.Compile(r)
if err != nil {
s.Logger.Printf("Error in route regex %q\n", r)
return
}
if fv, ok := handler.(reflect.Value); ok {
s.routes = append(s.routes, route{r, cr, method, fv})
} else {
fv := reflect.ValueOf(handler)
s.routes = append(s.routes, route{r, cr, method, fv})
}
}
func (s *Server) ServeHTTP(c http.ResponseWriter, req *http.Request) {
s.Process(c, req)
}
func (s *Server) Process(c http.ResponseWriter, req *http.Request) {
s.routeHandler(req, c)
}
func (s *Server) Get(route string, handler interface{}) {
s.addRoute(route, "GET", handler)
}
func (s *Server) Post(route string, handler interface{}) {
s.addRoute(route, "POST", handler)
}
func (s *Server) Put(route string, handler interface{}) {
s.addRoute(route, "PUT", handler)
}
func (s *Server) Delete(route string, handler interface{}) {
s.addRoute(route, "DELETE", handler)
}
func (s *Server) Match(method string, route string, handler interface{}) {
s.addRoute(route, method, handler)
}
func (s *Server) Run(addr string) {
s.initServer()
mux := http.NewServeMux()
if s.Config.Profiler {
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
mux.Handle("/debug/pprof/heap", pprof.Handler("heap"))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
}
mux.Handle("/", s)
s.Logger.Printf("web.go serving %s\n", addr)
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
s.l = l
err = http.Serve(s.l, mux)
s.l.Close()
}
func (s *Server) RunFcgi(addr string) {
s.initServer()
s.Logger.Printf("web.go serving fcgi %s\n", addr)
s.listenAndServeFcgi(addr)
}
func (s *Server) RunScgi(addr string) {
s.initServer()
s.Logger.Printf("web.go serving scgi %s\n", addr)
s.listenAndServeScgi(addr)
}
func (s *Server) RunTLS(addr string, config *tls.Config) error {
s.initServer()
mux := http.NewServeMux()
mux.Handle("/", s)
l, err := tls.Listen("tcp", addr, config)
if err != nil {
log.Fatal("Listen:", err)
return err
}
s.l = l
return http.Serve(s.l, mux)
}
func (s *Server) Close() {
if s.l != nil {
s.l.Close()
}
}
func (s *Server) safelyCall(function reflect.Value, args []reflect.Value) (resp []reflect.Value, e interface{}) {
defer func() {
if err := recover(); err != nil {
if !s.Config.RecoverPanic {
// go back to panic
panic(err)
} else {
e = err
resp = nil
s.Logger.Println("Handler crashed with error", err)
for i := 1; ; i += 1 {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
s.Logger.Println(file, line)
}
}
}
}()
return function.Call(args), nil
}
func requiresContext(handlerType reflect.Type) bool {
//if the method doesn't take arguments, no
if handlerType.NumIn() == 0 {
return false
}
//if the first argument is not a pointer, no
a0 := handlerType.In(0)
if a0.Kind() != reflect.Ptr {
return false
}
//if the first argument is a context, yes
if a0.Elem() == contextType {
return true
}
return false
}
func (s *Server) tryServingFile(name string, req *http.Request, w http.ResponseWriter) bool {
//try to serve a static file
if s.Config.StaticDir != "" {
staticFile := path.Join(s.Config.StaticDir, name)
if fileExists(staticFile) {
http.ServeFile(w, req, staticFile)
return true
}
} else {
for _, staticDir := range defaultStaticDirs {
staticFile := path.Join(staticDir, name)
if fileExists(staticFile) {
http.ServeFile(w, req, staticFile)
return true
}
}
}
return false
}
// the main route handler in web.go
func (s *Server) routeHandler(req *http.Request, w http.ResponseWriter) {
requestPath := req.URL.Path
ctx := Context{req, map[string]string{}, s, w}
//log the request
var logEntry bytes.Buffer
fmt.Fprintf(&logEntry, "\033[32;1m%s %s\033[0m", req.Method, requestPath)
//ignore errors from ParseForm because it's usually harmless.
req.ParseForm()
if len(req.Form) > 0 {
for k, v := range req.Form {
ctx.Params[k] = v[0]
}
fmt.Fprintf(&logEntry, "\n\033[37;1mParams: %v\033[0m\n", ctx.Params)
}
ctx.Server.Logger.Print(logEntry.String())
//set some default headers
ctx.SetHeader("Server", "goweb", true)
tm := time.Now().UTC()
ctx.SetHeader("Date", webTime(tm), true)
if req.Method == "GET" || req.Method == "HEAD" {
if s.tryServingFile(requestPath, req, w) {
return
}
}
//Set the default content-type
ctx.SetHeader("Content-Type", "text/html; charset=utf-8", true)
for i := 0; i < len(s.routes); i++ {
route := s.routes[i]
cr := route.cr
//if the methods don't match, skip this handler (except HEAD can be used in place of GET)
if req.Method != route.method && !(req.Method == "HEAD" && route.method == "GET") {
continue
}
if !cr.MatchString(requestPath) {
continue
}
match := cr.FindStringSubmatch(requestPath)
if len(match[0]) != len(requestPath) {
continue
}
var args []reflect.Value
handlerType := route.handler.Type()
if requiresContext(handlerType) {
args = append(args, reflect.ValueOf(&ctx))
}
for _, arg := range match[1:] {
args = append(args, reflect.ValueOf(arg))
}
ret, err := s.safelyCall(route.handler, args)
if err != nil {
//there was an error or panic while calling the handler
ctx.Abort(500, "Server Error")
}
if len(ret) == 0 {
return
}
sval := ret[0]
var content []byte
if sval.Kind() == reflect.String {
content = []byte(sval.String())
} else if sval.Kind() == reflect.Slice && sval.Type().Elem().Kind() == reflect.Uint8 {
content = sval.Interface().([]byte)
}
ctx.SetHeader("Content-Length", strconv.Itoa(len(content)), true)
_, err = ctx.ResponseWriter.Write(content)
if err != nil {
ctx.Server.Logger.Println("Error during write: ", err)
}
return
}
// try serving index.html or index.htm
if req.Method == "GET" || req.Method == "HEAD" {
if s.tryServingFile(path.Join(requestPath, "index.html"), req, w) {
return
} else if s.tryServingFile(path.Join(requestPath, "index.htm"), req, w) {
return
}
}
ctx.Abort(404, "Page not found")
}
// SetLogger sets the logger for server s
func (s *Server) SetLogger(logger *log.Logger) {
s.Logger = logger
}