generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.go
45 lines (39 loc) · 919 Bytes
/
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
package http
import (
"context"
"errors"
"net"
"net/http"
"net/url"
"time"
"github.com/TBD54566975/ftl/internal/log"
)
const ShutdownGracePeriod = 5 * time.Second
func Serve(ctx context.Context, listen *url.URL, handler http.Handler) error {
httpServer := &http.Server{
Addr: listen.Host,
Handler: handler,
ReadHeaderTimeout: 30 * time.Second,
BaseContext: func(_ net.Listener) context.Context {
return ctx
},
}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), ShutdownGracePeriod)
defer cancel()
err := httpServer.Shutdown(shutdownCtx)
if err != nil {
if errors.Is(err, context.Canceled) {
_ = httpServer.Close()
return
}
log.FromContext(ctx).Errorf(err, "server shutdown error")
}
}()
err := httpServer.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}