- 下載安裝gin
go get -u github.com/gin-gonic/gin
- 事例
編譯運行下邊的代碼
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 創建一個默認的路由引擎
r := gin.Default()
// GET:請求方式;/hello:請求的路徑
// 當客戶端以GET方法請求/hello路徑時,會執行后面的匿名函數
r.GET("/hello", func(c *gin.Context) {
// c.JSON:返回JSON格式的數據
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
// 啟動HTTP服務,默認在0.0.0.0:8080啟動服務
r.Run()
}
- 報錯
cannot find module providing package github.com/gin-gonic/gin: working directory is not part of a module
- 解決方案
$ go mod init gin
$ go mod edit -require github.com/gin-gonic/gin@latest
$ go mod tidy
在編譯運行,搞定