附录B:第三方库推荐清单
附录B推荐Go常用的第三方库:Web框架(Gin、Echo)、ORM( GORM)、数据库(go-redis)、CLI(cobra)、日志(zap)等。注意:选择库时优先GitHub星数和最近更新时间。
使用方法:按需查阅
Gin(最流行)
Section titled “Gin(最流行)”轻量级Web框架,性能优秀。
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(":8080")}高性能、简洁的Web框架。
import "github.com/labstack/echo/v4"
func main() { e := echo.New() e.GET("/hello", func(c echo.Context) error { return c.String(200, "Hello") }) e.Start(":8080")}受Express启发的Web框架,性能接近fasthttp。
import "github.com/gofiber/fiber/v2"
func main() { app := fiber.New() app.Get("/hello", func(c *fiber.Ctx) error { return c.SendString("Hello") }) app.Listen(":8080")}GORM(ORM库)
Section titled “GORM(ORM库)”import "gorm.io/gorm"import "gorm.io/driver/sqlite"
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
// 自动迁移db.AutoMigrate(&User{})
// CRUDvar user Userdb.First(&user, 1)db.Create(&user)db.Model(&user).Update("Name", "new name")db.Delete(&user)sqlx(原生SQL)
Section titled “sqlx(原生SQL)”import ( "github.com/jmoiron/sqlx" _ "github.com/go-sql-driver/mysql")
db, _ := sqlx.Connect("mysql", "root:@tcp(localhost:3306)/test")
var users []Userdb.Select(&users, "SELECT * FROM users WHERE age > ?", 18)Redis客户端
Section titled “Redis客户端”import "github.com/redis/go-redis/v9"
rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379",})
ctx := context.Background()rdb.Set(ctx, "key", "value", 0)val, _ := rdb.Get(ctx, "key").Result()viper(配置库)
Section titled “viper(配置库)”import "github.com/spf13/viper"
viper.SetConfigName("config")viper.SetConfigType("yaml")viper.AddConfigPath(".")viper.ReadInConfig()
// 使用viper.GetString("database.host")viper.GetInt("database.port")viper.GetBool("debug")godotenv(环境变量)
Section titled “godotenv(环境变量)”import "github.com/joho/godotenv"
godotenv.Load() // 加载.env文件os.Getenv("DB_HOST")zap(高性能日志)
Section titled “zap(高性能日志)”import "go.uber.org/zap"
logger, _ := zap.NewProduction()defer logger.Sync()
logger.Info("info message", zap.String("key", "value"), zap.Int("count", 10),)
// 字段记录logger.Error("error occurred", zap.Error(err), zap.String("operation", "db_query"),)logrus(结构化日志)
Section titled “logrus(结构化日志)”import "github.com/sirupsen/logrus"
log := logrus.New()log.SetFormatter(&logrus.JSONFormatter{})
log.WithFields(logrus.Fields{ "user": "alice", "action": "login",}).Info("user logged in")cobra(CLI框架)
Section titled “cobra(CLI框架)”import "github.com/spf13/cobra"
var rootCmd = &cobra.Command{ Use: "app", Short: "My CLI app", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello") },}
var serveCmd = &cobra.Command{ Use: "serve", Short: "Start server", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Server started") },}
rootCmd.AddCommand(serveCmd)rootCmd.Execute()urfave/cli(简单CLI)
Section titled “urfave/cli(简单CLI)”import "github.com/urfave/cli/v3"
func main() { app := &cli.Command{ Name: "app", Usage: "My app", Action: func(ctx context.Context) error { fmt.Println("Hello!") return nil }, } app.Run(context.Background())}validator(数据验证)
Section titled “validator(数据验证)”import "github.com/go-playground/validator/v10"
type User struct { Name string `validate:"required,min=2,max=50"` Email string `validate:"required,email"` Age int `validate:"gte=0,lte=150"`}
validate := validator.New()err := validate.Struct(user)errors(错误包装)
Section titled “errors(错误包装)”import "github.com/pkg/errors"
err := errors.Wrap(originalErr, "操作失败")errors.Is(err, originalErr)errors.Cause(err)once(单次执行)
Section titled “once(单次执行)”import "golang.org/x/sync/once"
var onceFunc func()once := &once.Once{}
once.Do(func() { fmt.Println("只执行一次")})semaphore(信号量)
Section titled “semaphore(信号量)”import "golang.org/x/sync/semaphore"
sem := semaphore.NewWeighted(3)sem.Acquire(context.Background(), 1)defer sem.Release(1)
// 执行业务逻辑testify(断言库)
Section titled “testify(断言库)”import "github.com/stretchr/testify/assert"import "github.com/stretchr/testify/suite"
assert.Equal(t, expected, actual)assert.Nil(t, err)assert.Contains(t, str, "sub")assert.Len(t, slice, 3)
suite.Suiteginkgo(BDD测试)
Section titled “ginkgo(BDD测试)”import "github.com/onsi/ginkgo/v2"
var _ = Describe("Calculator", func() { It("should add numbers", func() { Expect(add(1, 2)).To(Equal(3)) })})| 类别 | 库 | 说明 |
|---|---|---|
| Web框架 | gin, echo, fiber | HTTP服务 |
| ORM | gorm, ent | 数据库ORM |
| 数据库驱动 | go-sql-driver/mysql, pgx | 数据库连接 |
| Redis | go-redis | Redis客户端 |
| 配置 | viper, godotenv | 配置管理 |
| 日志 | zap, logrus | 结构化日志 |
| 命令行 | cobra, urfave/cli | CLI应用 |
| 验证 | validator | 数据验证 |
| 错误 | pkg/errors | 错误包装 |
| 工具 | once, semaphore | 同步原语 |
| 测试 | testify, ginkgo | 测试框架 |
| API | chi, gorilla/mux | 路由库 |
| JSON | go-json, jsoniter | 高性能JSON |