Skip to content

简介

https://github.com/gin-gonic/gin

https://github.com/gin-gonic/examples

https://gin-gonic.com/zh-cn/

文档:

https://gin-gonic.com/zh-cn/docs/

快速开始

1
2
3
4
5
mkdir gin_test
cd gin_test
go mod init example.com/gin_test
go get -u github.com/gin-gonic/gin
touch example.go

接下来, 将如下的代码写入 example.go 中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

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

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}

然后, 执行 go run example.go 命令来运行代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$ go run example.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.main.func1 (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080

然后浏览器访问http://127.0.0.1:8080/ping,可以看到

1
{"message":"pong"}