Install
$ agentstack add skill-xu-xiang-everything-claude-code-zh-golang-patterns ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ● Network access Used
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ● Environment & secrets Used
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
Go 开发模式(Go Development Patterns)
用于构建健壮、高效且可维护应用程序的惯用法与最佳实践。
何时启用
- 编写新的 Go 代码时
- 评审 Go 代码时
- 重构现有 Go 代码时
- 设计 Go 软件包(Package)/ 模块(Module)时
核心原则
1. 简单与清晰
Go 倾向于简单而非巧妙。代码应当直观且易读。
// Good: 清晰且直接
func GetUser(id string) (*User, error) {
user, err := db.FindUser(id)
if err != nil {
return nil, fmt.Errorf("get user %s: %w", id, err)
}
return user, nil
}
// Bad: 过于巧妙
func GetUser(id string) (*User, error) {
return func() (*User, error) {
if u, e := db.FindUser(id); e == nil {
return u, nil
} else {
return nil, e
}
}()
}
2. 让零值(Zero Value)变得有用
在设计类型时,应确保其零值无需显式初始化即可直接使用。
// Good: 零值很有用
type Counter struct {
mu sync.Mutex
count int // 零值为 0,可直接使用
}
func (c *Counter) Inc() {
c.mu.Lock()
c.count++
c.mu.Unlock()
}
// Good: bytes.Buffer 可以直接使用零值
var buf bytes.Buffer
buf.WriteString("hello")
// Bad: 需要初始化
type BadCounter struct {
counts map[string]int // nil map 会引发 panic
}
3. 接受接口(Interface),返回结构体(Struct)
函数应当接收接口参数并返回具体类型。
// Good: 接收接口,返回具体类型
func ProcessData(r io.Reader) (*Result, error) {
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}
return &Result{Data: data}, nil
}
// Bad: 返回接口(无谓地隐藏了实现细节)
func ProcessData(r io.Reader) (io.Reader, error) {
// ...
}
错误处理模式(Error Handling Patterns)
带有上下文的错误包装(Error Wrapping)
// Good: 使用上下文包装错误
func LoadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("load config %s: %w", path, err)
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config %s: %w", path, err)
}
return &cfg, nil
}
自定义错误类型
// 定义领域特定错误
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation failed on %s: %s", e.Field, e.Message)
}
// 常见情况的哨兵错误(Sentinel errors)
var (
ErrNotFound = errors.New("resource not found")
ErrUnauthorized = errors.New("unauthorized")
ErrInvalidInput = errors.New("invalid input")
)
使用 errors.Is 与 errors.As 进行错误检查
func HandleError(err error) {
// 检查特定错误
if errors.Is(err, sql.ErrNoRows) {
log.Println("No records found")
return
}
// 检查错误类型
var validationErr *ValidationError
if errors.As(err, &validationErr) {
log.Printf("Validation error on field %s: %s",
validationErr.Field, validationErr.Message)
return
}
// 未知错误
log.Printf("Unexpected error: %v", err)
}
永不忽略错误
// Bad: 使用空白标识符忽略错误
result, _ := doSomething()
// Good: 处理错误或显式记录为何可以安全忽略
result, err := doSomething()
if err != nil {
return err
}
// Acceptable: 当错误确实无关紧要时(罕见)
_ = writer.Close() // 尽力清理,错误已在别处记录
并发处理模式(Concurrency Patterns)
工作池(Worker Pool)
func WorkerPool(jobs 0 {
sb.WriteString(",")
}
sb.WriteString(p)
}
return sb.String()
}
// Best: 使用标准库
func join(parts []string) string {
return strings.Join(parts, ",")
}
Go 工具链集成
基本命令
# 构建并运行
go build ./...
go run ./cmd/myapp
# 测试
go test ./...
go test -race ./...
go test -cover ./...
# 静态分析
go vet ./...
staticcheck ./...
golangci-lint run
# 模块管理
go mod tidy
go mod verify
# 格式化
gofmt -w .
goimports -w .
推荐的 Linter 配置(.golangci.yml)
linters:
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- gofmt
- goimports
- misspell
- unconvert
- unparam
linters-settings:
errcheck:
check-type-assertions: true
govet:
check-shadowing: true
issues:
exclude-use-default: false
快速参考:Go 惯用法
| 惯用法 | 说明 | |-------|-------------| | 接受接口,返回结构体 | 函数应当接收接口参数并返回具体类型 | | 错误即值 | 将错误视为一等公民(First-class Value),而非异常 | | 不要通过共享内存来通信 | 使用通道(Channel)进行协程间的协调 | | 让零值变得有用 | 类型应在无显式初始化的情况下即可正常工作 | | 少量的拷贝好过少量的依赖 | 避免不必要的外部依赖 | | 清晰好过巧妙 | 可读性优先于奇技淫巧 | | gofmt 虽然不是任何人的最爱,但它是每个人的朋友 | 始终使用 gofmt/goimports 进行格式化 | | 尽早返回 | 优先处理错误,使快乐路径(Happy Path)保持较浅的缩进 |
应避免的反模式(Anti-patterns)
// Bad: 长函数中的裸返回(Naked returns)
func process() (result int, err error) {
// ... 50 行代码 ...
return // 返回了什么?
}
// Bad: 使用 panic 进行控制流管理
func GetUser(id string) *User {
user, err := db.Find(id)
if err != nil {
panic(err) // 不要这样做
}
return user
}
// Bad: 在结构体中传递 context
type Request struct {
ctx context.Context // context 应该是第一个参数
ID string
}
// Good: context 作为第一个参数
func ProcessRequest(ctx context.Context, id string) error {
// ...
}
// Bad: 混合使用值接收者和指针接收者
type Counter struct{ n int }
func (c Counter) Value() int { return c.n } // 值接收者
func (c *Counter) Increment() { c.n++ } // 指针接收者
// 请选择一种风格并保持一致
请记住:Go 代码在最好的意义上应当是“枯燥”的 —— 可预测、一致且易于理解。如有疑疑虑,请保持简单。
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: xu-xiang
- Source: xu-xiang/everything-claude-code-zh
- License: MIT
- Homepage: https://oneskill.one
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.