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:
Zeni Kim 2026-05-12 23:21:03 -05:00
parent 262c5befd9
commit 8446f6fb2a
2 changed files with 17 additions and 3 deletions

View file

@ -308,7 +308,11 @@ func (app *App) makeHTTPRouterHandlerFunc(h Controller, ms []Hook) httprouter.Ha
w.WriteHeader(ctx.Response.statusCode) w.WriteHeader(ctx.Response.statusCode)
} }
if ctx.Response.redirectTo != "" { 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 { } else {
w.Write(ctx.Response.body) w.Write(ctx.Response.body)
} }

View file

@ -20,6 +20,7 @@ type Response struct {
overrideContentType string overrideContentType string
isTerminated bool isTerminated bool
redirectTo string redirectTo string
redirectStatusCode int
HttpResponseWriter http.ResponseWriter HttpResponseWriter http.ResponseWriter
} }
@ -136,8 +137,10 @@ func (rs *Response) ForceSendResponse() {
rs.isTerminated = true rs.isTerminated = true
} }
// updates the redirect URL for the response and returns the modified Response. Validates the URL before setting it. // Redirect sends a redirect response to the given URL.
func (rs *Response) Redirect(url string) *Response { // 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() validator := resolveValidator()
v := validator.Validate(map[string]interface{}{ v := validator.Validate(map[string]interface{}{
"url": url, "url": url,
@ -153,6 +156,13 @@ func (rs *Response) Redirect(url string) *Response {
return rs return rs
} }
rs.redirectTo = url rs.redirectTo = url
if len(use303) > 0 && use303[0] {
rs.redirectStatusCode = http.StatusSeeOther // 303
} else {
rs.redirectStatusCode = http.StatusTemporaryRedirect // 307 (default)
}
return rs return rs
} }