Standard library / net/http
http.Redirect()
Writes a redirect response with a Location header and appropriate status. Validate untrusted redirect destinations. Expected stdout: '303 /next\n'.
Formal Syntax & Structure
go syntaxgo
func Redirect(w ResponseWriter, r *Request, url string, code int)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| w | ResponseWriter | Destination writer. |
| r | *Request | Source reader. |
| url | string | Destination URL string. |
| code | int | HTTP status code. |
Working Example
Example Snippetgo
package main
import ( "fmt" "net/http" "net/http/httptest")
func main() { w := httptest.NewRecorder() http.Redirect(w, httptest.NewRequest("GET", "/", nil), "/next", 303) fmt.Println(w.Code, w.Header().Get("Location"))}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}