From 92692454dad649a8a12ab51c807e9618f8357a87 Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Sat, 12 Aug 2023 19:37:51 +0400 Subject: [PATCH] Inversed logic of if else statement to reduce nesting by 1. --- httpr.go | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/httpr.go b/httpr.go index 6a0163f..c201093 100644 --- a/httpr.go +++ b/httpr.go @@ -157,27 +157,29 @@ func New() *Router { } func (rr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if tree, ok := rr.tree[r.Method]; ok { - path, err := newPath(r.URL.Path) - if err != nil { - http.Error(w, err.Error(), http.StatusNotAcceptable) - return - } - - if handler, params := tree.get(path); handler != nil { - if params != nil { - r = r.WithContext(context.WithValue(r.Context(), ParamsKey, params)) - } - handler(w, r) - } else { - if rr.NotFoundHandler != nil { - rr.NotFoundHandler(w, r) - } else { - http.Error(w, "Not Found", http.StatusNotFound) - } - } - } else { + tree, ok := rr.tree[r.Method] + if !ok { http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + return + } + + path, err := newPath(r.URL.Path) + if err != nil { + http.Error(w, err.Error(), http.StatusNotAcceptable) + return + } + + if handler, params := tree.get(path); handler != nil { + if params != nil { + r = r.WithContext(context.WithValue(r.Context(), ParamsKey, params)) + } + handler(w, r) + } else { + if rr.NotFoundHandler != nil { + rr.NotFoundHandler(w, r) + } else { + http.Error(w, "Not Found", http.StatusNotFound) + } } }