func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() }
type User struct { Name string `json:"name"` Email string `json:"email"` } func main() { r := gin.Default() r.POST("/users", func(c *gin.Context) { var user User if err := c.BindJSON(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) return } // save user to database or perform some action c.JSON(200, gin.H{ "message": "user created", }) }) r.Run() }In the example above, a POST request handler is created for `/users` endpoint. The endpoint expects a JSON payload with two fields - name and email. Upon receiving the request, the payload is decoded into a user struct. If the decoding fails, a JSON response with a status code of 400 and an error message is returned. If the decoding succeeds, the user is saved to the database, and a JSON response with a status code of 200 and a message confirming the user creation is returned. Overall, the Go github.com.gin-gonic.gin engine provides a simple and efficient way of creating RESTful APIs in Go. Its functionality is further enhanced by the numerous third-party packages available in the community.