Skip to content

Commit

Permalink
simplify handler logic
Browse files Browse the repository at this point in the history
simplify handler logic
  • Loading branch information
notnmeyer committed Oct 23, 2023
1 parent ac6db4f commit 2862d30
Showing 1 changed file with 19 additions and 29 deletions.
48 changes: 19 additions & 29 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,53 +32,43 @@ func main() {
}

func handler(w http.ResponseWriter, r *http.Request) {
responseBody, responseCode := buildResponse(r.Header)

w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(responseCode)
w.Write([]byte(responseBody))
}

func buildResponse(header map[string][]string) (string, int) {
var (
contentType = "application/json; charset=utf-8"
responseBody string
responseCode int
)

err := validateResponseBody(r.Header)
if err == nil {
responseBody = r.Header["X-Response-Json"][0]
} else {
responseBody = err.Error()
responseCode = http.StatusBadRequest
writeRequest(w, contentType, responseBody, responseCode)
return
responseBody, err := validateResponseBody(header)
if err != nil {
return err.Error(), http.StatusBadRequest

}

responseCode, err = validateResponseCode(r.Header)
responseCode, err = validateResponseCode(header)
if err != nil {
responseBody = err.Error()
responseCode = http.StatusBadRequest
writeRequest(w, contentType, responseBody, responseCode)
return
return err.Error(), http.StatusBadRequest
}

writeRequest(w, contentType, responseBody, responseCode)

// w.Header().Set("Content-Type", contentType)
// w.WriteHeader(responseCode)
// w.Write([]byte(responseBody))
}

func writeRequest(w http.ResponseWriter, contentType string, responseBody string, responseCode int) {
w.Header().Set("Content-Type", contentType)
w.WriteHeader(responseCode)
w.Write([]byte(responseBody))
return responseBody, responseCode
}

func validateResponseBody(header map[string][]string) error {
func validateResponseBody(header map[string][]string) (string, error) {
if _, exists := header["X-Response-Json"]; !exists {
return errorResponseFormatter("x-response-json must be set on the request")
return "", errorResponseFormatter("x-response-json must be set on the request")
}

if !isJSON(header["X-Response-Json"][0]) {
return errorResponseFormatter("x-response-json must be valid JSON")
return "", errorResponseFormatter("x-response-json must be valid JSON")
}

return nil
return header["X-Response-Json"][0], nil
}

func validateResponseCode(header map[string][]string) (int, error) {
Expand Down

0 comments on commit 2862d30

Please sign in to comment.