1、安装

要使用Gin非常简单,它和其他第三方 Golang 库一样。如果你是基于GOPATH开发的,你需要先使用

  1. go get -u github.com/gin-gonic/gin

下载gin,然后import导入即可。

如果你是用Go Module这种方式,使用import直接导入使用,然后你在go run运行的时候,会自动的下载gin包编译使用。当然你也可以通过go mod tidy来下载依赖的模块。

2、Hello Gin

src 目录下创建hello.go 文件

  1. package main
  2. import "github.com/gin-gonic/gin"
  3. func main() {
  4. r := gin.Default()
  5. r.GET("/", func(c *gin.Context) {
  6. c.JSON(200, gin.H{
  7. "welcome":"hello gin",
  8. })
  9. })
  10. // 启动HTTP服务,默认在0.0.0.0:8080启动服务 、localhost:8080、127.0.0.1:8080
  11. r.Run(":8080")
  12. }

然后我们运行它,

  1. git bash 下运行
  2. go run hello.go

打开浏览器,输入http://localhost:8080/就可以看到如下内容:

  1. {"welcome":"hello gin"}

3、注意点

3.1、报错:main.go:3:8: cannot find module providing package github.com/gin-gonic/gin: working directory is not part of a module

  1. 解决方法,当前目录分别运行下面两句代码:
  2. go mod init gin
  3. go mod edit -require github.com/gin-gonic/gin@latest

原文地址:
https://www.flysnow.org/2019/12/10/golang-gin-quick-start.html