blob: 424f3597fea61b63ecdb9810ab4924aa87786fff (
plain)
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
|
// Copyright 2022 Terin Stock.
// SPDX-License-Identifier: MPL-2.0
package server
import (
"context"
"net"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
)
type Server struct {
mux *mux.Router
host string
port int
}
type Options struct {
Host string
Port int
}
func New(options Options) *Server {
return &Server{
mux: mux.NewRouter(),
host: options.Host,
port: options.Port,
}
}
func (s *Server) Register(path string, handler http.Handler) {
s.mux.Handle(path, handler)
}
func (s *Server) Start(ctx context.Context) error {
ln, err := net.Listen("tcp", net.JoinHostPort(s.host, strconv.Itoa(s.port)))
if err != nil {
return err
}
srv := &http.Server{
Handler: s.mux,
MaxHeaderBytes: 1 << 20,
IdleTimeout: 90 * time.Second,
ReadHeaderTimeout: 32 * time.Second,
}
shutdownCh := make(chan struct{})
go func() {
<-ctx.Done()
if err := srv.Shutdown(context.Background()); err != nil {
_ = err
}
close(shutdownCh)
}()
if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
return err
}
<-shutdownCh
return nil
}
|