From 7698b1b5fd36d5bab7cb3bcfe6ab9a34b1af3d42 Mon Sep 17 00:00:00 2001 From: James Shubin Date: Fri, 16 Feb 2024 06:15:38 -0500 Subject: [PATCH] engine: resources: Add an http error wrapper This makes it easier to return errors more succinctly. --- engine/resources/http.go | 15 +++++++++------ engine/resources/http_flag.go | 3 +-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/engine/resources/http.go b/engine/resources/http.go index 01e8ceb9..3be456b8 100644 --- a/engine/resources/http.go +++ b/engine/resources/http.go @@ -244,8 +244,7 @@ func (obj *HTTPServerRes) ServeHTTP(w http.ResponseWriter, req *http.Request) { handle, err := os.Open(p) if err != nil { obj.init.Logf("could not open: %s", p) - msg, httpStatus := toHTTPError(err) - http.Error(w, msg, httpStatus) + sendHTTPError(w, err) return } @@ -960,16 +959,14 @@ func (obj *HTTPFileRes) ServeHTTP(w http.ResponseWriter, req *http.Request) { absPath, err := safepath.ParseIntoAbsPath(requestPath) if err != nil { obj.init.Logf("invalid input path: %s", requestPath) - msg, httpStatus := toHTTPError(err) - http.Error(w, msg, httpStatus) + sendHTTPError(w, err) return } handle, err := obj.getContent(absPath) if err != nil { obj.init.Logf("could not get content for: %s", requestPath) - msg, httpStatus := toHTTPError(err) - http.Error(w, msg, httpStatus) + sendHTTPError(w, err) return } @@ -1123,3 +1120,9 @@ func toHTTPError(err error) (msg string, httpStatus int) { //return "500 Internal Server Error", http.StatusInternalServerError return http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError } + +// sendHTTPError is a helper function for sending an http error response. +func sendHTTPError(w http.ResponseWriter, err error) { + msg, httpStatus := toHTTPError(err) + http.Error(w, msg, httpStatus) +} diff --git a/engine/resources/http_flag.go b/engine/resources/http_flag.go index a30de27f..7c86a4d0 100644 --- a/engine/resources/http_flag.go +++ b/engine/resources/http_flag.go @@ -122,8 +122,7 @@ func (obj *HTTPFlagRes) ServeHTTP(w http.ResponseWriter, req *http.Request) { //requestPath := req.URL.Path //if err := req.ParseForm(); err != nil { // needed to access querystring - // msg, httpStatus := toHTTPError(err) - // http.Error(w, msg, httpStatus) + // sendHTTPError(w, err) // return //} if obj.Key != "" {