Skip to content

Commit

Permalink
Refactor redirect request in gin.go (gin-gonic#1970)
Browse files Browse the repository at this point in the history
* Refactor redirect request in gin.go

* Update http status code
  • Loading branch information
nsiregar authored and ThomasObenaus committed Feb 19, 2020
1 parent 8207066 commit 95602a0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
2 changes: 1 addition & 1 deletion binding/form.go
Expand Up @@ -8,7 +8,7 @@ import (
"net/http"
)

const defaultMemory = 32 * 1024 * 1024
const defaultMemory = 32 << 20

type formBinding struct{}
type formPostBinding struct{}
Expand Down
31 changes: 16 additions & 15 deletions gin.go
Expand Up @@ -457,34 +457,35 @@ 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 {
req := c.Request
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()
}

0 comments on commit 95602a0

Please sign in to comment.