This repository has been archived by the owner on Mar 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.go
302 lines (256 loc) · 7.18 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
package xweb
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"net/http/pprof"
"os"
"runtime"
runtimePprof "runtime/pprof"
"strconv"
"strings"
"time"
"github.com/go-xweb/httpsession"
"github.com/go-xweb/log"
)
// ServerConfig is configuration for server objects.
type ServerConfig struct {
Addr string
Port int
RecoverPanic bool
Profiler bool
EnableGzip bool
StaticExtensionsToGzip []string
Url string
UrlPrefix string
UrlSuffix string
StaticHtmlDir string
SessionTimeout time.Duration
}
var ServerNumber uint = 0
// Server represents a xweb server.
type Server struct {
Config *ServerConfig
Apps map[string]*App
AppsNamePath map[string]string
Name string
SessionManager *httpsession.Manager
RootApp *App
Logger *log.Logger
Env map[string]interface{}
//save the listener so it can be closed
l net.Listener
}
func NewServer(args ...string) *Server {
name := ""
if len(args) == 1 {
name = args[0]
} else {
name = fmt.Sprintf("Server%d", ServerNumber)
ServerNumber++
}
s := &Server{
Config: Config,
Env: map[string]interface{}{},
Apps: map[string]*App{},
AppsNamePath: map[string]string{},
Name: name,
}
Servers[s.Name] = s
s.SetLogger(log.New(os.Stdout, "", log.Ldefault()))
app := NewApp("/", "root")
s.AddApp(app)
return s
}
func (s *Server) AddApp(a *App) {
a.BasePath = strings.TrimRight(a.BasePath, "/") + "/"
s.Apps[a.BasePath] = a
if a.Name != "" {
s.AppsNamePath[a.Name] = a.BasePath
}
a.Server = s
a.Logger = s.Logger
if a.BasePath == "/" {
s.RootApp = a
}
}
func (s *Server) AddAction(cs ...interface{}) {
s.RootApp.AddAction(cs...)
}
func (s *Server) AutoAction(c ...interface{}) {
s.RootApp.AutoAction(c...)
}
func (s *Server) AddRouter(url string, c interface{}) {
s.RootApp.AddRouter(url, c)
}
func (s *Server) AddTmplVar(name string, varOrFun interface{}) {
s.RootApp.AddTmplVar(name, varOrFun)
}
func (s *Server) AddTmplVars(t *T) {
s.RootApp.AddTmplVars(t)
}
func (s *Server) AddFilter(filter Filter) {
s.RootApp.AddFilter(filter)
}
func (s *Server) AddConfig(name string, value interface{}) {
s.RootApp.SetConfig(name, value)
}
func (s *Server) SetConfig(name string, value interface{}) {
s.RootApp.SetConfig(name, value)
}
func (s *Server) GetConfig(name string) interface{} {
return s.RootApp.GetConfig(name)
}
func (s *Server) error(w http.ResponseWriter, status int, content string) error {
return s.RootApp.error(w, status, content)
}
func (s *Server) initServer() {
if s.Config == nil {
s.Config = &ServerConfig{}
s.Config.Profiler = true
}
for _, app := range s.Apps {
app.initApp()
}
}
// ServeHTTP is the interface method for Go's http server package
func (s *Server) ServeHTTP(c http.ResponseWriter, req *http.Request) {
s.Process(c, req)
}
// Process invokes the routing system for server s
// non-root app's route will override root app's if there is same path
func (s *Server) Process(w http.ResponseWriter, req *http.Request) {
var result bool = true
_, _ = XHook.Call("BeforeProcess", &result, s, w, req)
if !result {
return
}
if s.Config.UrlSuffix != "" && strings.HasSuffix(req.URL.Path, s.Config.UrlSuffix) {
req.URL.Path = strings.TrimSuffix(req.URL.Path, s.Config.UrlSuffix)
}
if s.Config.UrlPrefix != "" && strings.HasPrefix(req.URL.Path, "/"+s.Config.UrlPrefix) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, "/"+s.Config.UrlPrefix)
}
if req.URL.Path[0] != '/' {
req.URL.Path = "/" + req.URL.Path
}
for _, app := range s.Apps {
if app != s.RootApp && strings.HasPrefix(req.URL.Path, app.BasePath) {
app.routeHandler(req, w)
return
}
}
s.RootApp.routeHandler(req, w)
_, _ = XHook.Call("AfterProcess", &result, s, w, req)
}
// Run starts the web application and serves HTTP requests for s
func (s *Server) Run(addr string) {
addrs := strings.Split(addr, ":")
s.Config.Addr = addrs[0]
s.Config.Port, _ = strconv.Atoi(addrs[1])
s.initServer()
mux := http.NewServeMux()
if s.Config.Profiler {
mux.Handle("/debug/pprof", http.HandlerFunc(pprof.Index))
mux.Handle("/debug/pprof/heap", pprof.Handler("heap"))
mux.Handle("/debug/pprof/block", pprof.Handler("block"))
mux.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
mux.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
mux.Handle("/debug/pprof/startcpuprof", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
StartCPUProfile()
}))
mux.Handle("/debug/pprof/stopcpuprof", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
StopCPUProfile()
}))
mux.Handle("/debug/pprof/memprof", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
runtime.GC()
runtimePprof.WriteHeapProfile(rw)
}))
mux.Handle("/debug/pprof/gc", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
PrintGCSummary(rw)
}))
}
if c, err := XHook.Call("MuxHandle", mux); err == nil {
if ret := XHook.Value(c, 0); ret != nil {
mux = ret.(*http.ServeMux)
}
}
mux.Handle("/", s)
s.Logger.Infof("http server is listening %s", addr)
l, err := net.Listen("tcp", addr)
if err != nil {
s.Logger.Error("ListenAndServe:", err)
}
s.l = l
err = http.Serve(s.l, mux)
s.l.Close()
}
// RunFcgi starts the web application and serves FastCGI requests for s.
func (s *Server) RunFcgi(addr string) {
s.initServer()
s.Logger.Infof("fcgi server is listening %s", addr)
s.listenAndServeFcgi(addr)
}
// RunScgi starts the web application and serves SCGI requests for s.
func (s *Server) RunScgi(addr string) {
s.initServer()
s.Logger.Infof("scgi server is listening %s", addr)
s.listenAndServeScgi(addr)
}
// RunTLS starts the web application and serves HTTPS requests for s.
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 {
s.Logger.Errorf("Listen: %v", err)
return err
}
s.l = l
s.Logger.Infof("https server is listening %s", addr)
return http.Serve(s.l, mux)
}
// Close stops server s.
func (s *Server) Close() {
if s.l != nil {
s.l.Close()
}
}
// SetLogger sets the logger for server s
func (s *Server) SetLogger(logger *log.Logger) {
s.Logger = logger
s.Logger.SetPrefix("[" + s.Name + "] ")
if s.RootApp != nil {
s.RootApp.Logger = s.Logger
}
}
func (s *Server) InitSession() {
if s.SessionManager == nil {
s.SessionManager = httpsession.Default()
}
if s.Config.SessionTimeout > time.Second {
s.SessionManager.SetMaxAge(s.Config.SessionTimeout)
}
s.SessionManager.Run()
if s.RootApp != nil {
s.RootApp.SessionManager = s.SessionManager
}
}
func (s *Server) SetTemplateDir(path string) {
s.RootApp.SetTemplateDir(path)
}
func (s *Server) SetStaticDir(path string) {
s.RootApp.SetStaticDir(path)
}
func (s *Server) App(name string) *App {
path, ok := s.AppsNamePath[name]
if ok {
return s.Apps[path]
}
return nil
}