package core import ( "fmt" "net/http" ) type ( ApiRoute struct { ServletRoute *ServletRoute HttpMethodRoutes *map[HttpMethod]ServletHandleFunction } ) type ( HttpMethod int ) const ( GET HttpMethod = iota POST PUT PATCH DELETE UNDEFINED ) func NewApiRoute(pattern string) *ApiRoute { functionMap := make(map[HttpMethod]ServletHandleFunction) ancestorRoute := NewServletRoute(pattern, createMethodHandler(&functionMap)) route := ApiRoute{ ancestorRoute, &functionMap, } return &route } func createMethodHandler(m *map[HttpMethod]ServletHandleFunction) ServletHandleFunction { 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 ServletHandleFunction) { (*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) } }