package router import ( "context" "net/http" "strconv" "strings" "gocarlog/internal/handler" "gocarlog/internal/middleware" "gocarlog/internal/db" ) // ParamKey is used to store path parameters in the request context. type ParamKey struct{} // New creates and configures the HTTP router with all API routes. func New(database *db.Database) http.Handler { // Use a custom multiplexer since Go 1.19 ServeMux doesn't support // method routing or path parameters (e.g., /vehicles/:id). mux := &patternMux{} // --- Fuel endpoints --- mux.HandleFunc("GET", "/api/fuels", handler.HandleListFuels) // --- Vehicle endpoints --- mux.HandleFunc("POST", "/api/vehicles", handler.HandleCreateVehicle) mux.HandleFunc("GET", "/api/vehicles", handler.HandleListVehicles) // GET /api/vehicles/:id/consumption must be registered before the generic catch-all mux.HandleFunc("GET", "/api/vehicles/:id/consumption", handler.HandleConsumption) mux.HandleFunc("GET", "/api/vehicles/:id", handler.HandleGetVehicle) // --- Log endpoints --- mux.HandleFunc("POST", "/api/logs", handler.HandleCreateLog) mux.HandleFunc("GET", "/api/logs", handler.HandleListLogs) // --- Apply middleware chain --- // Order: CORS -> Logging -> WithDB -> mux var h http.Handler h = mux h = middleware.Logging(h) h = middleware.CORS(h) h = middleware.WithDB(database.DB)(h) return h } // patternMux is a simple multiplexer that supports method-based routing // and path parameters (e.g. :id) for Go 1.19 compatibility. type patternMux struct { routes []route } type route struct { method string pattern string handler http.HandlerFunc } func (m *patternMux) HandleFunc(method, pattern string, handler http.HandlerFunc) { m.routes = append(m.routes, route{method: method, pattern: pattern, handler: handler}) } func (m *patternMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { handler, params := m.match(r.Method, r.URL.Path) if handler == nil { http.NotFound(w, r) return } // Attach captured path parameters to context as int values if len(params) > 0 { intParams := make(map[string]int) for key, val := range params { if v, err := strconv.Atoi(val); err == nil { intParams[key] = v } } ctx := context.WithValue(r.Context(), ParamKey{}, intParams) r = r.WithContext(ctx) } handler(w, r) } // match tries to match the request against registered routes. func (m *patternMux) match(method, path string) (http.HandlerFunc, map[string]string) { for _, r := range m.routes { if r.method != method { continue } if params := matchPattern(r.pattern, path); params != nil { return r.handler, params } } return nil, nil } // matchPattern matches a pattern like /api/v1/vehicles/:id/consumption against a path. // Returns nil if no match, otherwise a map of captured parameters (as strings). func matchPattern(pattern, path string) map[string]string { pParts := strings.Split(strings.Trim(pattern, "/"), "/") aParts := strings.Split(strings.Trim(path, "/"), "/") if len(pParts) != len(aParts) { return nil } params := make(map[string]string) for i := range pParts { p := pParts[i] a := aParts[i] if strings.HasPrefix(p, ":") { params[p[1:]] = a } else if p != a { return nil } } return params }