SoFunction
Updated on 2025-03-02

Getting started tutorial for gin with Go Web Framework

At present, the Go-based web framework is also full of flowers. The reason why I chose gin is no other reason, because it has the largest number of stars on github, and from the perspective of README, its documentation is also quite rich.

Install gin

Just use go get /gin-gonic/gin directly.

There are many examples provided in the official README. For example, the simplest example code:

package main
import "/gin-gonic/gin"
func main() {
 r := ()
 ("/ping", func(c *) {
 (200, {
  "message": "pong",
 })
 })
 () // listen and serve on 0.0.0.0:8080
}

routing

router := () // The default is the Logger and Recovery middlewarerouter := () // Routing without middleware(()) // This method can be used to indicate middleware("/test", MyMiddleware(), testEndpoint) // This method can also be used to add middleware to the specified route("/someGet", getting) // Support all Restful operations//Route with parameters("/user/:name", func(c *) {
 name := ("name")
})

// Parameters optional/wildcard function("/user/:name/*action", ...)

//Route groupingv1 := ("/v1")
{
  ("/login", loginEndpoint)
  ("/submit", submitEndpoint)
}
(AuthRequired()) {} // The routing packet specifies the middleware separately

Request and Response

ask

// Get the routing parameters, assuming that the route is "/user/:name"("name")

// Get query parameters("name")
("name", "Guest")

// Get form parameters("name")
("name")

Parameter binding

Request verification

response

// Return a simple string(200, "pong")

// Return JSON data(200, {
  "message": "pong",
})

// Redirect(, "")

middleware

Custom middleware

BasicAuth Middleware

Asynchronous coroutine

gin can use coroutines to implement asynchronous tasks, but at this time, it needs to copy the context manually and can only be readable.

("/async", func(c *) {
  cCp := ()
  go func() {
    (5 * )
    ("Done! in path" + )
  }()
})

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.