-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.go
115 lines (99 loc) · 2.53 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
package xingyun
import (
"fmt"
"net"
"net/http"
"os"
"github.com/gorilla/securecookie"
)
type Server struct {
Router
Config *Config
StaticDir http.FileSystem
Name string
SecureCookie *securecookie.SecureCookie
DefaultPipeHandlers []PipeHandler
PanicHandler ContextHandlerFunc
ErrorPageHandler ContextHandlerFunc
SessionStorage SessionStorage
pipes map[string]*Pipe
defaultPipe *Pipe
l net.Listener
logger Logger
}
func NewServer(config *Config) *Server {
if config == nil {
config = &Config{}
}
setDefaultConfig(config)
server := &Server{
logger: &debugLogger{Logger: NewSimpleLevelLogger(os.Stdout), enableDebug: config.EnableDebug},
Config: config,
}
server.PanicHandler = DefaultPanicHandler
server.pipes = map[string]*Pipe{}
server.DefaultPipeHandlers = []PipeHandler{
server.GetErrorPagePipeHandler(),
server.GetLogPipeHandler(),
server.GetRecoverPipeHandler(),
server.GetStaticPipeHandler(),
}
server.Router = newRouter(server.getURLVarLoaderPipeHandler())
server.StaticDir = http.Dir(config.StaticDir)
server.SessionStorage = NewMemoryStore()
server.SecureCookie = securecookie.New(
[]byte(config.CookieSecret),
[]byte(config.CookieSecret),
)
return server
}
func (s *Server) SetLogger(l Logger) {
s.logger = &debugLogger{Logger: l, enableDebug: s.Config.EnableDebug}
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
pipeHandlers := []PipeHandler{s.GetContextPipeHandler()}
pipeHandlers = append(pipeHandlers, s.DefaultPipeHandlers...)
s.defaultPipe = newPipe(s, pipeHandlers...)
h := s.defaultPipe.HTTPHandler(s.Router)
h.ServeHTTP(wrapResponseWriter(w), r)
}
func (s *Server) NewPipe(name string, handlers ...PipeHandler) *Pipe {
p := newPipe(s, handlers...)
_, ok := s.pipes[name]
if ok {
panic(fmt.Errorf("pipe %s is exist", name))
}
s.pipes[name] = p
return p
}
func (s *Server) Pipe(name string) *Pipe {
p, ok := s.pipes[name]
if !ok {
panic(fmt.Errorf("pipe %s is not exist", name))
}
return p
}
func (s *Server) name() string {
if s.Name == "" {
return "xingyun"
}
return s.Name
}
func (s *Server) ListenAndServe(addr string) error {
l, err := net.Listen("tcp", addr)
if err != nil {
s.logger.Errorf(err.Error())
}
s.l = l
s.logger.Infof("%s start in: %s", s.name(), addr)
err = http.Serve(s.l, s)
// todo: must handle error when serve failed
// s.logger.Errorf("%s stop, err='%s'", err)
return err
}
func (s *Server) Stop() error {
if s.l != nil {
return s.l.Close()
}
return nil
}