-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
93 lines (81 loc) · 2.47 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
package mano
import (
"net/http"
"os"
"strings"
"github.com/junhwong/mano/logs"
)
func resolveAddress(addr []string) string {
switch len(addr) {
case 0:
if port := os.Getenv("PORT"); len(port) > 0 {
//debugPrint("Environment variable PORT=\"%s\"", port)
return ":" + port
}
//debugPrint("Environment variable PORT is undefined. Using port :8080 by default")
return ":8080"
case 1:
return addr[0]
default:
panic("too much parameters")
}
}
func (app *Application) onServe() {
app.muLock.Lock()
defer app.muLock.Unlock()
if !app.isDefault {
return
}
// for _, r := range DefaultRoutes.items {
// pattern := regexp.MustCompile(compilePattern(r.pattern))
// handler := buildHandler(r.handler)
// app.routeTable.Register(pattern, handler, 0, false)
// }
// route, err := defaultRoutes["0"].Route()
// if err != nil {
// panic(err)
// }
// app.routeTable.routes.PushFront(route)
}
// ServeHTTP is implements for http.Handler interface
func (app *Application) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if !strings.HasPrefix(request.URL.Path, "/") {
request.URL.Path = "/" + request.URL.Path
}
complated := false
var err error
logs.Debug("%s %s", request.Method, request.URL)
for _, handler := range app.handlers {
complated, err = handler.Handle(writer, request)
if err != nil {
logs.Error(err) //TODO:
return
}
if complated {
return
}
}
if !complated {
writer.WriteHeader(404)
}
}
// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (app *Application) Run(addr ...string) (err error) {
app.onServe()
defer func() { logs.Debug(err) }()
address := resolveAddress(addr)
logs.Info("Listening and serving HTTP on %s", address)
http.ListenAndServe(address, app)
return
}
// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
// func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
// //debugPrint("Listening and serving HTTPS on %s\n", addr)
// //defer func() { debugPrintError(err) }()
// err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
// return
// }