1、在命令终端中,使用下面的命令下载并安装Gin框架:
go get -u github.com/gin-gonic/gin
2、在您的Go工作区创建一个main.go文件
touch main.go
3、在文件中编写如下代码:
package mainimport ("net/http""github.com/gin-gonic/gin")func main() {r := gin.Default() // 初始化一个http服务对象r.GET("/hi", func(c *gin.Context) {// 通过请求上下文对象Context, 直接往客户端返回一个jsonc.JSON(http.StatusOK, gin.H{"message": "hello world",})})r.Run() // listen and serve on 0.0.0.0:8080}
4、您可以通过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 /hi --> 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

与此同时,您将在运行终端中看到一个终端日志:
[GIN] 2021/10/13 - 10:47:36 | 200 | 109.2µs | 127.0.0.1 | GET "/hi"
至此,恭喜您已经成功运行了一个hello world的API。
gin.SetMode(gin.ReleaseMode) // 设置 release模式gin.SetMode(gin.DebugMode) // 或者 设置debug模式