Gin foundations · 5 MIN READ

404, 405 and redirects in Gin: answer misses in your own format and pick redirect codes by what must survive

Configure NoRoute, NoMethod and HandleMethodNotAllowed for consistent JSON 404 and 405 responses with a correct Allow header, and choose between 301, 302, 303, 307 and 308 for redirects.

A Gin engine answers misses on its own: a plain-text 404 for unknown paths and, by default, the same 404 for a known path with the wrong method. API clients that expect JSON errors choke on the text, and a 404 for a wrong method sends whoever is debugging in the wrong direction. A few lines of configuration fix both, and the same lesson applies to redirects: the status code decides whether the method and body survive.

gin · A MAP OF THE IDEA

  1. Enable 405 handling
  2. Set NoRoute and NoMethod
  3. Register HEAD if probed
  4. Choose redirect codes

Useful when

  • Clients get one JSON error format for hits and misses.
  • Allow headers tell callers exactly which methods exist.

Watch out

  • Group middleware, including auth and CORS on a group, never runs for misses.
  • A wrong 301 is cached by browsers and hard to undo.

Implementation & operation cost: Two handlers and one flag per engine, plus tests for each miss; the 405 path adds one lookup per method tree on every unmatched request.

01

Gin's defaults: plain text, and 404 for wrong methods

Gin keeps one routing tree per HTTP method and looks only in the tree for the request's method. With HandleMethodNotAllowed at its default of false, PUT /api/items is a 404 even when GET /api/items exists, and the body is the text/plain string "404 page not found". Setting HandleMethodNotAllowed to true makes Gin search the other trees after a miss, and NoRoute and NoMethod let you replace the default bodies with the error format the rest of your API uses.

02

An API that answers its misses

The program enables 405 handling, installs JSON NoRoute and NoMethod handlers, registers a small items API plus a health route for GET and HEAD, and adds four redirect routes. Thirteen requests cover wrong methods, HEAD, an unknown path, a trailing slash, each redirect code and an attempted open redirect.

go
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/gin-gonic/gin"
)

type apiError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

// safeNext accepts only same-site absolute paths, so ?next= cannot become an open redirect.
func safeNext(raw string) string {
	if !strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, "//") || strings.ContainsRune(raw, '\\') {
		return "/"
	}
	return raw
}

func newRouter() *gin.Engine {
	r := gin.New()
	r.HandleMethodNotAllowed = true
	r.NoRoute(func(c *gin.Context) {
		c.JSON(http.StatusNotFound, apiError{Code: "not_found", Message: "no such resource"})
	})
	r.NoMethod(func(c *gin.Context) {
		// Gin has already set Allow from the registered routes.
		c.JSON(http.StatusMethodNotAllowed, apiError{Code: "method_not_allowed", Message: "allowed: " + c.Writer.Header().Get("Allow")})
	})

	api := r.Group("/api")
	api.GET("/items", func(c *gin.Context) { c.JSON(http.StatusOK, []string{"a", "b"}) })
	api.POST("/items", func(c *gin.Context) { c.Status(http.StatusCreated) })
	api.GET("/items/:id", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"id": c.Param("id")}) })
	api.DELETE("/items/:id", func(c *gin.Context) { c.Status(http.StatusNoContent) })
	api.Match([]string{http.MethodGet, http.MethodHead}, "/health", func(c *gin.Context) { c.Status(http.StatusOK) })

	r.GET("/old-items", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "/api/items") })
	r.POST("/old-items", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/api/items") })
	r.POST("/checkout", func(c *gin.Context) { c.Redirect(http.StatusSeeOther, "/orders/42") })
	r.GET("/login/done", func(c *gin.Context) { c.Redirect(http.StatusSeeOther, safeNext(c.Query("next"))) })
	return r
}

func main() {
	gin.SetMode(gin.TestMode)
	r := newRouter()
	for _, line := range []string{
		"GET /api/items",
		"PUT /api/items",
		"HEAD /api/items",
		"PATCH /api/items/7",
		"HEAD /api/health",
		"GET /api/nothing",
		"GET /api/items/",
		"GET /old-items",
		"POST /old-items",
		"POST /checkout",
		"GET /login/done?next=/api/items",
		"GET /login/done?next=//evil.example",
		"GET /login/done?next=https://evil.example",
	} {
		method, target, _ := strings.Cut(line, " ")
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest(method, target, nil))
		out := []string{line, "->", fmt.Sprint(w.Code)}
		if allow := w.Header().Get("Allow"); allow != "" {
			out = append(out, "Allow: "+allow)
		}
		if loc := w.Header().Get("Location"); loc != "" {
			out = append(out, "Location: "+loc)
		}
		if strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") {
			out = append(out, w.Body.String())
		}
		fmt.Println(strings.Join(out, " "))
	}
}
Read the code

PUT /api/items finds no PUT route, so Gin checks the other trees, sets Allow: GET, POST and runs NoMethod, which reads that header back into its message. HEAD /api/items is a 405 as well: a GET route does not answer HEAD. /api/health was registered with Match for both methods and answers 200. /api/nothing runs NoRoute. /api/items/ never reaches either handler, because the trailing-slash redirect fires first. GET and POST /old-items show 301 versus 308, /checkout uses 303 after a POST, and safeNext turns //evil.example and https://evil.example into a redirect to /.

03

How Gin chooses between 404, 405 and a redirect

After a miss in the request method's tree Gin first tries a trailing-slash redirect, then, if RedirectFixedPath is on, a cleaned case-insensitive redirect. Only then, with HandleMethodNotAllowed on, does it look the path up in every other method's tree. If any match, it sets Allow to those methods, in the order their trees were first created on the engine, and runs the NoMethod chain with status 405; otherwise it runs the NoRoute chain with 404. If your handler writes nothing, Gin falls back to "405 method not allowed" or "404 page not found" as text/plain. Allow lists only methods you registered, so HEAD and OPTIONS never appear by implication. If a load balancer health-checks with HEAD, register it with Match or HEAD; http.Server discards a HEAD response body, but your handler still produces it. CORS preflight OPTIONS requests reach only engine-level middleware, so a CORS middleware must be installed with r.Use to answer them.

04

One error shape, including for misses

NoRoute and NoMethod handlers are combined with engine-level middleware from r.Use only; group middleware never runs for a miss, and c.FullPath() is empty there. Reuse the same error type your handlers return so clients parse every failure the same way, and keep the message fixed rather than echoing the request path, which is attacker-controlled text that may end up in a log viewer or an HTML page. Missing files under StaticFS also run the NoRoute handlers, as the HTML-templates lesson showed. A service that serves both pages and an API can branch on the path prefix.

go
r.NoRoute(func(c *gin.Context) {
	if strings.HasPrefix(c.Request.URL.Path, "/api/") {
		c.JSON(http.StatusNotFound, apiError{Code: "not_found", Message: "no such resource"})
		return
	}
	c.HTML(http.StatusNotFound, "404.html", gin.H{"Title": "Page not found"})
})
Read the code

This fragment assumes the apiError type from the program and a 404.html template loaded with SetHTMLTemplate. Requests under /api/ get the JSON error contract; everything else gets an HTML page with the same 404 status. Only one NoRoute chain exists per engine, so this branch is the single place where that policy lives.

05

Pick the redirect status by what must survive

301 and 302 are the historical codes, and clients may change a POST into a GET when following them; browsers also cache a 301 aggressively, so a mistaken permanent redirect is hard to take back. Use 302 or 307 while a move is still tentative. 303 See Other tells the client to fetch the result with GET, the post/redirect/get pattern after a form submission. 307 and 308 preserve the method and the body; 308 is permanent. Gin's own trailing-slash redirects use 301 for GET and 307 for other methods for exactly that reason. c.Redirect panics for codes outside 300 to 308, except 201 Created, and http.Redirect writes its short HTML body only for GET and HEAD. Never redirect to a client-supplied URL without validation: accept only paths that start with a single slash, and reject // and backslashes, because browsers treat /\evil.example like //evil.example, a protocol-relative URL to another host.

06

Test the misses as carefully as the hits

Extend the route-table test from the route-groups lesson: for every entry in r.Routes(), send the common methods that are not registered and assert 405, the exact Allow value and a JSON Content-Type. Add HEAD for every GET route you expect monitors to probe, an unknown path, a trailing-slash variant, each redirect's status and Location, and a list of hostile next values including //host, /\host and https://host.

TAKE THIS WITH YOU

Turn on HandleMethodNotAllowed, answer misses through NoRoute and NoMethod in your normal error format, register HEAD explicitly where it is probed, and use 303, 307 or 308 whenever the method or body must survive a redirect.

Check your understanding

Does Gin serve HEAD /items from a route registered only with api.GET("/items", ...)?

Go to the source

Progress stays in this browser. No account needed.