-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
87 lines (72 loc) · 1.92 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
package rest
import (
"context"
"fmt"
"net/http"
"reflect"
"runtime"
"strconv"
"github.com/briand787b/ncx/src/svc/pkg/cslog"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"github.com/google/uuid"
"github.com/pkg/errors"
)
// ServerParams structures the parameters for a new Server
type ServerParams struct {
Port string
Logger cslog.Logger
// StatsStore stats.Store
}
// Server holds the variables for running a server
type Server struct {
port int
l cslog.Logger
// statsStore stats.Store
}
// NewServer instantiates a new Server
func NewServer(p *ServerParams) (*Server, error) {
port, err := strconv.Atoi(p.Port)
if err != nil {
}
return &Server{
port: port,
l: p.Logger,
// statsStore: p.StatsStore,
}, nil
}
// Run runs the server
func (s *Server) Run() error {
mw, err := NewMiddleware(s.l, uuid.New())
if err != nil {
return errors.Wrap(err, "could not create new middleware")
}
// sc := NewStatsController(s.l, s.statsStore)
// initialize router
r := chi.NewMux()
r.Use(middleware.Recoverer)
r.Use(render.SetContentType(render.ContentTypeJSON))
r.Use(mw.spanAndTrace)
r.Use(mw.logRoute)
r.Route("/v1.0", func(r chi.Router) {
// r.Get("/locations/{location_id}/items/most-ordered", sc.handleGetMostOrderedItemByLocationID)
})
ctx := cslog.StoreSpanIDTraceID(context.Background(), "main", "main")
walkFn := func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
funcName := runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
s.l.Info(ctx, "API Route",
"method", method,
"route", route,
"handler", funcName,
)
return nil
}
if err := chi.Walk(r, walkFn); err != nil {
return errors.Wrap(err, "could not print API routes")
}
if err := http.ListenAndServe(fmt.Sprintf(":%v", s.port), r); err != nil {
return errors.Wrap(err, "could not listen and serve")
}
return nil
}