From fdc7f64d6fc68c6a905ca13bcb040c00190bb013 Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Thu, 20 Jan 2022 21:09:45 +0800 Subject: [PATCH] chore: update unauthorized callback calling order (#1469) * chore: update unauthorized callback calling order * chore: add comments --- core/limit/tokenlimit.go | 3 ++- core/mapping/unmarshaler.go | 4 +++- rest/handler/authhandler.go | 6 ++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/core/limit/tokenlimit.go b/core/limit/tokenlimit.go index dcab984b..9fabc8f6 100644 --- a/core/limit/tokenlimit.go +++ b/core/limit/tokenlimit.go @@ -112,7 +112,8 @@ func (lim *TokenLimiter) reserveN(now time.Time, n int) bool { // Lua boolean false -> r Nil bulk reply if err == redis.Nil { return false - } else if err != nil { + } + if err != nil { logx.Errorf("fail to use rate limiter: %s, use in-process limiter for rescue", err) lim.startMonitor() return lim.rescueLimiter.AllowN(now, n) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index c2fefcea..38703744 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -742,7 +742,9 @@ func getValueWithChainedKeys(m Valuer, keys []string) (interface{}, bool) { if len(keys) == 1 { v, ok := m.Value(keys[0]) return v, ok - } else if len(keys) > 1 { + } + + if len(keys) > 1 { if v, ok := m.Value(keys[0]); ok { if nextm, ok := v.(map[string]interface{}); ok { return getValueWithChainedKeys(MapValuer(nextm), keys[1:]) diff --git a/rest/handler/authhandler.go b/rest/handler/authhandler.go index 6756cf38..26aacca0 100644 --- a/rest/handler/authhandler.go +++ b/rest/handler/authhandler.go @@ -113,11 +113,13 @@ func unauthorized(w http.ResponseWriter, r *http.Request, err error, callback Un detailAuthLog(r, noDetailReason) } - writer.WriteHeader(http.StatusUnauthorized) - + // let callback go first, to make sure we respond with user-defined HTTP header if callback != nil { callback(writer, r, err) } + + // if user not setting HTTP header, we set header with 401 + writer.WriteHeader(http.StatusUnauthorized) } type guardedResponseWriter struct {