From 231ff00d1f77d30f8dd97278680d7731e1317d55 Mon Sep 17 00:00:00 2001 From: Ngalim Siregar Date: Tue, 26 Nov 2019 07:19:30 +0700 Subject: [PATCH] Refactor redirect request in gin.go (#1970) * Refactor redirect request in gin.go * Update http status code --- binding/form.go | 2 +- gin.go | 31 ++++++++++++++++--------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/binding/form.go b/binding/form.go index 9e9fc3de..b93c34cf 100644 --- a/binding/form.go +++ b/binding/form.go @@ -8,7 +8,7 @@ import ( "net/http" ) -const defaultMemory = 32 * 1024 * 1024 +const defaultMemory = 32 << 20 type formBinding struct{} type formPostBinding struct{} diff --git a/gin.go b/gin.go index caf4cf2c..c194d6bf 100644 --- a/gin.go +++ b/gin.go @@ -457,18 +457,11 @@ func redirectTrailingSlash(c *Context) { if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { p = prefix + "/" + req.URL.Path } - code := http.StatusMovedPermanently // Permanent redirect, request with GET method - if req.Method != "GET" { - code = http.StatusTemporaryRedirect - } - req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } - debugPrint("redirecting request %d: %s --> %s", code, p, req.URL.String()) - http.Redirect(c.Writer, req, req.URL.String(), code) - c.writermem.WriteHeaderNow() + redirectRequest(c) } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { @@ -476,15 +469,23 @@ func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { rPath := req.URL.Path if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { - code := http.StatusMovedPermanently // Permanent redirect, request with GET method - if req.Method != "GET" { - code = http.StatusTemporaryRedirect - } req.URL.Path = string(fixedPath) - debugPrint("redirecting request %d: %s --> %s", code, rPath, req.URL.String()) - http.Redirect(c.Writer, req, req.URL.String(), code) - c.writermem.WriteHeaderNow() + redirectRequest(c) return true } return false } + +func redirectRequest(c *Context) { + req := c.Request + rPath := req.URL.Path + rURL := req.URL.String() + + code := http.StatusMovedPermanently // Permanent redirect, request with GET method + if req.Method != "GET" { + code = http.StatusTemporaryRedirect + } + debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) + http.Redirect(c.Writer, req, rURL, code) + c.writermem.WriteHeaderNow() +}