diff options
author | Ben Morrison <ben@gbmor.dev> | 2020-05-06 00:01:29 -0400 |
---|---|---|
committer | Ben Morrison <ben@gbmor.dev> | 2020-05-06 00:01:29 -0400 |
commit | dda0e0760411b3a7c56d43eef9aab26137622eaa (patch) | |
tree | f4ff76d65ca9473546f05fda16b8ed8414c2ef5a | |
parent | a3c1e1c95798046f72e990412d7342789f047f22 (diff) | |
download | api-dda0e0760411b3a7c56d43eef9aab26137622eaa.tar.gz |
one validation function that branches off. be easier to test later.
-rw-r--r-- | http.go | 28 | ||||
-rw-r--r-- | main.go | 2 |
2 files changed, 17 insertions, 13 deletions
diff --git a/http.go b/http.go index 9584c10..c549cb6 100644 --- a/http.go +++ b/http.go @@ -9,26 +9,30 @@ import ( const mimePlain = "text/plain; charset=utf-8" const mimeJSON = "application/json; charset=utf-8" -// Simple HTTP method check -func methodHop(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet && r.Method != http.MethodHead { +// Validates the request and then sends it off to where it needs to go. +// Eventually. +func validateRequest(w http.ResponseWriter, r *http.Request) { + if !methodHop(r) { errHTTP(w, r, errors.New("405 Method Not Allowed"), http.StatusMethodNotAllowed) return } - formatHop(w, r) -} - -// Makes sure the format requested is either plaintext or JSON -func formatHop(w http.ResponseWriter, r *http.Request) { - split := strings.Split(r.URL.Path[1:], "/") - - if split[0] != "plain" && split[0] != "json" { + format := formatHop(r) + if format != "plain" && format != "json" { errHTTP(w, r, errors.New("400 Bad Request"), http.StatusBadRequest) return } +} + +// Simple HTTP method check +func methodHop(r *http.Request) bool { + return r.Method == http.MethodGet || r.Method == http.MethodHead +} - routingHop(w, r, split[0]) +// Makes sure the format requested is either plaintext or JSON +func formatHop(r *http.Request) string { + split := strings.Split(r.URL.Path[1:], "/") + return split[0] } // Chooses next hop based on the endpoint diff --git a/main.go b/main.go index 4fec978..079fd98 100644 --- a/main.go +++ b/main.go @@ -9,7 +9,7 @@ import ( func main() { mux := http.NewServeMux() - mux.HandleFunc("/", methodHop) + mux.HandleFunc("/", validateRequest) server := &http.Server{ Addr: ":9999", |