...
1
2 package xhttp
3
4 import (
5 "context"
6 "log"
7 "net"
8 "net/http"
9 "time"
10
11 "oss.terrastruct.com/util-go/xcontext"
12 )
13
14 func NewServer(log *log.Logger, h http.Handler) *http.Server {
15 return &http.Server{
16 MaxHeaderBytes: 1 << 18,
17 ReadTimeout: time.Minute,
18 WriteTimeout: time.Minute,
19 IdleTimeout: time.Hour,
20 ErrorLog: log,
21 Handler: http.MaxBytesHandler(h, 1<<20),
22 }
23 }
24
25 func Serve(ctx context.Context, shutdownTimeout time.Duration, s *http.Server, l net.Listener) error {
26 s.BaseContext = func(net.Listener) context.Context {
27 return ctx
28 }
29
30 done := make(chan error, 1)
31 go func() {
32 done <- s.Serve(l)
33 }()
34
35 select {
36 case err := <-done:
37 return err
38 case <-ctx.Done():
39 ctx = xcontext.WithoutCancel(ctx)
40 ctx, cancel := context.WithTimeout(ctx, shutdownTimeout)
41 defer cancel()
42 return s.Shutdown(ctx)
43 }
44 }
45
View as plain text