-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
90 lines (82 loc) · 2.25 KB
/
server.go
File metadata and controls
90 lines (82 loc) · 2.25 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
package chiweb
import (
"context"
"errors"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type HttpServer struct {
Server *http.Server
RootRouter chi.Router
}
func NewHttpServer(bindAddr string) *HttpServer {
return &HttpServer{
Server: &http.Server{
Addr: bindAddr,
ReadTimeout: time.Second * 10,
WriteTimeout: time.Second * 10,
},
RootRouter: newDefaultRootRouter(),
}
}
func (s *HttpServer) Serve(serveCtx context.Context) error {
s.Server.Handler = s.RootRouter
slog.Info("http server listen", "addr", s.Server.Addr)
err := s.Server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func (s *HttpServer) Shutdown(shutdownCtx context.Context) error {
slog.Info("http server shutdown")
if err := s.Server.Shutdown(shutdownCtx); err != nil {
return err
}
return nil
}
func (s *HttpServer) GracefulShutdown(serverCtx context.Context, timeout time.Duration) error {
// Shutdown signal with grace period of 30 seconds
shutdownCtx, _ := context.WithTimeout(serverCtx, timeout)
go func() {
<-shutdownCtx.Done()
if errors.Is(shutdownCtx.Err(), context.DeadlineExceeded) {
slog.Info("http server graceful shutdown timed out.. forcing exit.")
}
}()
// Trigger graceful shutdown
return s.Shutdown(shutdownCtx)
}
func GoServe(server *HttpServer, serverCtx context.Context, serverStopCtx context.CancelFunc) {
// Listen for syscall signals for process to interrupt/quit
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
<-sig
server.GracefulShutdown(serverCtx, time.Second*10)
serverStopCtx()
}()
if err := server.Serve(serverCtx); err != nil {
log.Print("web server serve", "error", err)
}
<-serverCtx.Done()
}
func newDefaultRootRouter() chi.Router {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Set a timeout value on the request context (ctx), that will signal
// through ctx.Done() that the request has timed out and further
// processing should be stopped.
r.Use(middleware.Timeout(10 * time.Second))
return r
}