89 lines
1.6 KiB
Go
89 lines
1.6 KiB
Go
package servlet
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
type (
|
|
ApiRoute struct {
|
|
VinegarRoute *VinegarRoute
|
|
HttpMethodRoutes *map[HttpMethod]VinegarHandlerFunction
|
|
}
|
|
)
|
|
|
|
type (
|
|
HttpMethod int
|
|
)
|
|
|
|
const (
|
|
GET HttpMethod = iota
|
|
POST
|
|
PUT
|
|
PATCH
|
|
DELETE
|
|
UNDEFINED
|
|
)
|
|
|
|
func NewApiRoute(serv *VinegarServlet, 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 "GET":
|
|
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)
|
|
w.WriteHeader(httpCode)
|
|
|
|
_, err := w.Write([]byte(respMessage))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|