一、检查环境配置

Go环境配置(关键几项):

set GO111MODULE=on
GOMODCACHE=D:\devops\go\pkg\mod
GOPROXY=https://mirrors.aliyun.com/goproxy/
GOPATH=D:\devops\go
GOROOT=D:\Programs\Go
GOVERSION=go1.18.4

二、下载Gin

下载gin:

PS C:\Users\lam> go install github.com/gin-gonic/gin@latest
go: downloading github.com/gin-gonic/gin v1.8.1
go: downloading github.com/gin-contrib/sse v0.1.0
go: downloading github.com/mattn/go-isatty v0.0.14
go: downloading golang.org/x/net v0.0.0-20210226172049-e18ecbb05110
go: downloading github.com/go-playground/validator/v10 v10.10.0
go: downloading github.com/pelletier/go-toml/v2 v2.0.1
go: downloading github.com/ugorji/go/codec v1.2.7
go: downloading google.golang.org/protobuf v1.28.0
go: downloading github.com/go-playground/universal-translator v0.18.0
go: downloading github.com/leodido/go-urn v1.2.1
go: downloading golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97
go: downloading golang.org/x/text v0.3.6
go: downloading github.com/go-playground/locales v0.14.0
package github.com/gin-gonic/gin is not a main package

需要注意的是,GO111MODULE=on 模式下,下载好的gin包不在 $GOPATH/src** 目录下,而在 **$GOPATH/pkg/mod 目录下。

三、创建项目

创建一个项目:

PS D:\devops\go\src\github.com\lamxops> mkdir gogin    
PS D:\devops\go\src\github.com\lamxops> cd gogin
PS D:\devops\go\src\github.com\lamxops\gogin> go mod init gogin
go: creating new go.mod: module gogin

使用VSCode直接打开gogin项目文件夹(强调:注意是直接打开gogin项目文件夹),VSCode目录结构如下:
gogindir.png

创建一个测试main.go文件,采用Gin官方快速入门文档中提供的代码例子(https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go):

package main

import (
    "net/http"

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

var db = make(map[string]string)

func setupRouter() *gin.Engine {
    // Disable Console Color
    // gin.DisableConsoleColor()
    r := gin.Default()

    // Ping test
    r.GET("/ping", func(c *gin.Context) {
        c.String(http.StatusOK, "pong")
    })

    // Get user value
    r.GET("/user/:name", func(c *gin.Context) {
        user := c.Params.ByName("name")
        value, ok := db[user]
        if ok {
            c.JSON(http.StatusOK, gin.H{"user": user, "value": value})
        } else {
            c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})
        }
    })

    // Authorized group (uses gin.BasicAuth() middleware)
    // Same than:
    // authorized := r.Group("/")
    // authorized.Use(gin.BasicAuth(gin.Credentials{
    //      "foo":  "bar",
    //      "manu": "123",
    //}))
    authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
        "foo":  "bar", // user:foo password:bar
        "manu": "123", // user:manu password:123
    }))

    /* example curl for /admin with basicauth header
       Zm9vOmJhcg== is base64("foo:bar")

        curl -X POST \
          http://localhost:8080/admin \
          -H 'authorization: Basic Zm9vOmJhcg==' \
          -H 'content-type: application/json' \
          -d '{"value":"bar"}'
    */
    authorized.POST("admin", func(c *gin.Context) {
        user := c.MustGet(gin.AuthUserKey).(string)

        // Parse JSON
        var json struct {
            Value string `json:"value" binding:"required"`
        }

        if c.Bind(&json) == nil {
            db[user] = json.Value
            c.JSON(http.StatusOK, gin.H{"status": "ok"})
        }
    })

    return r
}

func main() {
    r := setupRouter()
    // Listen and Server in 0.0.0.0:8080
    r.Run(":8080")
}

这个时候,会看到 "github.com/gin-gonic/gin" 下划红线有如下提示错误:

could not import github.com/gin-gonic/gin (cannot find package "github.com/gin-gonic/gin" in any of 
    D:\Programs\Go\src\github.com\gin-gonic\gin (from $GOROOT)
    D:\devops\go\src\github.com\gin-gonic\gin (from $GOPATH))compiler(BrokenImport)

需要在gogin项目目录下执行 go mod tidy 命令,引用项目需要的依赖增加到go.mod文件:

PS D:\devops\go\src\github.com\lamxops\gogin> go mod tidy
go: finding module for package github.com/gin-gonic/gin
go: found github.com/gin-gonic/gin in github.com/gin-gonic/gin v1.8.1

会看到 go.mod 文件更新了,且新增了 go.sum 文件,且 import "github.com/gin-gonic/gin" 错误提示已消失。


另外需要注意的是,如果在VSCode中打开lamxops文件夹(该文件夹下有多个项目,包括gogin),而不是直接打开gogin项目文件下,import "github.com/gin-gonic/gin" 也会报如下错误:

could not import github.com/gin-gonic/gin (cannot find package "github.com/gin-gonic/gin" in any of 
    D:\Programs\Go\src\github.com\gin-gonic\gin (from $GOROOT)
    D:\devops\go\src\github.com\gin-gonic\gin (from $GOPATH))compiler(BrokenImport)

如果一定要打开lamxops文件夹,需要做一个额外操作,即运行go mod tidy命令后,打开 lamxops/gogin/go.mod 文件,点击 Create vendor directory 创建vendor目录:
gomodvendor.png

会生成,如上图中 gogin/vendor 目录,且 import "github.com/gin-gonic/gin" 错误提示已消失。

四、运行项目

命令行输入 go run main.go,运行成功后,浏览器访问对应路径即可,运行终端记录下了访问日志,如下图所示:
gorun.png