初探gin框架

引入gin

go get -u -v github.com/gin-gonic/gin

Restful风格示例

package main

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

func getBook(c *gin.Context){
	c.JSON(200, gin.H{
		"message":"get book",
	})
}

func createBook(c *gin.Context){
	c.JSON(200, gin.H{
		"message": "create book",
	})
}

func updateBook(c *gin.Context){
	c.JSON(200, gin.H{
		"message":"update book",
	})
}

func deleteBook(c *gin.Context){
	c.JSON(200, gin.H{
		"message":"delete book",
	})
}

func main() {
	r:=gin.Default()// 使用默认engine
	r.GET("/book", getBook)// 配置路由
	r.POST("/book", createBook)
	r.PUT("/book", updateBook)
	r.DELETE("/book", deleteBook)
	r.Run(":9090")
}

使用postman测试一下

vscode里面有个vsc-postman插件,很好用。
初探gin框架
控制台也有相关输出:

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /book                     --> main.getBook (3 handlers)
[GIN-debug] POST   /create_book              --> main.createBook (3 handlers)
[GIN-debug] PUT    /update_book              --> main.updateBook (3 handlers)
[GIN-debug] DELETE /delete_book              --> main.deleteBook (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :9090
[GIN] 2021/12/05 - 20:01:23 | 200 |            0s |       127.0.0.1 | GET      "/book"
[GIN] 2021/12/05 - 20:01:34 | 200 |       582.9µs |       127.0.0.1 | POST     "/create_book"
[GIN] 2021/12/05 - 20:01:42 | 200 |       526.4µs |       127.0.0.1 | DELETE   "/delete_book"
[GIN] 2021/12/05 - 20:01:51 | 200 |            0s |       127.0.0.1 | PUT      "/update_book"
上一篇:go get 安装gin失败


下一篇:gin框架中多种数据格式返回请求结果