moai-lang-go by modu-ai/moai-adk
npx skills add https://github.com/modu-ai/moai-adk --skill moai-lang-goGo 1.23+ 开发专家,专注于高性能后端系统和 CLI 应用程序。
自动触发:包含 .go 扩展名的文件、go.mod、go.sum、goroutines、channels、Fiber、Gin、GORM、Echo、Chi
核心用例:
快速模式:
Fiber API 模式:
通过调用 fiber.New 函数创建应用。在 api/users/:id 定义一个 get 路由,其处理函数接收 fiber.Ctx 并返回错误。在处理函数中,调用 c.JSON 并传入包含从 c.Params 获取的 id 的 fiber.Map。在端口 3000 上调用 app.Listen。
Gin API 模式:
通过调用 函数创建 。在 定义一个 GET 路由,其处理函数接收 。在处理函数中,调用 ,状态码为 200,并传入包含从 获取的 id 的 。在端口 3000 上调用 。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
gin.Defaultrapi/users/:id*gin.Contextc.JSONc.Paramgin.Hr.Run带错误处理的 Goroutine:
使用 context.Background 调用 errgroup.WithContext 来创建 g 和 ctx。调用 g.Go 并传入返回 processUsers(ctx) 的函数。调用 g.Go 并传入返回 processOrders(ctx) 的函数。如果 g.Wait 返回的 err 不为 nil,则调用 log.Fatal 并传入该错误。
新特性:
for i range 10 语法遍历整数并打印 i泛型模式:
创建泛型函数 Map,类型参数 T 和 U 为 any。接收 T 类型的切片和从 T 到 U 的函数。创建相同长度的 U 类型结果切片。遍历切片范围,将结果元素设置为函数应用于值后的结果。返回结果。
使用 fiber.New 创建应用,传入包含 ErrorHandler 和 Prefork 为 true 的 fiber.Config。使用 recover.New、logger.New 和 cors.New 中间件。在路径 api/v1 创建 api 分组。为 listUsers、带 id 参数的 getUser、createUser、带 id 的 updateUser 和带 id 的 deleteUser 定义路由。在端口 3000 上调用 app.Listen。
使用 gin.Default 创建 r。使用 cors.Default 中间件。在路径 api/v1 创建 api 分组。为调用 listUsers 的 users 定义 GET,为调用 getUser 的 users/:id 定义 GET,为调用 createUser 的 users 定义 POST。在端口 3000 上调用 r.Run。
请求绑定模式:
定义 CreateUserRequest 结构体,包含 Name 和 Email 字段。添加 json 标签和 binding 标签,用于必填、最小长度 2 和必填的电子邮件验证。在 createUser 处理函数中,声明 req 变量,调用 c.ShouldBindJSON 并传入指针。如果有错误,调用 c.JSON,状态码为 400 并传入错误。否则调用 c.JSON,状态码为 201 并传入响应数据。
使用 echo.New 创建 e。使用 middleware.Logger、middleware.Recover 和 middleware.CORS。在路径 api/v1 创建 api 分组。为 users 定义 GET 和 POST。在端口 3000 上调用 e.Logger.Fatal 并传入 e.Start。
使用 chi.NewRouter 创建 r。使用 middleware.Logger 和 middleware.Recoverer。调用 r.Route,路径为 api/v1 并传入函数。在函数内部,调用路径为 users 的 r.Route。为列表定义 Get,为创建定义 Post,为单个用户定义带 id 参数的 Get。在端口 3000 上调用 http.ListenAndServe 并传入 r。
模型定义:
定义 User 结构体,嵌入 gorm.Model。添加带有 uniqueIndex 和 not null 标签的 Name,带有 uniqueIndex 和 not null 的 Email,以及带有 foreignKey AuthorID 标签的 Posts 切片。
查询模式:
调用 db.Preload,传入 Posts 和一个按 created_at 降序排序并限制为 10 条的函数,然后 First 传入 user 和 id 为 1。对于事务,调用 db.Transaction 并传入一个接收 *tx 指针的函数。在函数内部,创建 user 和 profile,返回任何错误。
创建 sqlc.yaml,包含版本 2,sql 部分包含 postgresql 引擎、queries 和 schema 路径,以及 go 生成设置,包括包名、输出目录和 pgx v5 sql_package。
在 query.sql 文件中,添加名为 GetUser 的查询,返回所有列,其中 id 匹配参数。添加名为 CreateUser 的查询,插入 name 和 email 值并返回所有列。
Errgroup 模式:
使用 errgroup.WithContext 创建 g 和 ctx。为 fetchUsers 调用 g.Go,赋值给 users 变量。为 fetchOrders 调用 g.Go,赋值给 orders 变量。如果 g.Wait 返回错误,则返回 nil 和错误。
工作池模式:
定义 workerPool 函数,接收 jobs 只读通道、results 只写通道和 n 个工作线程数。创建 WaitGroup。循环 n 次,递增 WaitGroup 并启动 goroutine,该 goroutine 延迟调用 Done,遍历 jobs,并将 processJob 的结果发送到 results。等待然后关闭 results。
带超时的 Context:
使用 context.WithTimeout 创建 ctx 和 cancel,超时时间为 5 秒。延迟调用 cancel。调用 fetchData 并传入 ctx。如果错误是 context.DeadlineExceeded,则响应超时和 StatusGatewayTimeout。
表驱动测试:
定义 tests 切片,包含结构体,该结构体有 name 字符串、input CreateUserInput 和 wantErr 布尔值。添加有效输入和空名称的测试用例。遍历 tests,调用 t.Run 并传入 name 和测试函数。调用 service.Create,检查 wantErr 是否为 true 并 require.Error。
HTTP 测试:
使用 fiber.New 创建应用。为调用 getUser 的 users/:id 添加 GET 路由。使用 httptest.NewRequest 为 users/1 的 GET 创建请求。调用 app.Test 并传入请求以获取响应。断言状态码为 200。
将 rootCmd 定义为 *cobra.Command,包含 Use 和 Short 字段。在 init 函数中,为 cfgFile 添加 PersistentFlags StringVar。调用 viper.BindPFlag,传入 config 和 lookup。将 viper.SetEnvPrefix 设置为 MYAPP 并调用 viper.AutomaticEnv。
如需全面覆盖,包括:
请参阅:reference/advanced.md 获取高级模式,reference/testing.md 获取测试模式
PGO 构建:
启用 GODEBUG pgo 并输出 cpuprofile 来运行应用程序。使用 go build 构建,并指定指向配置文件的 pgo 标志。
对象池:
创建 bufferPool 作为 sync.Pool,其 New 函数返回 4096 字节的切片。通过类型断言获取 buffer,延迟调用 Put 将其返回到池中。
多阶段 Dockerfile:第一阶段使用 golang:1.23-alpine 作为构建器,设置 WORKDIR,复制 go.mod 和 go.sum,运行 go mod download,复制源代码,使用 CGO_ENABLED 0 和用于剥离二进制文件的 ldflags 进行构建。第二阶段使用 scratch,复制二进制文件,设置 ENTRYPOINT。
启动 goroutine 调用 app.Listen。为 os.Signal 创建带缓冲区 1 的 quit 通道。为 SIGINT 和 SIGTERM 调用 signal.Notify。从 quit 接收信号,然后调用 app.Shutdown。
golang/go 用于 Go 语言和标准库gofiber/fiber 用于 Fiber web 框架gin-gonic/gin 用于 Gin web 框架labstack/echo 用于 Echo web 框架go-chi/chi 用于 Chi 路由器go-gorm/gorm 用于 GORM ORMsqlc-dev/sqlc 用于类型安全的 SQLjackc/pgx 用于 PostgreSQL 驱动spf13/cobra 用于 CLI 框架spf13/viper 用于配置管理stretchr/testify 用于测试工具包moai-domain-backend 用于 REST API 架构和微服务moai-lang-rust 用于系统编程伴侣moai-quality-security 用于安全加固moai-essentials-debug 用于性能分析moai-workflow-ddd 用于领域驱动开发常见问题:
go mod tidy 和 go mod verifygo version 和 go env GOVERSIONgo clean -cache 和 go build -v性能诊断:
go test -cpuprofile cpu.prof -bench .go test -memprofile mem.prof -bench .go test -race ./...请参阅 reference/advanced.md 获取高级并发模式、泛型和接口设计。
请参阅 reference/testing.md 获取全面的测试模式,包括 TDD、基准测试和模糊测试。
最后更新:2026-01-11 版本:1.1.0
每周安装次数
73
仓库
GitHub 星标数
888
首次出现
2026年1月19日
安全审计
安装于
opencode64
codex63
gemini-cli62
claude-code60
github-copilot58
cursor58
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:
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.
New Features:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
For comprehensive coverage including:
See: reference/advanced.md for advanced patterns, reference/testing.md for testing patterns
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.
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.
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.
Common Issues:
Performance Diagnostics:
See reference/advanced.md for advanced concurrency patterns, generics, and interface design.
See reference/testing.md for comprehensive testing patterns including TDD, benchmarks, and fuzzing.
Last Updated: 2026-01-11 Version: 1.1.0
Weekly Installs
73
Repository
GitHub Stars
888
First Seen
Jan 19, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykPass
Installed on
opencode64
codex63
gemini-cli62
claude-code60
github-copilot58
cursor58
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
122,000 周安装