Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
286 lines (230 loc) · 6.26 KB
/
Copy pathserver.go
File metadata and controls
286 lines (230 loc) · 6.26 KB
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
// Package gserv is a simple, fast, and flexible HTTP server framework for Go.
package gserv
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"go.oneofone.dev/gserv/router"
"go.oneofone.dev/oerrs"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
// DefaultPanicHandler is the default panic recovery handler that logs the panic and returns a JSON 500 error response.
var DefaultPanicHandler = func(ctx *Context, v any, fr *oerrs.Frame) {
msg, info := fmt.Sprintf("PANIC in %s %s: %v", ctx.Req.Method, ctx.Path(), v), fmt.Sprintf("at %s %s:%d", fr.Function, fr.File, fr.Line)
ctx.Logf("%s (%s)", msg, info)
resp := NewJSONErrorResponse(500, "internal server error")
_ = ctx.Encode(500, resp)
}
var noopLogger = log.New(io.Discard, "", 0)
// DefaultOpts are the default options used for creating new servers.
var DefaultOpts = Options{
WriteTimeout: time.Minute,
ReadTimeout: time.Minute,
MaxHeaderBytes: 1 << 20, // 1MiB
Logger: log.New(os.Stderr, "gserv: ", 0),
}
// New creates a new Server with the given options.
func New(opts ...Option) *Server {
o := DefaultOpts
for _, opt := range opts {
opt(&o)
}
return NewWithOpts(&o)
}
// NewWithOpts creates a new Server from an Options struct.
func NewWithOpts(opts *Options) *Server {
srv := &Server{}
if opts == nil {
cp := DefaultOpts
srv.opts = cp
} else {
srv.opts = *opts
}
ro := srv.opts.RouterOptions
srv.r = router.New(ro)
if srv.opts.CatchPanics {
srv.PanicHandler = DefaultPanicHandler
}
srv.r.NotFoundHandler = func(w http.ResponseWriter, req *http.Request, p router.Params) {
if h := srv.NotFoundHandler; h != nil {
ctx := getCtx(w, req, p, srv)
srv.NotFoundHandler(ctx)
putCtx(ctx)
return
}
_ = RespNotFound.WriteToCtx(&Context{
Req: req,
ResponseWriter: w,
})
}
srv.s = srv
return srv
}
type (
PanicHandler = func(ctx *Context, v any, fr *oerrs.Frame)
)
// Server is the main HTTP server type.
type Server struct {
Group
r *router.Router
PanicHandler
NotFoundHandler func(ctx *Context)
servers []*http.Server
opts Options
serversMux sync.Mutex
closed int32
NoCompression bool // used by proxies
}
// ServeHTTP implements http.Handler, allowing the server to be used in custom scenarios.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.r.ServeHTTP(w, req)
}
func (s *Server) newHTTPServer(ctx context.Context, addr string, forceHTTP2 bool) *http.Server {
opts := &s.opts
h := http.Handler(s.r)
if forceHTTP2 {
h = h2c.NewHandler(s.r, &http2.Server{})
}
lg := opts.Logger
// if !opts.EnableDefaultHTTPLogging {
// lg = noopLogger
// }
srv := &http.Server{
Addr: addr,
Handler: h,
ReadTimeout: opts.ReadTimeout,
WriteTimeout: opts.WriteTimeout,
MaxHeaderBytes: opts.MaxHeaderBytes,
ErrorLog: lg,
BaseContext: func(net.Listener) context.Context { return ctx },
ConnContext: func(context.Context, net.Conn) context.Context { return ctx },
}
go func() {
<-ctx.Done()
_ = srv.Shutdown(ctx)
}()
return srv
}
// Run starts the server on the given address with HTTP/2 support.
// If addr is empty, it defaults to ":http".
func (s *Server) Run(ctx context.Context, addr string) error {
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
srv := s.newHTTPServer(ctx, ln.Addr().String(), true)
s.serversMux.Lock()
s.servers = append(s.servers, srv)
s.serversMux.Unlock()
if err = srv.Serve(ln); err != nil && errors.Is(err, http.ErrServerClosed) {
err = nil
}
return err
}
// SetKeepAlivesEnabled enables or disables HTTP keep-alives on all underlying servers.
func (s *Server) SetKeepAlivesEnabled(v bool) {
s.serversMux.Lock()
for _, srv := range s.servers {
srv.SetKeepAlivesEnabled(v)
}
s.serversMux.Unlock()
}
// Addrs returns all the listening addresses of the underlying http.Servers.
func (s *Server) Addrs() (out []string) {
s.serversMux.Lock()
out = make([]string, len(s.servers))
for i, srv := range s.servers {
out[i] = srv.Addr
}
s.serversMux.Unlock()
return out
}
// Closed returns true if the server has been shut down or closed.
func (s *Server) Closed() bool {
return atomic.LoadInt32(&s.closed) == 1
}
// Logf logs a formatted message using the server's logger.
func (s *Server) Logf(f string, args ...any) {
s.logfStack(2, f, args...)
}
func (s *Server) logfStack(n int, f string, args ...any) {
lg := s.opts.Logger
if lg == nil {
lg = log.Default()
}
_, file, line, ok := runtime.Caller(n + 1)
if !ok {
file = "???"
line = 0
}
// make it output the package owning the file
parts := strings.Split(file, "/")
if len(parts) > 2 {
parts = parts[len(parts)-2:]
}
lg.Printf(strings.Join(parts, "/")+":"+strconv.Itoa(line)+": "+f, args...)
}
// AllowCORS adds an OPTIONS route for CORS support using the given allowed methods.
func (s *Server) AllowCORS(path string, allowedMethods ...string) {
s.AddRoute(http.MethodOptions, path, AllowCORS(allowedMethods, nil, nil))
}
// Swagger returns the swagger documentation instance for this server.
func (s *Server) Swagger() *router.Swagger {
return s.r.Swagger()
}
// Close immediately closes all the active underlying http servers and connections without graceful shutdown.
func (s *Server) Close() error {
if !atomic.CompareAndSwapInt32(&s.closed, 0, 1) {
return http.ErrServerClosed
}
var me MultiError
s.serversMux.Lock()
for _, srv := range s.servers {
srv.SetKeepAlivesEnabled(false)
if err := srv.Close(); err != nil {
err = fmt.Errorf("%s (%T): %s", srv.Addr, err, err)
me.Push(err)
}
}
s.servers = nil
s.serversMux.Unlock()
return me.Err()
}
// Shutdown gracefully shuts down all the underlying http servers, optionally with a timeout.
func (s *Server) Shutdown(timeout time.Duration) error {
if !atomic.CompareAndSwapInt32(&s.closed, 0, 1) {
return http.ErrServerClosed
}
var (
me MultiError
ctx = context.Background()
)
if timeout > 0 {
var cancelFn func()
ctx, cancelFn = context.WithDeadline(ctx, time.Now().Add(timeout))
defer cancelFn()
}
s.serversMux.Lock()
for _, srv := range s.servers {
srv.SetKeepAlivesEnabled(false)
me.Push(srv.Shutdown(ctx))
}
s.servers = nil
s.serversMux.Unlock()
return me.Err()
}