0%

Go 注意

Window 上建立Golang开发环境记录

Go 的main 函数必须再main 包内

下面代码执行

1
2
3
4
5
6
package gotest

func main() {
print("111")
}

执行效果如下

1
2
> go run main.go
go run: cannot run non-main package

需要修改为

1
2
3
4
5
6
package main

func main() {
print("111")
}

执行

1
2
> go run main.go
111

Go mod 管理包

https://www.cnblogs.com/dhcn/p/11321376.html

需要在 项目文件夹下 创建mod

如果当前项目为hello

1
go mod init hello

那么在需要导入本地包的地方需要使用

import “hello”

需要的地方 import 需要的包

如 导入 github.com/gin-gonic/gin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
}

在项目目录下使用

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

再去跑项目

1
go run main.go

这个时候 go.mod 会变成

1
2
3
4
5
module hello

go 1.16

require github.com/gin-gonic/gin v1.6.3 // indirect

将 项目的模块 链接到项目上了

Go Swig

给项目生成API文档

在项目根目录下执行

1
swag init

Go gorm 数据库连接库

在本地项目中安装库

1
go get -u github.com/jinzhu/gorm

Go 包引用规则

如果要引用自己的包,则需要知道自己的代码需要哪个包下

go 1.12版本以后

在go.mod顶上有定义

1
2
module xxx

那么自己的代码就是在 xxx下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
E:.
│ go.mod
│ go.sum
│ main.go
├─conf
├─docs
│ docs.go
│ swagger.json
│ swagger.yaml
├─models
│ models.go
└─pkg
└─setting
setting.go

go.mod

1
2
3
4
5
6
7
8
9
10
11
module github.com/rcant/test

go 1.16

require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/gin-gonic/gin v1.6.3 // indirect
github.com/jinzhu/gorm v1.9.16 // indirect
github.com/mattn/go-sqlite3 v2.0.1+incompatible // indirect
github.com/swaggo/swag v1.7.0 // indirect
)

如果在main.go中想使用 setting

需要导入

1
2
3
4
5
6
package main

import (
"github.com/gin-gonic/gin"
"github.com/rcant/test/pkg/setting"
)

“github.com/rcant/test/pkg/setting” = “github.com/rcant/test” + “pkg/setting” = “Mod名称” + 相对根目录路径

需要注意的是 这里导入的是 mod名称 + 相对路径,路径不包含直接的文件

如果要指定文件则使用

1
2
3
4
5
6
package main

import (
"github.com/gin-gonic/gin"
setting "github.com/rcant/test/pkg/setting"
)

欢迎关注我的其它发布渠道