golang by saisudhir14/golang-agent-skill
npx skills add https://github.com/saisudhir14/golang-agent-skill --skill golang来自 Google、Uber 和 Go 团队的生产模式。已更新至 Go 1.25。
子技能:
skills/go-error-handling、skills/go-concurrency、skills/go-testing、skills/go-performance、skills/go-code-review、skills/go-linting、skills/go-project-layout、skills/go-security。深度参考在references/中。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
可读代码按以下顺序优先考虑这些属性:
完整指南:
skills/go-error-handling/SKILL.md| 参考:references/error-handling.md
返回错误,切勿 panic 在生产代码中
使用 %w 包装 当调用者需要 errors.Is/errors.As 时;在边界处使用 %v
保持上下文简洁:使用 "new store: %w" 而不是 "failed to create new store: %w"
错误只处理一次:不要记录并返回同一个错误
错误字符串:小写,无标点符号
缩进错误流程:首先处理错误,保持正常路径缩进最小
使用 errors.Join (Go 1.20+) 处理多个独立的失败
哨兵错误:变量使用 Err 前缀,类型使用 Error 后缀
if err != nil { return fmt.Errorf("load config: %w", err) }
完整指南:
skills/go-concurrency/SKILL.md| 参考:references/concurrency.md
通道大小:0(无缓冲)或 1;其他任何大小都需要理由
记录 goroutine 生命周期:何时以及如何退出
使用 errgroup.Group 代替手动的 sync.WaitGroup 来处理返回错误的 goroutine
优先使用同步函数:让调用者添加并发
零值互斥锁:不要使用指针;不要嵌入到公共结构体中
类型化原子操作 (Go 1.19+):atomic.Int64、atomic.Bool、atomic.Pointer[T]
sync.Map (Go 1.24+):对于不相交的键集,性能显著提升
g, ctx := errgroup.WithContext(ctx) g.SetLimit(10) for _, item := range items { g.Go(func() error { return process(ctx, item) }) } return g.Wait()
MaxLength 而不是 MAX_LENGTH)URL、ID、HTTP 而不是 Url、Id、Http)i,全局变量用 DefaultTimeout)this/selfutil/common/mischttp.Serve 而不是 http.HTTPServe;用 c.WriteTo 而不是 c.WriteConfigTo| 指针接收器 | 值接收器 |
|---|---|
| 修改接收器 | 小型、不可变的结构体 |
| 大型结构体 | 不修改状态 |
| 包含 sync.Mutex | Map、func 或 chan |
| 与其他方法保持一致 | 基本类型 |
import (
"context"
"fmt"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
"yourcompany/internal/config"
)
import _ "pkg") 仅用于 main 或测试文件使用工具指令在 go.mod 中跟踪工具依赖:
tool (
golang.org/x/tools/cmd/stringer
github.com/golangci/golangci-lint/cmd/golangci-lint
)
go get -tool golang.org/x/tools/cmd/stringer # 添加
go tool stringer -type=Status # 运行
go get tool # 更新所有
go install tool # 安装到 GOBIN
var 声明零值结构体:var user Uservar t []string(仅当需要 JSON [] 编码时才使用 []string{})copy() 或 maps.Clone() 以防止被修改make([]T, 0, len(input))slices 和 maps 包:slices.Sort、slices.Clone、maps.Clone、maps.Equal当为不同类型编写相同代码时使用
使用 cmp.Ordered 或自定义约束以确保类型安全
泛型类型别名 (Go 1.24+):type Set[T comparable] = map[T]struct{}
不要过度泛化:当具体类型或接口足够时,使用它们
func Filter[T any](s []T, pred func(T) bool) []T { result := make([]T, 0, len(s)) for _, v := range s { if pred(v) { result = append(result, v) } } return result }
使用函数进行范围迭代以实现自定义迭代器:
func Backward[T any](s []T) func(yield func(int, T) bool) {
return func(yield func(int, T) bool) {
for i := len(s) - 1; i >= 0; i-- {
if !yield(i, s[i]) {
return
}
}
}
}
for i, v := range Backward(items) {
fmt.Println(i, v)
}
字符串/字节迭代器 (Go 1.24+):strings.Lines、strings.SplitSeq、strings.SplitAfterSeq
slog.Info("user created", "id", userID, "email", email)
slog.With("service", "auth").Info("starting")
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
slog.DiscardHandler (Go 1.24+) 用于在测试中抑制日志slog.Group 分组相关字段完整指南:
skills/go-performance/SKILL.md| 参考:references/performance.md
strconv 而不是 fmt:用 strconv.Itoa(n) 而不是 fmt.Sprintf("%d", n)[]byte 转换:存储一次,重复使用make(map[string]int, len(items))strings.Builder 配合 Grow() 进行字符串拼接完整指南:
skills/go-testing/SKILL.md| 参考:references/testing.md
t.Parallel() 用于子测试go-cmp 而不是 reflect.DeepEqual 以获得清晰的差异输出t.Fatal 处理设置失败T.Context 和 T.Chdir (Go 1.24+)b.Loop() (Go 1.24+):更清晰的基准测试,无需 b.ResetTimer()synctest.Test (Go 1.25+):使用合成时间进行确定性并发测试runtime.AddCleanup:每个对象多个清理函数,无循环泄漏(替代 SetFinalizer)weak.Pointer[T]:用于缓存、规范化、观察者的弱引用os.Root:作用域文件访问,防止路径遍历攻击完整参考:
references/patterns.md
WithTimeout(d)、WithLogger(l) 用于可配置的构造函数var _ http.Handler = (*Handler)(nil)srv.Shutdown(ctx)time.Duration:永远不要使用原始整数表示时间t, ok := i.(string) 以避免 panicfunc Process(ctx context.Context, ...)init():优先在 main 中进行显式初始化//go:embed (Go 1.16+):嵌入静态文件json:"name"完整参考:
references/gotchas.md
| 陷阱 | 修复方法 |
|---|---|
| 循环变量捕获 (Go 1.22 之前) | 已在 Go 1.22+ 中修复(每次迭代变量) |
| Defer 立即评估参数 | 在闭包中捕获 |
| Nil 接口 vs nil 指针 | 显式返回 nil |
| 在错误检查前使用结果 | 始终先检查 err (Go 1.25 强制执行) |
| 映射迭代顺序 | 使用 slices.Sorted(maps.Keys(m)) 对键排序 |
| 切片追加共享底层数组 | 完整切片表达式 a[:2:2] |
完整指南:
skills/go-linting/SKILL.md
go get -tool github.com/golangci/golangci-lint/cmd/golangci-lintgolangci/golangci-lint-action//nolint 注释完整指南:
skills/go-project-layout/SKILL.md
cmd/:每个可执行文件一个子目录,保持 main.go 精简internal/:私有包,由 Go 工具链强制执行pkg/、src/、models/、utils/:按用途命名包CGO_ENABLED=0,使用无发行版基础镜像完整指南:
skills/go-security/SKILL.md
os.Root (Go 1.24+):作用域文件访问,防止路径遍历String() 方法的 Secret 类型crypto/rand 用于随机字节,bcrypt 用于密码ReadTimeout、WriteTimeout、IdleTimeoutgovulncheck:扫描依赖项中的已知漏洞go test -race:在 CI 中始终使用竞态检测器运行encoding/json/v2:通过 GOEXPERIMENT=jsonv2 启用。更好的性能、流式处理、每次调用自定义序列化器。package 声明之前,无空行每周安装次数
333
代码仓库
GitHub 星标数
6
首次出现
2026年1月21日
安全审计
安装于
gemini-cli280
opencode278
codex277
cursor265
github-copilot261
amp222
Production patterns from Google, Uber, and the Go team. Updated for Go 1.25.
Sub-skills:
skills/go-error-handling,skills/go-concurrency,skills/go-testing,skills/go-performance,skills/go-code-review,skills/go-linting,skills/go-project-layout,skills/go-security. Deep-dive references inreferences/.
Readable code prioritizes these attributes in order:
Full guide:
skills/go-error-handling/SKILL.md| Reference:references/error-handling.md
Return errors, never panic in production code
Wrap with%w when callers need errors.Is/errors.As; use %v at boundaries
Keep context succinct : "new store: %w" not "failed to create new store: %w"
Handle errors once : don't log and return the same error
Error strings : lowercase, no punctuation
Indent error flow : handle errors first, keep happy path at minimal indentation
Useerrors.Join (Go 1.20+) for multiple independent failures
Full guide:
skills/go-concurrency/SKILL.md| Reference:references/concurrency.md
Channel size : 0 (unbuffered) or 1; anything else needs justification
Document goroutine lifetimes : when and how they exit
Useerrgroup.Group over manual sync.WaitGroup for error-returning goroutines
Prefer synchronous functions : let callers add concurrency
Zero value mutexes : don't use pointers; don't embed in public structs
Typed atomics (Go 1.19+): atomic.Int64, atomic.Bool, atomic.Pointer[T]
sync.Map (Go 1.24+): significantly improved performance for disjoint key sets
MaxLength not MAX_LENGTH)URL, ID, HTTP not Url, Id, Http)i for loops, DefaultTimeout for globals)| Pointer receiver | Value receiver |
|---|---|
| Modifies receiver | Small, immutable struct |
| Large struct | Doesn't modify state |
| Contains sync.Mutex | Map, func, or chan |
| Consistency with other methods | Basic types |
import (
"context"
"fmt"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
"yourcompany/internal/config"
)
import _ "pkg") only in main or testsTrack tool dependencies in go.mod with tool directives:
tool (
golang.org/x/tools/cmd/stringer
github.com/golangci/golangci-lint/cmd/golangci-lint
)
go get -tool golang.org/x/tools/cmd/stringer # add
go tool stringer -type=Status # run
go get tool # update all
go install tool # install to GOBIN
var for zero value structs: var user Uservar t []string (use []string{} only for JSON [] encoding)copy() or maps.Clone() to prevent mutationmake([]T, 0, len(input)) when size is knownslices and maps packages: slices.Sort, slices.Clone, , Use when writing identical code for different types
Use cmp.Ordered or custom constraints for type safety
Generic type aliases (Go 1.24+): type Set[T comparable] = map[T]struct{}
Don't over-generalize : use concrete types or interfaces when they suffice
func Filter[T any](s []T, pred func(T) bool) []T { result := make([]T, 0, len(s)) for _, v := range s { if pred(v) { result = append(result, v) } } return result }
Range over functions for custom iterators:
func Backward[T any](s []T) func(yield func(int, T) bool) {
return func(yield func(int, T) bool) {
for i := len(s) - 1; i >= 0; i-- {
if !yield(i, s[i]) {
return
}
}
}
}
for i, v := range Backward(items) {
fmt.Println(i, v)
}
String/bytes iterators (Go 1.24+): strings.Lines, strings.SplitSeq, strings.SplitAfterSeq
slog.Info("user created", "id", userID, "email", email)
slog.With("service", "auth").Info("starting")
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
slog.DiscardHandler (Go 1.24+) for suppressing logs in testsslog.GroupFull guide:
skills/go-performance/SKILL.md| Reference:references/performance.md
strconv over fmt: strconv.Itoa(n) not fmt.Sprintf("%d", n)[]byte conversions: store once, reusemake(map[string]int, len(items))strings.Builder with Grow() for concatenationFull guide:
skills/go-testing/SKILL.md| Reference:references/testing.md
t.Parallel() for subtestsgo-cmp over reflect.DeepEqual for clear diff outputt.Fatal for setup failuresT.Context and T.Chdir (Go 1.24+)b.Loop() (Go 1.24+): cleaner benchmarks, no b.ResetTimer() neededruntime.AddCleanup : multiple cleanups per object, no cycle leaks (replaces SetFinalizer)weak.Pointer[T] : weak references for caches, canonicalization, observersos.Root : scoped file access preventing path traversal attacksFull reference:
references/patterns.md
WithTimeout(d), WithLogger(l) for configurable constructorsvar _ http.Handler = (*Handler)(nil)srv.Shutdown(ctx)time.Duration: never raw ints for timet, ok := i.(string) to avoid panicsfunc Process(ctx context.Context, ...)Full reference:
references/gotchas.md
| Gotcha | Fix |
|---|---|
| Loop variable capture (pre-1.22) | Fixed in Go 1.22+ (per-iteration vars) |
| Defer evaluates args immediately | Capture in closure |
| Nil interface vs nil pointer | Return nil explicitly |
| Use result before error check | Always check err first (Go 1.25 enforces) |
| Map iteration order | Sort keys with slices.Sorted(maps.Keys(m)) |
| Slice append shared backing | Full slice expression a[:2:2] |
Full guide:
skills/go-linting/SKILL.md
go get -tool github.com/golangci/golangci-lint/cmd/golangci-lintgolangci/golangci-lint-action for GitHub Actions//nolint commentsFull guide:
skills/go-project-layout/SKILL.md
cmd/ : one subdirectory per executable, keep main.go thininternal/ : private packages, enforced by the Go toolchainpkg/, src/, models/, utils/: name packages by purposeCGO_ENABLED=0, distroless base imageFull guide:
skills/go-security/SKILL.md
os.Root (Go 1.24+): scoped file access preventing path traversalSecret type with redacted String()crypto/rand for random bytes, bcrypt for passwordsReadTimeout, WriteTimeout, IdleTimeoutencoding/json/v2 : enable with GOEXPERIMENT=jsonv2. Better performance, streaming, custom marshalers per call.package declaration, no blank lineWeekly Installs
333
Repository
GitHub Stars
6
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
gemini-cli280
opencode278
codex277
cursor265
github-copilot261
amp222
GSAP React 动画库使用指南:useGSAP Hook 与最佳实践
1,400 周安装
Sentinel errors : Err prefix for vars, Error suffix for types
if err != nil { return fmt.Errorf("load config: %w", err) }
g, ctx := errgroup.WithContext(ctx) g.SetLimit(10) for _, item := range items { g.Go(func() error { return process(ctx, item) }) } return g.Wait()
thisselfutil/common/mischttp.Serve not http.HTTPServe; c.WriteTo not c.WriteConfigTomaps.Clonemaps.Equalsynctest.Test (Go 1.25+): deterministic concurrent testing with synthetic timeinit(): prefer explicit initialization in main//go:embed (Go 1.16+): embed static filesjson:"name" on marshaled structsgovulncheckgo test -race : always run with the race detector in CI