初探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-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"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM