2022年最新整理7个必备Golang开源类库,武装生产力

https://static.ffeeii.com/ffeeii.com/2022/03/image.png

随着云计算的大力发展,“东数西算”工程正式全面启动,作为背后的云计算主力开发语言Golang,那是必须会更热门。本文整理项目中用的比较好的各开源库,只推荐1个,减轻技术选型压力。

1、Http框架 Gin

Github star 56.2K,推荐指数 ★★★★★ Github地址:https://github.com/gin-gonic/gin

Gin 是一个用 Go (Golang) 编写的 HTTP web框架,拥有更好性能的 API 框架,文档非常完全,很多微服务也很方便集成。其他框架不推荐,Gin 绝对最优秀的。

touch example.go
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() // 监听并在 0.0.0.0:8080 上启动服务
}
go run example.go

2、 ORM:Gorm

Github star 27.1K,推荐指数 ★★★★☆ Github地址:https://github.com/go-gorm/gorm/

官网:https://gorm.io/

推荐理由:代码最优雅,场景最丰富,满足你的SQL场景需求。

  • 全功能 ORM
  •  关联 (拥有一个,拥有多个,属于,多对多,多态,单表继承)
  •  Create,Save,Update,Delete,Find 中钩子方法
  •  支持 Preload、Joins 的预加载
  •  事务,嵌套事务,Save Point,Rollback To to Saved Point
  •  Context、预编译模式、DryRun 模式
  •  批量插入,FindInBatches,Find/Create with Map,使用 SQL 表达式、Context Valuer 进行 CRUD
  •  SQL 构建器,Upsert,锁,Optimizer/Index/Comment Hint,命名参数,子查询
  •  复合主键,索引,约束
  •  自动迁移
  •  自定义 Logger
  •  灵活的可扩展插件 API:Database Resolver(多数据库,读写分离)、Prometheus…
  •  每个特性都经过了测试的重重考验
  •  开发者友好

3、配置管理:viper

Github star 18.5K,推荐指数 ★★★★☆ Github地址:https://github.com/spf13/viper

官方例子非常易用。

  • 支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多种格式的配置文件;
  • 可以设置监听配置文件的修改,修改时自动加载新的配置;
  • 从环境变量、命令行选项和io.Reader中读取配置;
  • 从远程配置系统中读取和监听修改,如 etcd/Consul;
  • 代码逻辑中显示设置键值。

4、日志管理:zap

Github star 15.1K,推荐指数 ★★★★☆ Github地址:https://github.com/uber-go/zap

logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
sugar := logger.Sugar()
sugar.Infow("failed to fetch URL",
  // Structured context as loosely typed key-value pairs.
  "url", url,
  "attempt", 3,
  "backoff", time.Second,
)
sugar.Infof("Failed to fetch URL: %s", url)

5、Redis

Github star 13.7K,推荐指数 ★★★★☆ Github地址:https://github.com/go-redis/redis 如果你用的缓存或队列是Redis,那就用它,用它,用它。

6、消息队列 asynq

Github star 2.8K,推荐指数 ★★★★☆ Github地址 https://github.com/hibiken/asynq

asynq是简单、可靠、高效的分布式任务队列。

运行实例: https://static.ffeeii.com/ffeeii.com/2022/03/asynq.jpg

7、依赖注入 wire

Github star 7.6K,推荐指数 ★★★★☆ Github地址 https://github.com/google/wire/

当代码充斥着init函数、global变量,wire是极好的代码组织能力。