Appearance
Golang 库
通用库
- https://xorm.io/xorm ORM 库
GPT 提示词:使用 XORM(xorm.io/xorm) 实现 SQL
GPT 模版:使用 GORM(go-gorm/gorm) 实现 SQL
- https://github.com/mitchellh/mapstructure 支持从
map[string]interface{}解码 - https://github.com/go-resty/resty HTTP 和 SSE 客户端库
- https://github.com/moul/http2curl 将 HTTP 标准库的请求转化为 CURL 命令
- https://github.com/jinzhu/copier 结构体复制
- https://github.com/IBM/sarama Kafka 库
- https://github.com/redis/go-redis Redis 客户端
- gRPC protobuf
- https://github.com/jasonsoft/go-short-id
- singleflight 缓存击穿 docs
go
import (
shortid "github.com/jasonsoft/go-short-id"
)
func getShortID() string {
opt := shortid.Options{
Number: 8,
StartWithYear: false,
EndWithHost: false,
}
return shortid.Generate(opt)
}go
func getUuid() string {
return uuid.NewV4().String()
}项目结构
Web 开发
- https://github.com/gin-gonic/gin HTTP Web 框架
- https://github.com/swaggo/swag
- https://github.com/dgrijalva/jwt-go
日志
测试
命令行
在开发 Go 项目时,我们可以通过 Pflag 来解析命令行参数,通过 Viper 来解析配置文件,用 Cobra 来实现命令行框架
- https://github.com/spf13/viper 从命令行参数、环境变量、配置文件等位置读取配置项
viper.AddConfigPath 设置配置文件搜索路径
viper.SetConfigFile 和 viper.SetConfigType 设置配置文件名
viper.ReadInConfig 读取配置文件
读取完配置文件,然后在程序中使用 Get/Get<Type> 来读取配置项的值。
go
import (
"fmt"
"github.com/spf13/pflag"
)
func main() {
// 全局 FlagSet
var name string
pflag.StringVarP(&name, "name", "n", "Nobody", "名称")
pflag.Parse()
fmt.Printf("Hello, %s!\n", name)
nameflag := pflag.Lookup("name")
fmt.Printf("Hello, %s!\n", nameflag.Value.String())
// 自定义 flagSet
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.IntP("age", "a", 10, "Age")
flagSet.Parse([]string{"-a", "21"})
val, _ := flagSet.GetInt("age")
fmt.Println(val)
}谁在用?Kubernetes、Istio、Helm、Docker、Etcd 等
pflag 与标准库 flag 的区别:
- 支持直接组合短标志和长标志 例如
IntVarP函数 其中P代表 "P"refix, - 支持解析环境变量
- 支持更多的类型 例如
IntSlice、StringSlice
go
package colorutil
import "github.com/fatih/color"
func Red(a ...interface{}) string {
return color.New(color.FgRed).Sprint(a...)
}
func Green(a ...interface{}) string {
return color.New(color.FgGreen).Sprint(a...)
}
func Blue(a ...interface{}) string {
return color.New(color.FgBlue).Sprint(a...)
}
func Bold(a ...interface{}) string {
return color.New(color.Bold).Sprint(a...)
}
func Italic(a ...interface{}) string {
return color.New(color.Italic).Sprint(a...)
}
func Enable() {
color.NoColor = false
}
func Disable() {
color.NoColor = true
}工具
内置命令:
go buildgo rungo testgo fmtgo installgo get -ugo cleango mod- go mod init: 初始化新模块。
- go mod tidy: 移除未使用的依赖并下载缺失的模块。
- go mod vendor: 将依赖复制到 vendor 目录。
- go mod download: 下载依赖模块到本地缓存。
go generatego docgo listgo envgo vet
其它:
单元测试
goroutine 虽然很轻量,但还是会消耗资源,如果我们需要处理几百上千的并发,就需要用协程池来复用协程,达到节省资源的目的。有很多优秀的协程包可供我们直接使用,比如 ants、 tunny 等