In the core's response.go, add an optional RedirectCodeSetter field or variadic use303 ...bool parameter to Redirect() and use the stored code + http.StatusSeeOther in core.go instead of the hardcoded http.StatusTemporaryRedirect, so that a POST handler can redirect to a GET route by calling c.Response.Redirect("/url", true).
This commit is contained in:
parent
262c5befd9
commit
8446f6fb2a
2 changed files with 17 additions and 3 deletions
6
core.go
6
core.go
|
|
@ -308,7 +308,11 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha
|
|||
w.WriteHeader(ctx.Response.statusCode)
|
||||
}
|
||||
if ctx.Response.redirectTo != "" {
|
||||
http.Redirect(w, r, ctx.Response.redirectTo, http.StatusTemporaryRedirect)
|
||||
statusCode := ctx.Response.redirectStatusCode
|
||||
if statusCode == 0 {
|
||||
statusCode = http.StatusTemporaryRedirect // default to 307
|
||||
}
|
||||
http.Redirect(w, r, ctx.Response.redirectTo, statusCode)
|
||||
} else {
|
||||
w.Write(ctx.Response.body)
|
||||
}
|
||||
|
|
|
|||
14
response.go
14
response.go
|
|
@ -20,6 +20,7 @@ type Response struct {
|
|||
overrideContentType string
|
||||
isTerminated bool
|
||||
redirectTo string
|
||||
redirectStatusCode int
|
||||
HttpResponseWriter http.ResponseWriter
|
||||
}
|
||||
|
||||
|
|
@ -136,8 +137,10 @@ func (rs *Response) ForceSendResponse() {
|
|||
rs.isTerminated = true
|
||||
}
|
||||
|
||||
// updates the redirect URL for the response and returns the modified Response. Validates the URL before setting it.
|
||||
func (rs *Response) Redirect(url string) *Response {
|
||||
// Redirect sends a redirect response to the given URL.
|
||||
// By default it uses 307 (Temporary Redirect) to preserve the HTTP method.
|
||||
// Pass true as the second argument to use 303 (See Other), which changes POST to GET.
|
||||
func (rs *Response) Redirect(url string, use303 ...bool) *Response {
|
||||
validator := resolveValidator()
|
||||
v := validator.Validate(map[string]interface{}{
|
||||
"url": url,
|
||||
|
|
@ -153,6 +156,13 @@ func (rs *Response) Redirect(url string) *Response {
|
|||
return rs
|
||||
}
|
||||
rs.redirectTo = url
|
||||
|
||||
if len(use303) > 0 && use303[0] {
|
||||
rs.redirectStatusCode = http.StatusSeeOther // 303
|
||||
} else {
|
||||
rs.redirectStatusCode = http.StatusTemporaryRedirect // 307 (default)
|
||||
}
|
||||
|
||||
return rs
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue