11package route
22
33import (
4+ goflagsmode "github.com/ralvarezdev/go-flags/mode"
45 "net/http"
56)
67
@@ -16,13 +17,26 @@ type (
1617
1718 // Router is the route group struct
1819 Router struct {
19- mux * http.ServeMux
20+ mux * http.ServeMux
21+ path string
22+ mode * goflagsmode.Flag
23+ logger * Logger
2024 }
2125)
2226
2327// NewRouter creates a new router
24- func NewRouter () * Router {
25- return & Router {mux : http .NewServeMux ()}
28+ func NewRouter (path string , mode * goflagsmode.Flag , logger * Logger ) * Router {
29+ // Check if the path is empty
30+ if path == "" {
31+ path = "/"
32+ }
33+
34+ return & Router {
35+ mux : http .NewServeMux (),
36+ logger : logger ,
37+ path : path ,
38+ mode : mode ,
39+ }
2640}
2741
2842// NewRouterGroup creates a new route group
@@ -32,8 +46,19 @@ func NewRouterGroup(baseRoute *Router, path string) (*Router, error) {
3246 return nil , ErrNilRouter
3347 }
3448
49+ // Check the base route path
50+ routerPath := path
51+ if baseRoute .path != "/" {
52+ routerPath = baseRoute .path + path
53+ }
54+
3555 // Create a new router
36- instance := & Router {mux : http .NewServeMux ()}
56+ instance := & Router {
57+ mux : http .NewServeMux (),
58+ logger : baseRoute .logger ,
59+ path : routerPath ,
60+ mode : baseRoute .mode ,
61+ }
3762
3863 // Register the route group
3964 baseRoute .RegisterRouteGroup (path , instance )
@@ -48,7 +73,12 @@ func (r *Router) Handler() *http.ServeMux {
4873
4974// HandleFunc registers a new route with a path and a handler function
5075func (r * Router ) HandleFunc (path string , handler http.HandlerFunc ) {
76+ // Register the route
5177 r .mux .HandleFunc (path , handler )
78+
79+ if r .logger != nil && r .mode != nil && ! r .mode .IsProd () {
80+ r .logger .RegisterRoute (r .path , path )
81+ }
5282}
5383
5484// RegisterRoute registers a new route with a path and a handler function
@@ -63,7 +93,12 @@ func (r *Router) RegisterHandler(path string, handler http.Handler) {
6393 path = path [:len (path )- 1 ]
6494 }
6595
96+ // Register the route group
6697 r .mux .Handle (path + "/" , http .StripPrefix (path , handler ))
98+
99+ if r .logger != nil && r .mode != nil && ! r .mode .IsProd () {
100+ r .logger .RegisterRouteGroup (r .path , path )
101+ }
67102}
68103
69104// RegisterRouteGroup registers a new route group with a path and a router
0 commit comments