-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
69 lines (54 loc) · 1.33 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package http
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"strconv"
"github.com/yolkhovyy/go-otelw/otelw/slogw"
cserver "github.com/yolkhovyy/go-userv/internal/contract/server"
)
type Server struct {
*http.Server
config Config
}
//nolint:ireturn
func New(config Config, handler http.Handler) cserver.Contract {
return &Server{
Server: &http.Server{
Addr: net.JoinHostPort("", strconv.Itoa(config.Port)),
Handler: handler,
ReadHeaderTimeout: config.ReadHeaderTimeout,
},
config: config,
}
}
func (s *Server) Run(ctx context.Context) error {
logger := slogw.DefaultLogger()
errChan := make(chan error)
go func() {
logger.InfoContext(ctx, "http server starting",
slog.String("addr", s.Server.Addr))
if err := s.Server.ListenAndServe(); err != nil {
errChan <- err
}
close(errChan)
}()
select {
case <-ctx.Done():
case err := <-errChan:
if !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("http server start: %w", err)
}
}
logger.DebugContext(ctx, "http server shutting down")
ctx, timeout := context.WithTimeout(ctx, s.config.ShutdownTimeout)
defer timeout()
if err := s.Server.Shutdown(ctx); err != nil {
return fmt.Errorf("http server shutdown: %w", err)
}
logger.DebugContext(ctx, "http server shutting down complete")
return nil
}