-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
63 lines (51 loc) · 1.41 KB
/
http.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
package http
import (
"context"
"net/http"
"github.com/go-chi/chi"
gochiCors "github.com/go-chi/cors"
"github.com/floriantoufet/fizzbuzz/transport"
"github.com/floriantoufet/fizzbuzz/transport/http/endpoints"
)
type HTTP struct {
config *Config
server *http.Server
endpoints *endpoints.Endpoints
}
func NewHTTP(httpConfig *Config, endpoints *endpoints.Endpoints) transport.Server {
return &HTTP{
config: httpConfig,
endpoints: endpoints,
}
}
func (transport *HTTP) ListenAndServe() error {
handler := chi.NewRouter()
handler.Group(func(r chi.Router) {
transport.initRoutes(r)
})
transport.server = &http.Server{
Addr: transport.config.GetAddress(),
Handler: handler,
}
return transport.server.ListenAndServe()
}
func (transport *HTTP) Shutdown() error {
return transport.server.Shutdown(context.Background())
}
func (transport *HTTP) GetAddress() string {
return transport.config.GetAddress()
}
func (transport *HTTP) initRoutes(r chi.Router) {
// Init CORS
r.Use(gochiCors.New(gochiCors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "DELETE"},
AllowedHeaders: []string{"Accept", "Content-Type"},
}).Handler)
r.Route("/v1", func(r chi.Router) {
r.Get("/ping", transport.endpoints.Ping)
r.Get("/fizz_buzz", transport.endpoints.FizzBuzz)
r.Get("/stats", transport.endpoints.RetrieveStats)
r.Delete("/stats", transport.endpoints.ResetStats)
})
}