vinegar/servlet/dynamicRoute.go
2023-08-01 10:02:31 -04:00

66 lines
1.5 KiB
Go

package servlet
import (
"fmt"
"log"
"net/http"
)
type (
ApiRoute struct {
VinegarRoute *VinegarWebRoute
HttpMethodRoutes *map[string]VinegarHandlerFunction
}
)
//NewApiRoute this will cause a panic if serv is nil
func NewApiRoute(serv *VinegarWebServlet, pattern string) *ApiRoute {
functionMap := make(map[string]VinegarHandlerFunction)
ancestorRoute := NewServletRoute(pattern, createMethodHandler(&functionMap))
route := ApiRoute{
ancestorRoute,
&functionMap,
}
if serv != nil { //this will happen during testing
serv.Router.AddRoute(route.VinegarRoute)
}
return &route
}
func createMethodHandler(m *map[string]VinegarHandlerFunction) VinegarHandlerFunction {
return func(w http.ResponseWriter, req *http.Request) {
fn, exists := (*m)[req.Method]
if exists {
fn(w, req)
} else {
SendApiError(
w,
200,
404,
"Method ["+req.Method+"] does not exist for endpoint["+req.URL.Path+"].",
)
}
}
}
func (api *ApiRoute) RegisterHttpMethodHandler(method string, handler VinegarHandlerFunction) {
(*api.HttpMethodRoutes)[method] = handler
}
func (api *ApiRoute) AddGetHandler(handler VinegarHandlerFunction) {
(*api.HttpMethodRoutes)[http.MethodGet] = handler
}
func SendApiError(w http.ResponseWriter, httpCode int, messageCode int, message string) {
respMessage := fmt.Sprintf("{\"code\":%d, \"message\":\"%s\"}", messageCode, message)
log.Printf("[ERROR]\t%s\n", respMessage)
_, err := w.Write([]byte(respMessage))
if err != nil {
log.Println(err)
}
w.WriteHeader(httpCode)
}