package servlet import ( "encoding/json" "errors" "geniuscartel.xyz/vinegar/vinegarUtil" "log" "net/http" "regexp" ) type ( VinegarWebRouter struct { Routes []*VinegarWebRoute } // VinegarWebRoute defines a single route in the router. // It contains the following fields: // //Pattern - A regexp.Regexp instance that matches against the request URL path. // //Handler - A VinegarHandlerFunction to call when the route matches a request. // //Cache - An optional vinegarUtil.Cache instance to enable caching for this route. // //VinegarWebRoute is used to define custom routes to handle requests in the //VinegarWebRouter. Routes should be added to the router using: // // router.AddRoute(route) // //The router will match incoming requests against route patterns in order. //When a match is found, the Handler is executed to handle the request. // //Example usage: // // route := VinegarWebRoute{ // Pattern: regexp.MustCompile("/users"), // Handler: myUserHandler, // } // router.AddRoute(&route) VinegarWebRoute struct { Pattern *regexp.Regexp Handler VinegarHandlerFunction Cache vinegarUtil.Cache } ) func (s *VinegarWebRouter) AddRoute(route *VinegarWebRoute) { route.Announce() s.Routes = append(s.Routes, route) } func (r *VinegarWebRouter) RouteRequest(w http.ResponseWriter, req *http.Request) error { path := req.URL.Path for _, route := range r.Routes { if route.Pattern.MatchString(path) { log.Printf("SERVING: [%s]=>{%s}\n", path, route.Pattern.String()) go route.Handler(w, req) return nil } } notFoundHandler(w, req) return errors.New("failed to match route for [" + path + "]") } func notFoundHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) errorResponse := ErrorResponse{ Code: http.StatusNotFound, Message: "The requested resource could not be found.", } jsonBytes, _ := json.Marshal(errorResponse) w.Header().Add("Content-Type", "application/json") w.Write(jsonBytes) }