moai-lang-go
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseQuick Reference (30 seconds)
快速参考(30秒)
Go 1.23+ Development Expert for high-performance backend systems and CLI applications.
Auto-Triggers: Files with .go extension, go.mod, go.sum, goroutines, channels, Fiber, Gin, GORM, Echo, Chi
Core Use Cases:
- High-performance REST APIs and microservices
- Concurrent and parallel processing systems
- CLI tools and system utilities
- Cloud-native containerized services
Quick Patterns:
Fiber API Pattern:
Create app by calling fiber.New function. Define a get route at api/users/:id with handler function that takes fiber.Ctx and returns error. In the handler, call c.JSON with fiber.Map containing id from c.Params. Call app.Listen on port 3000.
Gin API Pattern:
Create r by calling gin.Default function. Define a GET route at api/users/:id with handler function taking gin.Context pointer. In handler, call c.JSON with status 200 and gin.H containing id from c.Param. Call r.Run on port 3000.
Goroutine with Error Handling:
Create g and ctx by calling errgroup.WithContext with context.Background. Call g.Go with function that returns processUsers with ctx. Call g.Go with function that returns processOrders with ctx. If err from g.Wait is not nil, call log.Fatal with error.
适用于高性能后端系统和CLI应用的Go 1.23+开发专家。
自动触发场景:带有.go扩展名的文件、go.mod、go.sum、goroutine、channels、Fiber、Gin、GORM、Echo、Chi
核心适用场景:
- 高性能REST API和微服务
- 并发与并行处理系统
- CLI工具与系统实用程序
- 云原生容器化服务
快速模式示例:
Fiber API模式:
通过调用fiber.New函数创建应用。在api/users/:id路径定义GET路由,处理函数接收fiber.Ctx并返回error。在处理函数中,调用c.JSON并传入包含从c.Params获取的id的fiber.Map。调用app.Listen监听3000端口。
Gin API模式:
通过调用gin.Default函数创建r实例。在api/users/:id路径定义GET路由,处理函数接收gin.Context指针。在处理函数中,调用c.JSON并传入状态码200和包含从c.Param获取的id的gin.H。调用r.Run监听3000端口。
带错误处理的Goroutine:
通过errgroup.WithContext和context.Background创建g和ctx。调用g.Go传入返回processUsers(ctx)的函数。调用g.Go传入返回processOrders(ctx)的函数。如果g.Wait返回的err不为nil,调用log.Fatal输出错误。
Implementation Guide (5 minutes)
实现指南(5分钟)
Go 1.23 Language Features
Go 1.23语言特性
New Features:
- Range over integers using for i range 10 syntax and print i
- Profile-Guided Optimization PGO 2.0
- Improved generics with better type inference
Generics Pattern:
Create generic Map function with type parameters T and U as any. Accept slice of T and function from T to U. Create result slice of U with same length. Iterate range slice setting result elements to function applied to values. Return result.
新特性:
- 使用for i range 10语法遍历整数并打印i
- 基于性能分析的优化PGO 2.0
- 改进的泛型,提供更优的类型推断
泛型模式:
创建带有类型参数T和U(均为any)的泛型Map函数。接收T类型的切片和从T到U的函数。创建长度相同的U类型结果切片。遍历输入切片,将每个值应用函数后赋值给结果切片对应元素。返回结果切片。
Web Framework Fiber v3
Web框架Fiber v3
Create app with fiber.New passing fiber.Config with ErrorHandler and Prefork true. Use recover.New, logger.New, and cors.New middleware. Create api group at api/v1 path. Define routes for listUsers, getUser with id parameter, createUser, updateUser with id, and deleteUser with id. Call app.Listen on port 3000.
通过传入包含ErrorHandler和Prefork为true的fiber.Config调用fiber.New创建应用。使用recover.New、logger.New和cors.New中间件。在api/v1路径创建API分组。为listUsers、带id参数的getUser、createUser、带id的updateUser和带id的deleteUser定义路由。调用app.Listen监听3000端口。
Web Framework Gin
Web框架Gin
Create r with gin.Default. Use cors.Default middleware. Create api group at api/v1 path. Define GET for users calling listUsers, GET for users/:id calling getUser, POST for users calling createUser. Call r.Run on port 3000.
Request Binding Pattern:
Define CreateUserRequest struct with Name and Email fields. Add json tags and binding tags for required, min length 2, and required email validation. In createUser handler, declare req variable, call c.ShouldBindJSON with pointer. If error, call c.JSON with 400 status and error. Otherwise call c.JSON with 201 and response data.
通过gin.Default创建r实例。使用cors.Default中间件。在api/v1路径创建API分组。定义GET /users路由调用listUsers,GET /users/:id路由调用getUser,POST /users路由调用createUser。调用r.Run监听3000端口。
请求绑定模式:
定义包含Name和Email字段的CreateUserRequest结构体。添加json标签和binding标签,设置必填、最小长度2和邮箱格式验证。在createUser处理函数中,声明req变量,调用c.ShouldBindJSON传入其指针。如果返回错误,调用c.JSON返回400状态码和错误信息;否则返回201状态码和响应数据。
Web Framework Echo
Web框架Echo
Create e with echo.New. Use middleware.Logger, middleware.Recover, and middleware.CORS. Create api group at api/v1 path. Define GET for users and POST for users. Call e.Logger.Fatal with e.Start on port 3000.
通过echo.New创建e实例。使用middleware.Logger、middleware.Recover和middleware.CORS中间件。在api/v1路径创建API分组。定义GET /users和POST /users路由。调用e.Logger.Fatal(e.Start(":3000"))启动服务。
Web Framework Chi
Web框架Chi
Create r with chi.NewRouter. Use middleware.Logger and middleware.Recoverer. Call r.Route with api/v1 path and function. Inside, call r.Route with users path. Define Get for list, Post for create, Get with id parameter for single user. Call http.ListenAndServe on port 3000 with r.
通过chi.NewRouter创建r实例。使用middleware.Logger和middleware.Recoverer中间件。调用r.Route传入api/v1路径和处理函数。在内部调用r.Route传入users路径。定义Get /路由(列表)、Post /路由(创建)、带id参数的Get /:id路由(单用户)。调用http.ListenAndServe(":3000", r)启动服务。
ORM GORM 1.25
ORM框架GORM 1.25
Model Definition:
Define User struct embedding gorm.Model. Add Name with uniqueIndex and not null tags, Email with uniqueIndex and not null, and Posts slice with foreignKey AuthorID tag.
Query Patterns:
Call db.Preload with Posts and function that orders by created_at desc and limits to 10, then First with user and id 1. For transactions, call db.Transaction with function taking tx pointer. Inside, create user and profile, returning any errors.
模型定义:
定义嵌入gorm.Model的User结构体。添加带有uniqueIndex和not null标签的Name字段、带有uniqueIndex和not null的Email字段,以及带有foreignKey AuthorID标签的Posts切片。
查询模式:
调用db.Preload(Posts)并传入按created_at降序排列且限制10条的函数,然后调用First查询id为1的user。对于事务,调用db.Transaction传入接收tx指针的函数。在事务函数内部创建user和profile,返回任何错误。
Type-Safe SQL with sqlc
类型安全SQL工具sqlc
Create sqlc.yaml with version 2, sql section with postgresql engine, queries and schema paths, and go generation settings for package name, output directory, and pgx v5 sql_package.
In query.sql file, add name GetUser as one returning all columns where id matches parameter. Add name CreateUser as one inserting name and email values and returning all columns.
创建sqlc.yaml文件,包含version 2、sql部分指定postgresql引擎、queries和schema路径,以及go生成设置(包名、输出目录、pgx v5 sql_package)。
在query.sql文件中,添加名为GetUser的查询,返回id匹配参数的所有列。添加名为CreateUser的查询,插入name和email值并返回所有列。
Concurrency Patterns
并发模式
Errgroup Pattern:
Create g and ctx with errgroup.WithContext. Call g.Go for fetchUsers that assigns to users variable. Call g.Go for fetchOrders that assigns to orders variable. If g.Wait returns error, return nil and error.
Worker Pool Pattern:
Define workerPool function taking jobs receive-only channel, results send-only channel, and n worker count. Create WaitGroup. Loop n times, incrementing WaitGroup and spawning goroutine that defers Done, ranges over jobs, and sends processJob result to results. Wait then close results.
Context with Timeout:
Create ctx and cancel with context.WithTimeout for 5 seconds. Defer cancel call. Call fetchData with ctx. If error is context.DeadlineExceeded, respond with timeout and StatusGatewayTimeout.
Errgroup模式:
通过errgroup.WithContext创建g和ctx。调用g.Go执行fetchUsers函数并将结果赋值给users变量。调用g.Go执行fetchOrders函数并将结果赋值给orders变量。如果g.Wait返回错误,返回nil和错误。
工作池模式:
定义workerPool函数,接收仅接收通道jobs、仅发送通道results和工作者数量n。创建WaitGroup。循环n次,递增WaitGroup计数并启动goroutine:defer Done,遍历jobs,将processJob的结果发送到results。等待所有工作者完成后关闭results。
带超时的Context:
通过context.WithTimeout创建ctx和cancel,超时时间为5秒。Defer调用cancel。调用fetchData传入ctx。如果错误为context.DeadlineExceeded,返回超时响应和StatusGatewayTimeout状态码。
Testing Patterns
测试模式
Table-Driven Tests:
Define tests slice with struct containing name string, input CreateUserInput, and wantErr bool. Add test cases for valid input and empty name. Range over tests calling t.Run with name and test function. Call service Create, check if wantErr is true and require.Error.
HTTP Testing:
Create app with fiber.New. Add GET route for users/:id calling getUser. Create request with httptest.NewRequest for GET at users/1. Call app.Test with request to get response. Assert 200 status code.
表驱动测试:
定义tests切片,包含name字符串、input CreateUserInput和wantErr bool的结构体。添加有效输入和空名称的测试用例。遍历tests,调用t.Run传入name和测试函数。调用service.Create,检查wantErr是否为true并使用require.Error断言。
HTTP测试:
通过fiber.New创建应用。添加GET /users/:id路由调用getUser。使用httptest.NewRequest创建指向/users/1的GET请求。调用app.Test传入请求获取响应。断言状态码为200。
CLI Cobra with Viper
CLI框架Cobra与Viper
Define rootCmd as cobra.Command pointer with Use and Short fields. In init function, add PersistentFlags StringVar for cfgFile. Call viper.BindPFlag with config and lookup. Set viper.SetEnvPrefix to MYAPP and call viper.AutomaticEnv.
定义rootCmd为cobra.Command指针,设置Use和Short字段。在init函数中,添加PersistentFlags StringVar用于cfgFile。调用viper.BindPFlag绑定config标志。设置viper.SetEnvPrefix为MYAPP并调用viper.AutomaticEnv。
Advanced Patterns
高级模式
Performance Optimization
性能优化
PGO Build:
Run application with GODEBUG pgo enabled and cpuprofile output. Build with go build using pgo flag pointing to profile file.
Object Pooling:
Create bufferPool as sync.Pool with New function returning 4096 byte slice. Get buffer with type assertion, defer Put to return to pool.
PGO构建:
在GODEBUG启用pgo并指定cpuprofile输出的情况下运行应用。使用go build并通过pgo标志指向性能分析文件进行构建。
对象池:
创建bufferPool为sync.Pool,其New函数返回4096字节的切片。通过类型断言获取buffer,defer Put将其放回池。
Container Deployment 10-20MB
容器部署(10-20MB)
Multi-stage Dockerfile: First stage uses golang:1.23-alpine as builder, sets WORKDIR, copies go.mod and go.sum, runs go mod download, copies source, builds with CGO_ENABLED 0 and ldflags for stripped binary. Second stage uses scratch, copies binary, sets ENTRYPOINT.
多阶段Dockerfile:第一阶段使用golang:1.23-alpine作为构建镜像,设置WORKDIR,复制go.mod和go.sum,运行go mod download,复制源码,使用CGO_ENABLED=0和ldflags编译剥离符号的二进制文件。第二阶段使用scratch镜像,复制二进制文件,设置ENTRYPOINT。
Graceful Shutdown
优雅关闭
Spawn goroutine calling app.Listen. Create quit channel for os.Signal with buffer 1. Call signal.Notify for SIGINT and SIGTERM. Receive from quit then call app.Shutdown.
启动goroutine调用app.Listen。创建容量为1的os.Signal类型quit通道。调用signal.Notify监听SIGINT和SIGTERM。接收quit通道信号后调用app.Shutdown。
Context7 Libraries
Context7库
- golang/go for Go language and stdlib
- gofiber/fiber for Fiber web framework
- gin-gonic/gin for Gin web framework
- labstack/echo for Echo web framework
- go-chi/chi for Chi router
- go-gorm/gorm for GORM ORM
- sqlc-dev/sqlc for type-safe SQL
- jackc/pgx for PostgreSQL driver
- spf13/cobra for CLI framework
- spf13/viper for configuration
- stretchr/testify for testing toolkit
- golang/go:Go语言及标准库
- gofiber/fiber:Fiber Web框架
- gin-gonic/gin:Gin Web框架
- labstack/echo:Echo Web框架
- go-chi/chi:Chi路由
- go-gorm/gorm:GORM ORM框架
- sqlc-dev/sqlc:类型安全SQL工具
- jackc/pgx:PostgreSQL驱动
- spf13/cobra:CLI框架
- spf13/viper:配置工具
- stretchr/testify:测试工具包
Works Well With
适配场景
- moai-domain-backend for REST API architecture and microservices
- moai-lang-rust for systems programming companion
- moai-quality-security for security hardening
- moai-essentials-debug for performance profiling
- moai-workflow-ddd for domain-driven development
- moai-domain-backend:REST API架构与微服务
- moai-lang-rust:系统编程配套工具
- moai-quality-security:安全加固
- moai-essentials-debug:性能分析
- moai-workflow-ddd:领域驱动开发
Troubleshooting
故障排查
Common Issues:
- Module errors: Run go mod tidy and go mod verify
- Version check: Run go version and go env GOVERSION
- Build issues: Run go clean -cache and go build -v
Performance Diagnostics:
- CPU profiling: Run go test -cpuprofile cpu.prof -bench .
- Memory profiling: Run go test -memprofile mem.prof -bench .
- Race detection: Run go test -race ./...
常见问题:
- 模块错误:运行go mod tidy和go mod verify
- 版本检查:运行go version和go env GOVERSION
- 构建问题:运行go clean -cache和go build -v
性能诊断:
- CPU分析:运行go test -cpuprofile cpu.prof -bench .
- 内存分析:运行go test -memprofile mem.prof -bench .
- 竞态检测:运行go test -race ./...
Additional Resources
额外资源
See reference.md for complete framework reference, advanced patterns, and Context7 library mappings.
See examples.md for production-ready code including REST APIs, CLI tools, and deployment configurations.
Last Updated: 2026-01-11
Version: 1.1.0
查看reference.md获取完整框架参考、高级模式及Context7库映射。
查看examples.md获取生产就绪代码,包括REST API、CLI工具和部署配置。
最后更新:2026-01-11
版本:1.1.0