-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
59 lines (51 loc) · 1.47 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
package nbc
import (
"context"
"log"
"net"
"net/http"
"os/signal"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/rs/cors"
"golang.org/x/sync/errgroup"
)
type Server struct {
Port string
Router *chi.Mux
}
func (s *Server) ServeHTTP() {
// "*" shouldn't be used as AllowedOrigins
c := cors.Options{
AllowedOrigins: []string{"http://localhost:3000", "http://127.0.0.1:3000"},
AllowCredentials: true,
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodPatch},
AllowedHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
}
handler := cors.New(c).Handler(s.Router)
serverCtx, serverStop := signal.NotifyContext(context.Background(), syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
defer serverStop()
server := http.Server{
Addr: s.Port,
Handler: handler,
ReadTimeout: 10 * time.Second, // max time to read request from the client
WriteTimeout: 10 * time.Second, // max time to write response to the client
IdleTimeout: 120 * time.Second, // max time for connections using TCP Keep-Alive
BaseContext: func(_ net.Listener) context.Context {
return serverCtx
},
}
g, gCtx := errgroup.WithContext(serverCtx)
g.Go(func() error {
// Run the server
return server.ListenAndServe()
})
g.Go(func() error {
<-gCtx.Done()
return server.Shutdown(context.Background())
})
if err := g.Wait(); err != nil {
log.Printf("exit reason: %s \n", err)
}
}