Go日常开发常用第三方库和工具介绍

2022-11-29 10:07:08

这里我主要将这些库分为两类:

    业务开发基础工具开发

    业务开发

    首先是业务开发,主要包含了>web、数据库、Redis 等。

    Gin

    首先是>

    当然和它配套的 github.com/swaggo/gin-… swagger 工具也是刚需;利用它可以生成 swagger 文档。

    GORM

    GORM>orm 的方式操作数据库,那就选它吧;同样的也是使用简单、资料较多。

    如果有读写分离需求,也可以使用 GORM 官方提供的插件 github.com/go-gorm/dbr… ,配合 GORM 使用也是非常简单。

    errors

    Go>

      包装异常包装堆栈等。

      常用的有以下 API:

      // WithMessagef annotates err with the format specifier.
      func WithMessagef(err error, format string, args ...interface{}) error
      
      // WithStack annotates err with a stack trace at the point WithStack was called.
      func WithStack(err error) error
      

      zorolog

      Go>

      "github.com/rs/zerolog/log"
      log.Debug().Msgf("OrderID :%s", "12121")
      

      excelize

      github.com/qax-os/exce…是一个读写>

      now

      github.com/jinzhu/now>

        获取当前的年月日、时分秒。不同时区支持。最后一周、最后一个月等。
        import "github.com/jinzhu/now"
        
        time.Now() // 2013-11-18 17:51:49.123456789 Mon
        
        now.BeginningOfMinute()        // 2013-11-18 17:51:00 Mon
        now.BeginningOfHour()          // 2013-11-18 17:00:00 Mon
        now.BeginningOfDay()           // 2013-11-18 00:00:00 Mon
        now.BeginningOfWeek()          // 2013-11-17 00:00:00 Sun
        now.BeginningOfMonth()         // 2013-11-01 00:00:00 Fri
        now.BeginningOfQuarter()       // 2013-10-01 00:00:00 Tue
        now.BeginningOfYear()          // 2013-01-01 00:00:00 Tue
        
        now.EndOfMinute()              // 2013-11-18 17:51:59.999999999 Mon
        now.EndOfHour()                // 2013-11-18 17:59:59.999999999 Mon
        now.EndOfDay()                 // 2013-11-18 23:59:59.999999999 Mon
        now.EndOfWeek()                // 2013-11-23 23:59:59.999999999 Sat
        now.EndOfMonth()               // 2013-11-30 23:59:59.999999999 Sat
        now.EndOfQuarter()             // 2013-12-31 23:59:59.999999999 Tue
        now.EndOfYear()                // 2013-12-31 23:59:59.999999999 Tue
        
        now.WeekStartDay = time.Monday // Set Monday as first day, default is Sunday
        now.EndOfWeek()                // 2013-11-24 23:59:59.999999999 Sun
        

        Decimal

        当业务上需要精度计算时>

        import (
        	"fmt"
        	"github.com/shopspring/decimal"
        )
        
        func main() {
        	price, err := decimal.NewFromString("136.02")
        
        	quantity := decimal.NewFromInt(3)
        	fee, _ := decimal.NewFromString(".035")
        	taxRate, _ := decimal.NewFromString(".08875")
        
        	subtotal := price.Mul(quantity)
        
        	preTax := subtotal.Mul(fee.Add(decimal.NewFromFloat(1)))
        
        	total := preTax.Mul(taxRate.Add(decimal.NewFromFloat(1)))
        
        	fmt.Println("Subtotal:", subtotal)                      // Subtotal: 408.06
        	fmt.Println("Pre-tax:", preTax)                         // Pre-tax: 422.3421
        	fmt.Println("Taxes:", total.Sub(preTax))                // Taxes: 37.482861375
        	fmt.Println("Total:", total)                            // Total: 459.824961375
        	fmt.Println("Tax rate:", total.Sub(preTax).Div(preTax)) // Tax rate: 0.08875
        }
        

        基本上你能想到的精度转换它都能做到;配合上 GORM 也可以将 model 字段声明为 decimal 的类型,数据库对应的也是 decimal ,这样使用起来时会更方便。

        Amount decimal.Decimal `gorm:"column:amout;default:0.0000;NOT NULL" json:"amout"` 
        

        configor

        github.com/jinzhu/conf…>YAML/JSON/TOML 等格式。

        go-cache

        github.com/patrickmn/g…>Guava cache,线程安全,使用简单;不需要分布式缓存的简单场景可以考虑。

        	c := cache.New(5*time.Minute, 10*time.Minute)
        	// Set the value of the key "foo" to "bar", with the default expiration time
        	c.Set("foo", "bar", cache.DefaultExpiration)
        

        copier

        github.com/jinzhu/copi…>Java 中的 BeanUtils.copy() 类似;可以将两个字段相同但对象不同的 struct 进行数据复制,也支持深拷贝。

        func Copy(toValue interface{}, fromValue interface{}) (err error) 
        

        在我们需要一个临时 struct 来存放数据时很有用,特别是一个 struct 中字段非常多时,一个个来回赋值确实有点费手指。

        但也要注意不要什么情况都使用,会带来一些弊端:

          当删除字段时,不能利用编译器提示。当一些字段需要额外人工处理时,代码不易阅读。反射赋值,有一定性能损耗。

          总之在业务开发时,还是建议人工编写,毕竟代码是给人看的。

          env

          github.com/caarlos0/en…>struct.

          type config struct {
          	Home string `env:"HOME"`
          }
          
          func main() {
          	cfg := config{}
          	if err := env.Parse(&cfg); err != nil {
          		fmt.Printf("%+v\n", err)
          	}
          
          	fmt.Printf("%+v\n", cfg)
          }
          

          这个在我们打包代码到不同的运行环境时非常有用,利用它可以方便的获取不同环境变量。

          user_agent

          github.com/mssola/user…>user-agent 的小工具。

          当我们需要在服务端收集 user-agen 时可以更快的读取数据。

          func main() {
              ua := user_agent.New("Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1")
          
              fmt.Printf("%v\n", ua.Mobile())   // => true
              fmt.Printf("%v\n", ua.Bot())      // => false
              fmt.Printf("%v\n", ua.Mozilla())  // => "5.0"
              fmt.Printf("%v\n", ua.Model())    // => "Nexus One"
              fmt.Printf("%v\n", ua.Platform()) // => "Linux"
              fmt.Printf("%v\n", ua.OS()) 
              }
          

          phonenumbers

          github.com/nyaruka/pho…>

          // parse our phone number
          num, err := phonenumbers.Parse("6502530000", "US")
          

          基础工具

          接下来是一些基础工具库,包含一些主流的存储的客户端、中间件等。

          gomonkey

          github.com/agiledragon…>mock 打桩工具,当我们写单元测试时,需要对一些非接口函数进行 mock 会比较困难,这时就需要用到它了。

          由于它是修改了调用对应函数时机器跳转指令,而 CPU 架构的不同对应的指令也不同,所以在我们使用时还不兼容苹果的 M1 芯片,不过目前应该已经兼容了,大家可以试试。

          goconvey

          github.com/smartystree…>go test 命令。

            提供可视化 web UI。与 IDE 集成显示单元覆盖率。

            dig

            github.com/uber-go/dig>

              所有的对象都是单例。有一个统一的地方管理对象。使用时直接传递对象当做参数进来即可(容器会自动注入)。

              当然也有一些不太方便的地方:

                不熟悉时,一个对象是如何创建的不清楚。代码不是很好理解。

                我们内部有自己开发一个业务框架,其中所有的对象都交由 dig 进行管理,使用起来倒也是比较方便。

                cobra

                github.com/spf13/cobra是一个功能强大的命令行工具库,我们用它来实现内部的命令行工具,同时也推荐使用>

                BloomRPC

                github.com/uw-labs/blo…>gRPC 可视化工具,比起自己写 gRPC 客户端的代码那确实是要简单许多。

                但也有些小问题,比如精度。如果是 int64 超过了 2^56 服务端拿到的值会发生错误,这点目前还未解决。

                redis

                github.com/go-redis/re…>

                elastic

                github.com/olivere/ela…>elasticsearch 库。

                resty

                github.com/go-resty/re…>

                // Create a Resty Client
                client := resty.New()
                resp, err := client.R().
                    EnableTrace().
                    Get("https://httpbin.org/get")
                

                有点 Python requests 包那味了。

                pulsar-client-go

                Pulsar>

                go-grpc-middleware

                github.com/grpc-ecosys…>gRPC 中间件,可以自己实现内部的一些鉴权、元数据、日志等功能。

                go-pilosa

                github.com/pilosa/go-p…>

                pb

                github.com/cheggaaa/pb>

                总结

                最后汇总了一个表格,方便查看:

                名称类型功能星级
                Gin业务开发HTTP>⭐️⭐️⭐️⭐️⭐️
                GORM业务开发ORM 框架⭐️⭐️⭐️⭐️⭐️
                errors业务开发异常处理库⭐️⭐️⭐️⭐️⭐️
                zorolog业务开发日志库⭐️⭐️⭐️⭐️⭐️
                excelize业务开发Excel相关需求⭐️⭐️⭐️⭐️⭐️
                now业务开发时间处理⭐️⭐️⭐️⭐️️
                Decimal业务开发精度处理⭐️⭐️⭐️⭐️️
                configor业务开发配置文件⭐️⭐️⭐️⭐️️
                go-cache业务开发本地缓存⭐️⭐️⭐️
                copier业务开发数据复制⭐️⭐️⭐️️️
                env业务开发环境变量⭐️⭐️⭐️️️
                user_agent业务开发读取 user-agent⭐️⭐️⭐️️️
                phonenumbers业务开发手机号码验证⭐️⭐️⭐️️️
                gomonkey基础工具mock工具⭐️⭐️⭐️⭐️⭐
                goconvey基础工具单测覆盖率⭐️⭐️⭐️⭐️⭐
                dig基础工具依赖注入⭐️⭐️⭐️⭐️⭐
                cobra基础工具命令行工具⭐️⭐️⭐️⭐
                cli基础工具命令行工具⭐️⭐️⭐️⭐
                BloomRPC基础工具gRPC 调试客户端⭐️⭐️⭐️⭐
                redis基础工具Redis 客户端⭐️⭐️⭐️⭐
                elastic基础工具elasticsearch 客户端⭐️⭐️⭐️⭐
                resty基础工具http 客户端⭐️⭐️⭐️⭐
                pulsar-client-go基础工具Pulsar 客户端⭐️⭐️⭐️
                go-grpc-middleware基础工具gRPC 中间件⭐️⭐️⭐
                go-pilosa基础工具pilosa 客户端⭐️⭐️⭐️
                pb基础工具命令行工具进度条⭐️⭐️⭐️

                更多关于Go日常开发常用第三方库和工具请点击下面的相关链接