vinegar/servlet/Router.go
2023-08-01 12:53:09 -04:00

55 lines
1.1 KiB
Go

package servlet
import (
"encoding/json"
"errors"
"geniuscartel.xyz/vinegar/vinegarUtil"
"log"
"net/http"
"regexp"
)
type (
VinegarWebRouter struct {
Routes []*VinegarWebRoute
}
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)
}