Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 39 ยท Routing and Handlers

Routes and HTTP Methods in Gin

Register Gin routes for GET, POST, PUT, PATCH and DELETE, learn what each method means, use Any, Match and Handle, return the right status codes and build a small CRUD API.

A route connects an HTTP method and a path to a handler function. When a request arrives, Gin looks up the method and path and runs the matching handler. This lesson covers the methods, what they mean, how to build a CRUD API, and what happens when no route matches. It continues from Structuring a Gin Project.

Registering routes

The engine has one registration method per HTTP method. Each takes a path and one or more handlers:

Go
r := gin.Default()

r.GET("/books", listBooks)
r.GET("/books/:id", getBook)
r.POST("/books", createBook)
r.PUT("/books/:id", replaceBook)
r.PATCH("/books/:id", updateBook)
r.DELETE("/books/:id", deleteBook)
r.HEAD("/books", headBooks)
r.OPTIONS("/books", optionsBooks)

The same path can appear several times with different methods; Gin keeps a separate routing tree per method. The path /books/:id contains a path parameter, covered in Path and Query Parameters.

What each method means

HTTP methods are a shared vocabulary. Using them correctly makes your API predictable, and lets caches, browsers and proxies behave properly.

Method Meaning Safe? Idempotent? Typical success status
GET Read a resource Yes Yes 200 OK
POST Create a resource, or run an action No No 201 Created
PUT Replace a resource completely No Yes 200 OK or 204 No Content
PATCH Change part of a resource No Not guaranteed 200 OK
DELETE Remove a resource No Yes 204 No Content
HEAD Like GET, headers only Yes Yes 200 OK
OPTIONS Ask what is allowed (used by CORS) Yes Yes 204 No Content

Safe means the request does not change server state. Idempotent means sending it several times has the same effect as sending it once. Never change data in a GET handler: browsers prefetch links, crawlers follow them, and an innocent page view could delete a record.

A CRUD API you can run

Here is the classic create-read-update-delete flow. The runnable program is a stand-in built on net/http; the handler logic is the same you would write with Gin, where c.JSON replaces the writeJSON helper.

Go Stand-in: CRUD for books with status 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.

Read the status codes in the output: 201 with a Location header after creation, 200 for reads and updates, 204 with no body after delete, 404 when the book is gone, 400 for malformed input. In real Gin the same flow looks like this:

Go
func createBook(c *gin.Context) {
	var in Book
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	in.ID = store.Next()
	c.Header("Location", "/books/"+in.ID)
	c.JSON(http.StatusCreated, in)
}

func deleteBook(c *gin.Context) {
	store.Delete(c.Param("id"))
	c.Status(http.StatusNoContent)
}

c.Status sets the code without a body. Binding is introduced properly in Binding JSON and Forms.

Any, Match and Handle

Sometimes one handler serves several methods:

Go
r.Any("/echo", echo)                               // all standard methods
r.Match([]string{"GET", "POST"}, "/search", search) // just these two
r.Handle("PROPFIND", "/dav", davHandler)            // a custom method

Any registers GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT and TRACE. Inside the handler you can branch on c.Request.Method. Prefer separate routes in API code; Any is mostly useful for proxies, webhooks that vary, and debugging endpoints.

Go Stand-in: one handler for several methods

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 DELETE request fails with 405 Method Not Allowed and an Allow header listing what is accepted. That is the right behavior for a path that exists with other methods.

404 versus 405 in Gin

By default Gin answers an unknown method on a known path with 404 page not found. If you want the more precise 405 plus an Allow header, switch it on:

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

Redirects and Custom 404 Pages covers NoRoute and NoMethod in more depth.

Choosing paths well

  • Use nouns, plural, lowercase: /books, /books/42/reviews, not /getBook or /createReview.
  • Express actions with the method, not the path. DELETE /books/42, not GET /books/42/delete.
  • Keep nesting shallow (two levels is plenty); filter with query strings instead, as in /reviews?book=42.
  • Version the API in the path (/api/v1/...) so you can change it later; route groups make this tidy.
  • Pick one convention for trailing slashes. Gin redirects /books/ to /books (or the reverse) automatically with 301 for GET and 307 otherwise, as long as only one form is registered.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which status code is the most fitting response after successfully creating a resource with POST?

    201 Created, ideally with a Location header pointing to the new resource, tells the client a new resource exists.
  2. 2. What does it mean that DELETE is idempotent?

    Deleting an already deleted resource leaves the server in the same state. The status code may differ, but the state does not.
  3. 3. Which Gin call registers one handler for GET and POST on /search only?

    Match takes a list of methods. Any registers every standard method, which is broader than you need.
  4. 4. Why should a GET handler never modify data?

    Clients and intermediaries assume GET has no side effects, so state changes belong in POST, PUT, PATCH or DELETE.
  5. 5. What does r.HandleMethodNotAllowed = true change?

    With the flag on, Gin replies 405 and an Allow header when the path exists but not for that method.

Summary

  • Register routes with r.GET, r.POST, r.PUT, r.PATCH, r.DELETE, r.HEAD and r.OPTIONS.
  • Use methods for their meaning: GET reads, POST creates, PUT replaces, PATCH changes part, DELETE removes.
  • Return precise status codes: 201 after create, 204 after delete, 400 for bad input, 404 for missing resources.
  • r.Any, r.Match and r.Handle register one handler for several or custom methods.
  • Enable HandleMethodNotAllowed to get 405 with an Allow header.
  • Name routes with plural nouns and keep nesting shallow.

Next: Path and Query Parameters reads values out of the URL.