package server import ( "log" "net/http" "net/http/httputil" "net/url" "git.secnex.io/secnex/api-gateway/config" "git.secnex.io/secnex/api-gateway/middlewares" "git.secnex.io/secnex/masterlog" ) type Routes struct { routes []config.RouteConfiguration handlers map[string]http.Handler } func NewRoutes(routes []config.RouteConfiguration, apis []config.ApiConfiguration) *Routes { handlers := createHandlers(routes, apis) return &Routes{routes: routes, handlers: handlers} } func findApi(apis []config.ApiConfiguration, id string) *config.ApiConfiguration { for _, api := range apis { if api.ID == id { return &api } } return nil } func createHandlers(routes []config.RouteConfiguration, apis []config.ApiConfiguration) map[string]http.Handler { handlers := make(map[string]http.Handler) for _, route := range routes { masterlog.Debug("Creating handler for route", map[string]interface{}{ "path": route.Path, "id": route.ID, }) api := findApi(apis, route.ID) if api == nil { log.Fatalf("API not found: %s", route.ID) continue } backendUrl, err := url.Parse( api.Target, ) if err != nil { log.Fatalf("Failed to parse backend URL: %v", err) } proxy := httputil.NewSingleHostReverseProxy(backendUrl) handlers[route.Path] = proxy if route.StripPrefix.Enabled { masterlog.Debug("Stripping prefix", map[string]interface{}{ "id": route.ID, "path": route.Path, "prefix": route.StripPrefix.Prefix, }) handlers[route.Path] = http.StripPrefix(route.StripPrefix.Prefix, handlers[route.Path]) } if route.Security.WAF.Enabled { masterlog.Debug("Applying WAF middleware", map[string]interface{}{ "id": route.ID, "path": route.Path, "methods": route.Security.WAF.Methods, }) handlers[route.Path] = middlewares.WAF(handlers[route.Path], route.Security.WAF) } if route.Security.Auth.Enabled { masterlog.Debug("Applying auth middleware", map[string]interface{}{ "id": route.ID, "path": route.Path, "type": route.Security.Auth.Type, "header": route.Security.Auth.Header, }) handlers[route.Path] = middlewares.Auth( handlers[route.Path], route.Security.Auth.Type, route.Security.Auth.Header, route.Security.Auth.Path, ) } } return handlers }