go version // output: go version go1.16.2 windows/amd64
不支持Go-mod的方法
更推荐大家使用Go-mod方法。
安装引入Gin,net/http包
1 2
go get -u github.com/gin-gonic/gin // go: downloading xxxx.......
创建.go代码文件,并按照官方教程拷贝一个模板文件:
1 2 3
curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go // curl: The term 'curl' is not recognized as a name of a cmdlet, function, script file, or executable program. // Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
funcsetupRouter() *gin.Engine { // Disable Console Color // gin.DisableConsoleColor() r := gin.Default()
// Ping test r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })
// Get user value r.GET("/user/:name", func(c *gin.Context) { user := c.Params.ByName("name") value, ok := db[user] if ok { c.JSON(http.StatusOK, gin.H{"user": user, "value": value}) } else { c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"}) } })
PS D:\lean_space\gin> go run main.go [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 /ping --> main.setupRouter.func1 (3 handlers) [GIN-debug] GET /user/:name --> main.setupRouter.func2 (3 handlers) [GIN-debug] POST /admin --> main.setupRouter.func3 (4 handlers) [GIN-debug] Listening and serving HTTP on :8080 [GIN] 2021/06/03 - 21:35:31 |?[97;42m 200 ?[0m| 0s | ::1 |?[97;46m POST ?[0m "/admin" [GIN] 2021/06/03 - 21:35:35 |?[97;42m 200 ?[0m| 0s | ::1 |?[97;44m GET ?[0m "/ping" [GIN] 2021/06/03 - 21:35:39 |?[97;42m 200 ?[0m| 0s | ::1 |?[97;44m GET ?[0m "/user/foo"