Skip to content

Golang 库

通用库

GPT 提示词:使用 XORM(xorm.io/xorm) 实现 SQL

GPT 模版:使用 GORM(go-gorm/gorm) 实现 SQL

time.Time 类型转化错误


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 开发

日志

测试

命令行

在开发 Go 项目时,我们可以通过 Pflag 来解析命令行参数,通过 Viper 来解析配置文件,用 Cobra 来实现命令行框架


viper.AddConfigPath 设置配置文件搜索路径

viper.SetConfigFileviper.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 的区别:

  1. 支持直接组合短标志和长标志 例如 IntVarP 函数 其中 P 代表 "P"refix,
  2. 支持解析环境变量
  3. 支持更多的类型 例如 IntSliceStringSlice

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 build
  • go run
  • go test
  • go fmt
  • go install
  • go get -u
  • go clean
  • go mod
    • go mod init: 初始化新模块。
    • go mod tidy: 移除未使用的依赖并下载缺失的模块。
    • go mod vendor: 将依赖复制到 vendor 目录。
    • go mod download: 下载依赖模块到本地缓存。
  • go generate
  • go doc
  • go list
  • go env
  • go vet

其它:

  • delve 调试器
  • gofmt
  • goimport
  • golint 官方的 Go 代码风格检查工具
  • goconvey
  • gopls LSP

单元测试

uber/go-mock

gomock-tutorial

goroutine 虽然很轻量,但还是会消耗资源,如果我们需要处理几百上千的并发,就需要用协程池来复用协程,达到节省资源的目的。有很多优秀的协程包可供我们直接使用,比如 ants、 tunny 等