-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
227 lines (209 loc) · 6.95 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
package web
import (
"net"
"net/http"
"sync"
"time"
"github.com/ecnepsnai/logtic"
"github.com/ecnepsnai/web/router"
"golang.org/x/time/rate"
)
// Server describes an web server
type Server struct {
// The socket address that the server is listening on. Only populated if the server was created with web.New().
BindAddress string
// The port that this server is listening on. Only populated if the server was created with web.New().
ListenPort uint16
// The JSON API server. API handles return data or an error, and all responses are wrapped in a common
// response object; [web.JSONResponse].
API API
// HTTPEasy describes a easy HTTP server. HTTPEasy handles are expected to return a reader and specify the content
// type and length themselves.
//
// The HTTPEasy server supports HTTP range requests, should the client request it and the application provide a
// supported Reader [io.ReadSeekCloser].
HTTPEasy HTTPEasy
// The HTTP server. HTTP handles are exposed to the raw http request and response writers.
HTTP HTTP
// The handler called when a request that does not match a registered path occurs. Defaults to a plain
// HTTP 404 with "Not found" as the body.
NotFoundHandler func(w http.ResponseWriter, r *http.Request)
// The handler called when a request that did match a router but with the incorrect method occurs. Defaults to a
// plain HTTP 405 with "Method not allowed" as the body.
MethodNotAllowedHandler func(w http.ResponseWriter, r *http.Request)
// The handler called when a request exceed the configured maximum per second limit. Defaults to a plain HTTP 429
// with "Too many requests" as the body.
RateLimitedHandler func(w http.ResponseWriter, r *http.Request)
// Additional options for the server
Options ServerOptions
router *router.Server
listener net.Listener
shuttingDown bool
limits map[string]*rate.Limiter
limitLock *sync.Mutex
}
type ServerOptions struct {
// Specify the maximum number of requests any given client IP address can make per second. Requests that are rate
// limited will call the RateLimitedHandler, which you can override to customize the response.
// Setting this to 0 disables rate limiting.
MaxRequestsPerSecond int
// The level to use when logging out HTTP requests. Maps to github.com/ecnepsnai/logtic levels. Defaults to Debug.
RequestLogLevel logtic.LogLevel
// If true then the server will not try to reply with chunked data for a HTTP range request
IgnoreHTTPRangeRequests bool
}
// New create a new server object that will bind to the provided address. Does not accept incoming connections until
// the server is started.
// Bind address must be in the format of "address:port", such as "localhost:8080" or "0.0.0.0:8080".
func New(bindAddress string) *Server {
httpRouter := router.New()
server := Server{
BindAddress: bindAddress,
Options: ServerOptions{
RequestLogLevel: logtic.LevelDebug,
},
router: httpRouter,
limits: map[string]*rate.Limiter{},
limitLock: &sync.Mutex{},
}
httpRouter.SetNotFoundHandle(server.notFoundHandle)
httpRouter.SetMethodNotAllowedHandle(server.methodNotAllowedHandle)
server.API = API{
server: &server,
}
server.HTTPEasy = HTTPEasy{
server: &server,
}
server.HTTP = HTTP{
server: &server,
}
return &server
}
// NewListener creates a new server object that will use the given listener. Does not accept incoming connections until
// the server is started.
func NewListener(listener net.Listener) *Server {
httpRouter := router.New()
server := Server{
Options: ServerOptions{
RequestLogLevel: logtic.LevelDebug,
},
router: httpRouter,
listener: listener,
limits: map[string]*rate.Limiter{},
limitLock: &sync.Mutex{},
}
httpRouter.SetNotFoundHandle(server.notFoundHandle)
httpRouter.SetMethodNotAllowedHandle(server.methodNotAllowedHandle)
server.API = API{
server: &server,
}
server.HTTPEasy = HTTPEasy{
server: &server,
}
server.HTTP = HTTP{
server: &server,
}
return &server
}
// Start will start the web server and listen on the socket address. This method blocks.
// If a server is stopped using the Stop() method, this returns no error.
func (s *Server) Start() error {
if s.BindAddress != "" {
listener, err := net.Listen("tcp", s.BindAddress)
if err != nil {
log.PError("Error listening on address", map[string]interface{}{
"listen_address": s.BindAddress,
"error": err.Error(),
})
return err
}
s.listener = listener
s.ListenPort = uint16(listener.Addr().(*net.TCPAddr).Port)
log.PInfo("HTTP server listen", map[string]interface{}{
"listen_address": s.BindAddress,
"listen_port": s.ListenPort,
})
}
if err := s.router.Serve(s.listener); err != nil {
if s.shuttingDown {
log.Info("HTTP server stopped")
return nil
}
return err
}
return nil
}
// Stop will stop the server. The Start() method will return without an error after stopping.
func (s *Server) Stop() {
log.Warn("Stopping HTTP server")
s.shuttingDown = true
s.ListenPort = 0
s.listener.Close()
}
func (s *Server) notFoundHandle(w http.ResponseWriter, r *http.Request) {
log.PWrite(s.Options.RequestLogLevel, "HTTP Request", map[string]interface{}{
"remote_addr": RealRemoteAddr(r),
"method": r.Method,
"url": r.URL,
"elapsed": time.Duration(0).String(),
"status": 404,
})
if s.NotFoundHandler != nil {
s.NotFoundHandler(w, r)
return
}
w.WriteHeader(404)
w.Write([]byte("Not found"))
}
func (s *Server) methodNotAllowedHandle(w http.ResponseWriter, r *http.Request) {
log.PWrite(s.Options.RequestLogLevel, "HTTP Request", map[string]interface{}{
"remote_addr": RealRemoteAddr(r),
"method": r.Method,
"url": r.URL,
"elapsed": time.Duration(0).String(),
"status": 405,
})
if s.MethodNotAllowedHandler != nil {
s.MethodNotAllowedHandler(w, r)
return
}
w.WriteHeader(405)
w.Write([]byte("Method not allowed"))
}
func (s *Server) isRateLimited(w http.ResponseWriter, r *http.Request) bool {
// If rate limiting is not configured return a new limiter for each connection
if s.Options.MaxRequestsPerSecond == 0 {
return false
}
s.limitLock.Lock()
defer s.limitLock.Unlock()
sourceIP := RealRemoteAddr(r).String()
limiter := s.limits[sourceIP]
if limiter == nil {
// Allow MaxRequestsPerSecond every 1 second
limiter = rate.NewLimiter(rate.Limit(s.Options.MaxRequestsPerSecond), s.Options.MaxRequestsPerSecond)
s.limits[sourceIP] = limiter
}
if !limiter.Allow() {
log.PWarn("Rate-limiting request", map[string]interface{}{
"remote_addr": RealRemoteAddr(r),
"method": r.Method,
"url": r.URL,
})
log.PWrite(s.Options.RequestLogLevel, "HTTP Request", map[string]interface{}{
"remote_addr": RealRemoteAddr(r),
"method": r.Method,
"url": r.URL,
"elapsed": time.Duration(0).String(),
"status": 429,
})
if s.RateLimitedHandler != nil {
s.RateLimitedHandler(w, r)
} else {
w.WriteHeader(429)
w.Write([]byte("Too many requests"))
}
return true
}
return false
}