vinegar/servlet/dynamicRoute.go
2023-07-31 16:57:21 -04:00

90 lines
1.7 KiB
Go

package servlet
import (
"fmt"
"log"
"net/http"
)
type (
ApiRoute struct {
VinegarRoute *VinegarWebRoute
HttpMethodRoutes *map[HttpMethod]VinegarHandlerFunction
}
)
type (
HttpMethod int
)
const (
GET HttpMethod = iota
POST
PUT
PATCH
DELETE
UNDEFINED
)
func NewApiRoute(serv *VinegarHttpServlet, pattern string) *ApiRoute {
functionMap := make(map[HttpMethod]VinegarHandlerFunction)
ancestorRoute := NewServletRoute(pattern, createMethodHandler(&functionMap))
route := ApiRoute{
ancestorRoute,
&functionMap,
}
serv.AddRoute(route.VinegarRoute)
return &route
}
func createMethodHandler(m *map[HttpMethod]VinegarHandlerFunction) VinegarHandlerFunction {
return func(w http.ResponseWriter, req *http.Request) {
method := getHttpMethod(req)
fn, exists := (*m)[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 HttpMethod, handler VinegarHandlerFunction) {
(*api.HttpMethodRoutes)[method] = handler
}
func getHttpMethod(req *http.Request) HttpMethod {
switch req.Method {
case http.MethodGet:
return GET
case "POST":
return POST
case "PUT":
return PUT
case "PATCH":
return PATCH
case "DELETE":
return DELETE
case "UNDEFINED":
default:
return UNDEFINED
}
return UNDEFINED
}
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)
}