forked from eaciit/knot
/
webserver.go
196 lines (171 loc) · 4.61 KB
/
webserver.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
package knot
import (
"fmt"
"github.com/eaciit/toolkit"
"github.com/gorilla/mux"
"net/http"
"os"
"reflect"
"strings"
"time"
)
type Server struct {
Address string
mxrouter *mux.Router
log *toolkit.LogEngine
status chan string
}
func (s *Server) Log() *toolkit.LogEngine {
if s.log == nil {
s.log, _ = toolkit.NewLog(true, false, "", "", "")
}
return s.log
}
type FnContent func(r *Request) interface{}
func (s *Server) router() *mux.Router {
if s.mxrouter == nil {
s.mxrouter = mux.NewRouter()
}
return s.mxrouter
}
func (s *Server) Register(c interface{}, prefix string) error {
return s.RegisterWithConfig(c, prefix, NewResponseConfig())
}
func (s *Server) RegisterWithConfig(c interface{}, prefix string, cfg *ResponseConfig) error {
var t reflect.Type
v := reflect.ValueOf(c)
if v.Kind() != reflect.Ptr {
return fmt.Errorf("Invalid controller object passed (%s). Controller object should be a pointer", v.Kind())
}
t = reflect.TypeOf(c)
controllerName := reflect.Indirect(v).Type().Name()
s.Log().Info(fmt.Sprintf("Registering %s", controllerName))
path := prefix
fixUrlPath(&path, true, true)
controllerName = strings.ToLower(controllerName)
if strings.HasSuffix(controllerName, "controller") {
controllerName = controllerName[0 : len(controllerName)-len("controller")]
}
path += controllerName + "/"
if t == nil {
}
methodCount := t.NumMethod()
for mi := 0; mi < methodCount; mi++ {
method := t.Method(mi)
// validate if this method match FnContent
isFnContent := false
tm := method.Type
if tm.NumIn() == 2 && tm.In(1).String() == "*knot.Request" {
if tm.NumOut() == 1 && tm.Out(0).Kind() == reflect.Interface {
isFnContent = true
}
}
if isFnContent {
var fnc FnContent
fnc = v.MethodByName(method.Name).Interface().(func(*Request) interface{})
methodName := method.Name
handlerPath := path + strings.ToLower(methodName)
s.Log().Info(fmt.Sprintf("Registering handler for %s", handlerPath))
newcfg := NewResponseConfig()
*newcfg = *cfg
if newcfg.OutputType == OutputTemplate && newcfg.ViewName == "" {
newcfg.ViewName = strings.Join([]string{
strings.ToLower(controllerName),
strings.ToLower(methodName)}, "/") + ".html"
}
s.RouteWithConfig(handlerPath, fnc, newcfg)
}
}
return nil
}
func fixUrlPath(urlPath *string, preSlash, postSlash bool) {
path := strings.ToLower(*urlPath)
if preSlash && strings.HasPrefix(path, "/") == false {
path = "/" + path
}
if postSlash && strings.HasSuffix(path, "/") == false {
path += "/"
}
*urlPath = path
}
func fixLogicalPath(logicalPath *string, preSlash, postSlash bool) {
path := strings.ToLower(*logicalPath)
if preSlash && strings.HasPrefix(path, "/") == false {
path = "/" + path
}
if postSlash && strings.HasSuffix(path, "/") == false {
path += "/"
}
*logicalPath = path
}
func (s *Server) RouteStatic(pathUrl, path string) {
_, ePath := os.Stat(path)
if ePath != nil {
s.Log().Error(fmt.Sprintf("Unable to add static %s from %s : %s", pathUrl, path, ePath.Error()))
return
}
fixUrlPath(&pathUrl, true, true)
s.Log().Info(fmt.Sprintf("Add static %s from %s", pathUrl, path))
fsHandler := http.StripPrefix(pathUrl, http.FileServer(http.Dir(path)))
s.router().PathPrefix(pathUrl).Handler(fsHandler)
}
func (s *Server) Route(path string, fnc FnContent) {
s.RouteWithConfig(path, fnc, NewResponseConfig())
}
func (s *Server) RouteWithConfig(path string, fnc FnContent, cfg *ResponseConfig) {
fixUrlPath(&path, true, false)
s.router().HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if fnc != nil {
rcfg := NewResponseConfig()
*rcfg = *cfg
kr := new(Request)
kr.server = s
kr.httpRequest = r
kr.responseConfig = rcfg
v := fnc(kr)
s.Log().Info(fmt.Sprintf("%s %s OutputType=%s",
r.URL.String(), r.RemoteAddr, kr.ResponseConfig().OutputType.String()))
kr.WriteCookie(w)
kr.Write(w, v)
} else {
w.Write([]byte(""))
}
})
}
func (s *Server) GetHandler(path string) http.Handler {
mr := s.router().GetRoute(path)
if mr == nil {
return nil
}
return mr.GetHandler()
}
func (s *Server) Listen() {
s.start()
s.listen()
}
func (s *Server) start() error {
addr := s.Address
s.status = make(chan string)
s.Log().Info("Start listening on server " + addr)
go func() {
http.ListenAndServe(addr, s.router())
}()
return nil
}
func (s *Server) Stop() {
s.Log().Info(fmt.Sprintf("Stopping server %s", s.Address))
s.status <- "Stop"
}
func (s *Server) listen() {
running := true
for running {
select {
case status := <-s.status:
if status == "Stop" {
running = false
}
default:
time.Sleep(1 * time.Millisecond)
}
}
}