快速入门
在此快速入门中,我们将从代码段中获取见解,并学习如何
要求
- Go 1.16 或更高版本
安装
要安装 Gin 包,您需要先安装 Go 并设置 Go 工作空间。
- 下载并安装
$ go get -u github.com/gin-gonic/gin
或安装
$ go install github.com/gin-gonic/gin@latest
- 在代码中导入它
import "github.com/gin-gonic/gin"
- (可选)导入
net/http
。例如,如果使用http.StatusOK
等常量,则需要此项。
import "net/http"
- 创建项目文件夹并在其中
cd
$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
- 在项目中复制一个起始模板
$ curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go
- 运行项目
$ go run main.go
入门
不确定如何编写和执行 Go 代码?点击此处。
首先,创建一个名为 example.go
的文件
# assume the following codes in example.go file
$ touch example.go
接下来,将以下代码放入 example.go
中
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() // listen and serve on 0.0.0.0:8080
}
然后,您可以通过 go run example.go
运行代码
# run example.go and visit 0.0.0.0:8080/ping on browser
$ go run example.go