This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
81 lines (66 loc) · 1.88 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package http
import (
"context"
"fmt"
"github.com/rs/cors"
"net"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/superhorsy/quest-app-backend/internal/core/errors"
"github.com/superhorsy/quest-app-backend/internal/core/logging"
)
const (
// ErrAddRoutes is the error returned when adding routes to the router fails.
ErrAddRoutes = errors.Error("failed to add routes")
// ErrServer is the error returned when the server stops due to an error.
ErrServer = errors.Error("listen stopped with error")
)
const (
readHeaderTimeout = 60 * time.Second
)
// Config represents the configuration of the http listener.
type Config struct {
Port string `yaml:"port"`
}
// Service represents a http service that provides routes for the listener.
type Service interface {
AddRoutes(r *mux.Router) error
}
// Server represents a http server that listens on a port.
type Server struct {
server *http.Server
port string
}
// New instantiates a new instance of Server.
func New(s Service, cfg Config, ctx context.Context) (*Server, error) {
r := mux.NewRouter()
r.Use(tracingMiddleware)
r.Use(logTracingMiddleware)
r.Use(requestLoggingMiddleware)
if err := s.AddRoutes(r); err != nil {
return nil, ErrAddRoutes.Wrap(err)
}
handler := cors.AllowAll().Handler(r)
return &Server{
server: &http.Server{
Addr: fmt.Sprintf(":%s", cfg.Port),
BaseContext: func(net.Listener) context.Context {
return logging.With(ctx, logging.From(ctx))
},
Handler: handler,
ReadHeaderTimeout: readHeaderTimeout,
},
port: cfg.Port,
}, nil
}
// Listen starts the server and listens on the configured port.
func (s *Server) Listen(ctx context.Context) error {
logging.From(ctx).Info(fmt.Sprintf("http server starting on port: %s", s.port))
err := s.server.ListenAndServe()
if err != nil {
return ErrServer.Wrap(err)
}
logging.From(ctx).Info("http server stopped")
return nil
}