-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
82 lines (65 loc) · 1.73 KB
/
main.go
File metadata and controls
82 lines (65 loc) · 1.73 KB
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
package main
import (
"log"
"net/http"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"chiapitest/controller"
)
func Routes(c *controller.Controller) *chi.Mux {
router := chi.NewRouter()
router.Use(
RequestTraceMiddleware,
render.SetContentType(render.ContentTypeJSON),
middleware.Logger,
//middleware.RequestLogger()
middleware.DefaultCompress,
middleware.RedirectSlashes,
//middleware.RequestID,
middleware.RealIP,
middleware.Recoverer,
)
// Set a timeout value on the request context (ctx), that will signal
// through ctx.Done() that the request has timed out and further
// processing should be stopped.
router.Use(middleware.Timeout(60 * time.Second))
router.Route("/v1", func(r chi.Router) {
r.Mount("/people", c.Routes())
})
return router
}
func main() {
//log.SetPrefix("Hola ")
log.Print("Starting API")
port := ":8080"
var c = controller.NewController()
router := Routes(c)
walkFunc := func(
method string,
route string,
handler http.Handler,
middlewares ...func(http.Handler) http.Handler) error {
log.Printf("%s %s\n", method, route)
return nil
}
if err := chi.Walk(router, walkFunc); err != nil {
log.Panicf("Logging err: %s\n", err.Error())
}
log.Print("API available at localhost" + port)
log.Fatal(http.ListenAndServe(port, router))
}
const TRACE_HEADER = "X-Correlation-ID"
func RequestTraceMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if w.Header().Get(TRACE_HEADER) == "" {
if r.Header.Get(TRACE_HEADER) != "" {
w.Header().Set(TRACE_HEADER, "traceid")
} else {
w.Header().Set(TRACE_HEADER, "traceid")
}
}
next.ServeHTTP(w, r)
})
}