package server import ( "net/http" "strings" "git.secnex.io/secnex/api-gateway/config" "git.secnex.io/secnex/masterlog" "github.com/go-chi/chi/v5" ) type Routes struct { routes []Route } type Route struct { ID string Path string StripPrefix config.StripPrefix Api *Api } func NewRoutes(cfg *config.Configuration, apis Apis) *Routes { routes := make([]Route, 0) for _, route := range cfg.Routes { routes = append(routes, Route{ ID: route.ID, Path: route.Path, StripPrefix: route.StripPrefix, Api: apis[route.Api], }) } return &Routes{routes: routes} } func (rs *Routes) Register(r *chi.Mux) { for _, route := range rs.routes { masterlog.Info("Registering route", map[string]interface{}{ "id": route.ID, "path": route.Path, "api": route.Api.ID, }) handler := route.createHandler() r.Handle(route.Path, handler) } } func (r *Route) createHandler() http.Handler { handler := http.Handler(r.Api) if r.StripPrefix.Enabled { handler = newStripPrefixMiddleware(r.StripPrefix.Prefix, handler) } return handler } type stripPrefixMiddleware struct { prefix string handler http.Handler } func newStripPrefixMiddleware(prefix string, handler http.Handler) http.Handler { return &stripPrefixMiddleware{ prefix: prefix, handler: handler, } } func (m *stripPrefixMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Remove prefix from path if strings.HasPrefix(r.URL.Path, m.prefix) { r.URL.Path = strings.TrimPrefix(r.URL.Path, m.prefix) // Ensure path starts with / if !strings.HasPrefix(r.URL.Path, "/") { r.URL.Path = "/" + r.URL.Path } } m.handler.ServeHTTP(w, r) }