This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
93 lines (80 loc) 路 2.11 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package server
import (
"context"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
"go.uber.org/zap"
"go.bobheadxi.dev/res"
"go.bobheadxi.dev/seer/config"
"go.bobheadxi.dev/seer/jobs"
"go.bobheadxi.dev/seer/riot"
"go.bobheadxi.dev/seer/store"
"go.bobheadxi.dev/zapx/zhttp"
)
// Server contains Seer's core application logic
type Server struct {
l *zap.Logger
mux *chi.Mux
srv *http.Server
jobsQueue jobs.Queue
}
// New instantiates a new server
func New(
l *zap.Logger,
riotAPI riot.API,
backend store.Store,
jobsQueue jobs.Queue,
meta config.BuildMeta,
) (*Server, error) {
srv := &Server{
l: l,
srv: &http.Server{},
jobsQueue: jobsQueue,
}
mux := chi.NewMux()
mux.Use(
middleware.Recoverer,
cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // TODO
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
}).Handler,
middleware.RequestID,
middleware.RealIP,
zhttp.NewMiddleware(l.Named("requests"), nil).Logger,
)
// status check endpoints
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
mux.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
res.R(w, r, res.MsgOK("server online",
"build.commit", meta.Commit))
})
// register api endpoints
teams := &teamAPI{l.Named("teams"), riotAPI, backend, jobsQueue}
mux.Route("/team", teams.Group)
srv.srv.Handler = mux
return srv, nil
}
// Start spins up the API server
func (s *Server) Start(addr string, stop chan bool) error {
if addr == "" {
addr = ":8080"
}
s.srv.Addr = addr
go func() {
<-stop
s.Stop(context.Background())
}()
return s.srv.ListenAndServe()
}
// Stop shuts down this server and its associated resources
func (s *Server) Stop(ctx context.Context) {
if err := s.srv.Shutdown(ctx); err != nil {
s.l.Error(err.Error())
}
}