美文网首页
Golang + Gin初试

Golang + Gin初试

作者: 赤色要塞满了 | 来源:发表于2022-02-26 23:30 被阅读0次

安装配置Go

自行搜索下载(官网需要翻),Win还是Mac都可以下载安装程序,点击安装。Mac下还可以使用homebrew来安装,不过感觉手感差点。
安装后,会自动添加一些环境变量,Win如下:

# 用户变量
GOPATH: %USERPROFILE%\go # go get下载的包在这里,USERPROFILE就是C:\Users\yourname
Path: %USERPROFILE%\go\bin # go install编译的用户程序在这里
# 系统变量
Path: C:\Program Files\Go\bin # go本身运行目录

另外还会添加GOROOT,默认为安装目录C:\Program Files\Go
如果是Mac,一些变量也会自动添加,也可以自己vim ~/.bash_profile,添加如下变量:

export GO111MODULE=on # 去gopath下寻找包
export GOPROXY=https://goproxy.cn # go get代理
export GOROOT=/usr/local/go # go安装目录
export GOPATH=$HOME/go # go包下载目录
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin # go程序目录、编译目录

有的教程会推荐使用gopmgovendor等,简单试了试,基于GOPATH,且还是要翻,感觉不方便,直接用go modgo get好了。go get也是需要翻的,参考使用goproxy,亲测Windows有效:

$ go env -w GO111MODULE=on
$ go env -w GOPROXY=https://goproxy.cn,direct

go mod详细使用可参考go mod使用

试一试Gin

Gin是web框架,类似Python的Flask,首先建个工作目录E:\golang\src,放所有的源代码。也可以把GOPATH设置为E:\golang,这样src/bin/pkg就一起了,这也是常见的一个做法。好了,在src下建个新项目文件夹hellogin,并建一个文件main.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 (for windows "localhost:8080")
}

直接运行,会先报错working directory is not part of a module,那就运行如下:

go mod init hellogin

会生成go.mod文件以管理模块。再运行,应该还是报错,

E:\golang\src\hellogin>go run main.go
main.go:4:5: no required module provides package github.com/gin-gonic/gin; to add it:
        go get github.com/gin-gonic/gin

因为还没下载gin嘛,运行go get下载。

E:\golang\src\hellogin>go get github.com/gin-gonic/gin
go: downloading github.com/gin-gonic/gin v1.6.3
go: downloading github.com/gin-contrib/sse v0.1.0
go: downloading github.com/mattn/go-isatty v0.0.12
...

可以去之前的GOPATH目录下的pkg\mod\github.com找到下载的包。当然,如果之前已经下载过了,会提示go get: added github.com/gin-gonic/gin v1.6.3,自动把模块添加到go.mod文件了。好了,再运行一次。

E:\golang\src\hellogin>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.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://localhost:8080/ping,返回{"message":"pong"},大功告成!

配置swaggo

我们重新配置下项目的目录结构,如下:

image.png
main.go的代码如下:
package main

import (
    "github.com/gin-gonic/gin"
    swaggerFiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"

    "hellogin/controllers"
)

// @title Golang hellogin API
// @version 1.0
// @description This is a sample server hellogin server
// @host 127.0.0.1:8080
// @BasePath /api/v1
func main() {
    r := gin.Default()

    var c controllers.Controller

    v1 := r.Group("/api/v1")
    {
        users := v1.Group("/users")
        {
            users.GET(":id", c.GetUser)
            users.POST("", c.AddUser)
        }
    }

    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    r.Run(":8080")
}

userController.go的代码如下:

package controllers

import (
    "net/http"

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

type Controller struct{}

// @Summary Get an user
// @Description 获取用户信息
// @Tags 用户
// @Param id path int true "ID"
// @Success 200 {string} string "ok"
// @Router /user/{id} [get]
func (c *Controller) GetUser(ctx *gin.Context) {
    id := ctx.Param("id")
    users := make(map[string]string)
    users["1"] = "Tom"
    users["2"] = "Jerry"
    ctx.String(http.StatusOK, "Hello %s", users[id])
}

type Res struct {
    id        string `json:"id"`
    name      string `json:"name"`
    user_type string `json:"user_type"`
}

// @Summary Add an user
// @Description 提交用户信息
// @Tags 用户
// @Param id formData int true "ID"
// @Param name formData string true "姓名"
// @Param user_type formData string true "类别"
// @Success 200 {object} Res
// @Router /user [post]
func (c *Controller) AddUser(ctx *gin.Context) {
    id := ctx.PostForm("id")
    name := ctx.PostForm("name")
    user_type := ctx.DefaultPostForm("user_type", "student")

    ctx.JSON(200, Res{
        id:        id,
        name:      name,
        user_type: user_type,
    })
}

然后运行:

go init mod hellogin

会生成go.mod文件,然后运行:

go mod tidy

自动下载依赖并更新到go.mod文件,免得自己一个个的go get。接下来初始化swagger文档,不过先要安装个swag命令:

go get -u github.com/swaggo/swag/cmd/swag

然后初始化:

E:\golang\src\hellogin>swag init

会生成docs文件夹,需要引入到main.go,如下:

import (
    "github.com/gin-gonic/gin"
    swaggerFiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"

    "hellogin/controllers"
    _ "hellogin/docs"
)

重新运气,提示下载模板后,继续运行:

E:\golang\src\hellogin>go run main.go 
go: hellogin/docs: package github.com/alecthomas/template imported from implicitly required module; to add missing requirements, run:
        go get github.com/alecthomas/template@v0.0.0-20190718012654-fb15b899a751
E:\golang\src\hellogin>go get github.com/alecthomas/template@v0.0.0-20190718012654-fb15b899a751
E:\golang\src\hellogin>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    /api/v1/users/:id         --> hellogin/controllers.(*Controller).GetUser-fm (3 handlers)
[GIN-debug] POST   /api/v1/users             --> hellogin/controllers.(*Controller).AddUser-fm (3 handlers)
[GIN-debug] GET    /swagger/*any             --> github.com/swaggo/gin-swagger.CustomWrapHandler.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080

如果成功运行,访问http://localhost:8080/swagger/index.html查看。

image.png
OK! 后面就靠自己搭建了。

参考

gin-swagger
swaggo,这里有对swagger参数的很详细的介绍。

相关文章

网友评论

      本文标题:Golang + Gin初试

      本文链接:https://www.haomeiwen.com/subject/qlbcrrtx.html