-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserve.go
49 lines (43 loc) · 1.05 KB
/
serve.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
// Package xhttp implements http helpers.
package xhttp
import (
"context"
"log"
"net"
"net/http"
"time"
"oss.terrastruct.com/util-go/xcontext"
)
func NewServer(log *log.Logger, h http.Handler) *http.Server {
return &http.Server{
MaxHeaderBytes: 1 << 18, // 262,144B
ReadTimeout: time.Minute,
WriteTimeout: time.Minute,
IdleTimeout: time.Hour,
ErrorLog: log,
Handler: http.MaxBytesHandler(h, 1<<20), // 1,048,576B
}
}
func Serve(ctx context.Context, shutdownTimeout time.Duration, s *http.Server, l net.Listener) error {
s.BaseContext = func(net.Listener) context.Context {
return ctx
}
done := make(chan error, 1)
go func() {
done <- s.Serve(l)
}()
select {
case err := <-done:
return err
case <-ctx.Done():
shutdownCtx := xcontext.WithoutCancel(ctx)
shutdownCtx, cancel := context.WithTimeout(shutdownCtx, shutdownTimeout)
defer cancel()
shutdownErr := s.Shutdown(shutdownCtx)
serveErr := <-done
if serveErr != nil && serveErr != http.ErrServerClosed {
return serveErr
}
return shutdownErr
}
}