Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Routing and Handlers

Redirects and Custom 404 Pages in Gin

Send redirects with c.Redirect, rewrite routes internally, handle unknown URLs with NoRoute and wrong methods with NoMethod, and try runnable net/http stand-ins for each behavior.

Not every request matches a route, and not every route should answer with a body. Sometimes the right response is "go to this other URL", and sometimes it is "there is nothing here". Gin gives you small, precise tools for both: c.Redirect for sending visitors elsewhere, NoRoute for unknown paths and NoMethod for known paths used with the wrong verb. This lesson follows Responses: JSON, XML, HTML and More and finishes the routing toolbox before we move on to binding data.

Gin itself cannot run on this site, so the Gin code below is read-only. Each section also has a runnable Go stand-in built on net/http, clearly labelled, that shows the same HTTP behavior.

Redirects with c.Redirect

c.Redirect(code, location) writes a Location header and a status code in the 3xx range. The code tells the client how to treat the move:

Code Name Meaning Method kept?
301 Moved Permanently The old URL is gone for good; caches may remember it Clients may change POST to GET
302 Found Temporary move (old habit, ambiguous) Clients may change POST to GET
303 See Other After a POST, show a result page with GET Becomes GET
307 Temporary Redirect Temporary, repeat the same request Yes
308 Permanent Redirect Permanent, repeat the same request Yes
Go
r.GET("/old-docs", func(c *gin.Context) {
	c.Redirect(http.StatusMovedPermanently, "/docs") // 301
})

r.POST("/login", func(c *gin.Context) {
	// ... check credentials ...
	c.Redirect(http.StatusSeeOther, "/dashboard") // 303: browser follows with GET
})

The post-then-redirect pattern (often called Post/Redirect/Get) prevents a duplicate form submission when the user presses reload: the browser reloads the GET page, not the POST.

Use 301 or 308 only when you are sure. Browsers cache permanent redirects aggressively, and a mistake can keep following visitors long after you fix it. For anything that might change, prefer 302, 303 or 307.

Redirecting to another site

c.Redirect accepts absolute URLs too:

Go
r.GET("/github", func(c *gin.Context) {
	c.Redirect(http.StatusFound, "https://github.com/gin-gonic/gin")
})

Never build that location from user input without checking it. A link like /go?next=https://evil.example that you blindly redirect to is called an open redirect, and attackers use it to make phishing links look like they come from your domain. The safe rule is to accept only local paths (starting with a single /, not //) or to look the target up in an allow-list.

Internal "redirects": HandleContext

A redirect makes the client send a second request. Sometimes you want to serve a different route without telling the client. Gin lets you rewrite the path and run the router again:

Go
r.GET("/home", func(c *gin.Context) {
	c.Request.URL.Path = "/index"
	r.HandleContext(c)
})
r.GET("/index", func(c *gin.Context) {
	c.String(http.StatusOK, "welcome")
})

The browser still shows /home, only one request is made, and the response comes from /index. Use it sparingly: it makes the code path harder to follow, and a loop (two routes rewriting to each other) hangs the request.

Trailing slashes

By default Gin redirects between /users and /users/ when only one of them is registered. A GET gets a 301, other methods get a 307 so the body is not lost. You can turn the behavior off with r.RedirectTrailingSlash = false. Related switches are RedirectFixedPath (try to fix the case or extra slashes of a path) and HandleMethodNotAllowed, which we meet next.

Custom 404 with NoRoute

When no route matches, Gin answers with a plain 404 page not found. Replace that with NoRoute:

Go
r.NoRoute(func(c *gin.Context) {
	c.JSON(http.StatusNotFound, gin.H{
		"error": "not_found",
		"path":  c.Request.URL.Path,
	})
})

NoRoute registers handlers that run with the global middleware (logger, recovery, CORS) but only when nothing else matched. For an API you want a JSON error, for a website you want an HTML page:

Go
r.NoRoute(func(c *gin.Context) {
	c.HTML(http.StatusNotFound, "404.tmpl", gin.H{"path": c.Request.URL.Path})
})

Always pass the status code yourself. c.HTML(200, ...) for a missing page is called a "soft 404"; search engines treat it as a real page and keep indexing it.

Wrong method with NoMethod

If /users exists for GET and someone sends DELETE /users, the path is known but the method is not allowed. By default Gin reports 404 for that. Turn on proper handling with:

Go
r.HandleMethodNotAllowed = true
r.NoMethod(func(c *gin.Context) {
	c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "method_not_allowed"})
})

With the switch on, Gin answers 405 Method Not Allowed and should include an Allow header listing the permitted methods. Clients and API tools rely on it, so set it yourself in the handler when you can (c.Header("Allow", "GET, POST")).

Stand-in: redirects

This runnable program uses the standard library to produce each redirect type and prints the status code and Location header, exactly what a client sees. It uses httptest, so no network is needed.

Go Stand-in: the redirect codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

http.Redirect is the standard-library twin of c.Redirect. It also writes a tiny HTML body with a link for old clients; Gin does the same for GET requests.

Stand-in: 404 and 405

Go's standard mux already knows the difference between "no such path" and "wrong method". The stand-in below wraps it so unknown paths get a JSON 404 and wrong methods get a 405 with an Allow header, which is what NoRoute and NoMethod achieve in Gin.

Go Stand-in: custom 404 and 405 responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first request passes straight through (the recorder only watches the status). The other two are intercepted and replaced. In Gin you would not need the wrapper: NoRoute and NoMethod are built in.

Which one should I use?

flowchart TD
    A["Request arrives"] --> B{"Path registered?"}
    B -- "no" --> C["NoRoute handlers (404)"]
    B -- "yes" --> D{"Method registered?"}
    D -- "yes" --> E["Your handler"]
    D -- "no" --> F{"HandleMethodNotAllowed?"}
    F -- "true" --> G["NoMethod handlers (405)"]
    F -- "false" --> C

Gin first matches the path, then the method.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After a successful form POST you want the browser to load a result page with GET. Which status fits best?

    303 explicitly tells the client to follow the redirect with GET, which is the Post/Redirect/Get pattern.
  2. 2. Which handler runs when a request path matches no route at all?

    NoRoute handlers (with the global middleware) answer unmatched paths.
  3. 3. What must you set so that DELETE /users (only GET registered) produces 405 instead of 404?

    HandleMethodNotAllowed is false by default; when true, Gin answers 405 and runs the NoMethod handlers.
  4. 4. Why is redirecting to a URL taken straight from a query parameter risky?

    Attackers craft links on your domain that bounce visitors to a malicious site. Allow only local paths or an allow-list.

Summary

  • c.Redirect(code, url) sends a 3xx response; use 303 after a POST, 301/308 only for permanent moves.
  • Never redirect to unchecked user input (open redirect).
  • r.HandleContext(c) re-routes internally without a second request.
  • NoRoute customizes 404 pages; always return a real 404 status.
  • NoMethod plus HandleMethodNotAllowed = true gives correct 405 responses.

Next: HTTP Status Codes and Error Responses shows how to report problems consistently.