golang-pro by 404kidwiz/claude-supercode-skills
npx skills add https://github.com/404kidwiz/claude-supercode-skills --skill golang-pro提供专业的 Go 编程能力,专注于 Go 1.21+ 特性、使用 goroutine 和 channel 的并发系统以及高性能后端服务。擅长使用地道的 Go 模式和全面的标准库来构建可扩展的微服务、CLI 工具和分布式系统。
专业的 Go 开发专家,专注于 Go 1.21+ 特性、使用 goroutine 和 channel 的并发编程,以及全面的标准库使用,以构建高性能、并发系统。
Use Case Analysis
│
├─ Need to process multiple items independently?
│ └─ Worker Pool Pattern ✓
│ - Buffered channel for jobs
│ - Fixed number of goroutines
│ - WaitGroup for completion
│
├─ Need to transform data through multiple stages?
│ └─ Pipeline Pattern ✓
│ - Chain of channels
│ - Each stage processes and passes forward
│ - Fan-out for parallel processing
│
├─ Need to merge results from multiple sources?
│ └─ Fan-In Pattern ✓
│ - Multiple input channels
│ - Single output channel
│ - select statement for multiplexing
│
├─ Need request-scoped cancellation?
│ └─ Context Pattern ✓
│ - context.WithCancel()
│ - context.WithTimeout()
│ - Propagate through call chain
│
├─ Need to synchronize access to shared state?
│ ├─ Read-heavy workload → sync.RWMutex
│ ├─ Simple counter → sync/atomic
│ └─ Complex coordination → Channels
│
└─ Need to ensure single initialization?
└─ sync.Once ✓
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 场景 | 模式 | 示例 |
|---|---|---|
| 用上下文包装错误 | fmt.Errorf("%w") | return fmt.Errorf("failed to connect: %w", err) |
| 自定义错误类型 | 定义带有 Error() 的结构体 | type ValidationError struct { Field string } |
| 哨兵错误 | var ErrNotFound = errors.New("not found") | if errors.Is(err, ErrNotFound) { ... } |
| 检查错误类型 | errors.As() | var valErr *ValidationError; if errors.As(err, &valErr) { ... } |
| 返回多个错误 | 同时返回值和错误 | func Get(id string) (*User, error) |
| 仅在程序员错误时 panic | panic("unreachable code") | 永远不要为预期的失败 panic |
HTTP Server Requirements
│
├─ Need full-featured framework with middleware?
│ └─ Gin or Echo ✓
│ - Routing, middleware, validation
│ - JSON binding
│ - Production-ready
│
├─ Need microframework for simple APIs?
│ └─ Chi or Gorilla Mux ✓
│ - Lightweight routing
│ - stdlib-compatible
│ - Fine-grained control
│
├─ Need maximum performance and control?
│ └─ net/http stdlib ✓
│ - No external dependencies
│ - Full customization
│ - Good for learning
│
└─ Need gRPC services?
└─ google.golang.org/grpc ✓
- Protocol Buffers
- Streaming support
- Cross-language
| 观察现象 | 为何上报 | 示例 |
|---|---|---|
| Goroutine 泄漏导致内存增长 | 复杂的生命周期管理 | "内存无限增长,怀疑 goroutine 未终止" |
| 尽管使用了互斥锁仍存在竞态条件 | 微妙的同步错误 | "go test -race 显示生产代码中存在数据竞争" |
| 上下文取消未传播 | 分布式系统协调 | "客户端断开连接后,已取消的请求仍在运行" |
| 泛型导致编译时爆炸 | 类型系统复杂性 | "带有约束的泛型函数导致编译时间超过 10 分钟" |
| CGO 内存损坏 | 不安全代码交互 | "从 Go 调用 C 库时出现段错误" |
场景:具有中间件和优雅关闭功能的生产就绪 HTTP 服务器
步骤 1:定义服务器结构
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type Server struct {
httpServer *http.Server
logger *log.Logger
}
func NewServer(addr string, handler http.Handler) *Server {
return &Server{
httpServer: &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
},
logger: log.New(os.Stdout, "[SERVER] ", log.LstdFlags|log.Lmicroseconds),
}
}
func (s *Server) Start() error {
s.logger.Printf("Starting server on %s", s.httpServer.Addr)
if err := s.httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func (s *Server) Shutdown(ctx context.Context) error {
s.logger.Println("Shutting down server...")
return s.httpServer.Shutdown(ctx)
}
步骤 2:实现中间件
// Middleware for logging
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Wrap response writer to capture status code
wrapped := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(wrapped, r)
log.Printf("%s %s %d %s", r.Method, r.URL.Path, wrapped.statusCode, time.Since(start))
})
}
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// Middleware for panic recovery
func RecoveryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("Panic recovered: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
// Middleware for request timeout
func TimeoutMiddleware(timeout time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
r = r.WithContext(ctx)
done := make(chan struct{})
go func() {
next.ServeHTTP(w, r)
close(done)
}()
select {
case <-done:
return
case <-ctx.Done():
http.Error(w, "Request Timeout", http.StatusRequestTimeout)
}
})
}
}
步骤 3:设置路由和优雅关闭
func main() {
// Setup routes
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
// Simulate slow endpoint
time.Sleep(2 * time.Second)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"users": []}`))
})
// Apply middleware chain
handler := RecoveryMiddleware(LoggingMiddleware(TimeoutMiddleware(5 * time.Second)(mux)))
// Create server
server := NewServer(":8080", handler)
// Start server in goroutine
go func() {
if err := server.Start(); err != nil {
log.Fatalf("Server failed: %v", err)
}
}()
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
// Graceful shutdown with 30s timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Printf("Server shutdown error: %v", err)
}
log.Println("Server stopped")
}
预期成果:
用例:当客户端断开连接时取消所有下游操作
// Template: Context-aware HTTP handler
func HandleRequest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Pass context to all downstream calls
result, err := fetchData(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
// Client disconnected
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(result)
}
func fetchData(ctx context.Context) (*Data, error) {
// Check context before expensive operation
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
// Simulate database call with timeout
resultChan := make(chan *Data, 1)
errChan := make(chan error, 1)
go func() {
// Actual database query
time.Sleep(2 * time.Second)
resultChan <- &Data{Value: "result"}
}()
select {
case result := <-resultChan:
return result, nil
case err := <-errChan:
return nil, err
case <-ctx.Done():
return nil, ctx.Err() // Canceled or timed out
}
}
用例:以最少的代码实现全面的测试覆盖
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -2, -3, -5},
{"mixed signs", -2, 3, 1},
{"zero values", 0, 0, 0},
{"large numbers", 1000000, 2000000, 3000000},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)
}
})
}
}
错误示例:
// WRONG: All goroutines reference same variable
for _, user := range users {
go func() {
fmt.Println(user.Name) // Captures loop variable by reference!
}()
}
// Prints last user's name multiple times!
失败原因:
正确方法:
// CORRECT: Pass variable as argument (Go 1.21 and earlier)
for _, user := range users {
go func(u User) {
fmt.Println(u.Name) // Each goroutine has own copy
}(user)
}
// CORRECT: Use local variable (Go 1.21 and earlier)
for _, user := range users {
user := user // Shadow variable
go func() {
fmt.Println(user.Name)
}()
}
// Go 1.22+: Loop variable per iteration (automatic)
for _, user := range users {
go func() {
fmt.Println(user.Name) // Now safe in Go 1.22+
}()
}
每周安装次数
68
代码仓库
GitHub 星标数
45
首次出现
2026年1月24日
安全审计
安装于
opencode58
claude-code56
gemini-cli54
codex53
cursor51
github-copilot46
Provides expert Go programming capabilities specializing in Go 1.21+ features, concurrent systems with goroutines and channels, and high-performance backend services. Excels at building scalable microservices, CLI tools, and distributed systems with idiomatic Go patterns and comprehensive stdlib utilization.
Expert Go developer specializing in Go 1.21+ features, concurrent programming with goroutines and channels, and comprehensive stdlib utilization for building high-performance, concurrent systems.
Use Case Analysis
│
├─ Need to process multiple items independently?
│ └─ Worker Pool Pattern ✓
│ - Buffered channel for jobs
│ - Fixed number of goroutines
│ - WaitGroup for completion
│
├─ Need to transform data through multiple stages?
│ └─ Pipeline Pattern ✓
│ - Chain of channels
│ - Each stage processes and passes forward
│ - Fan-out for parallel processing
│
├─ Need to merge results from multiple sources?
│ └─ Fan-In Pattern ✓
│ - Multiple input channels
│ - Single output channel
│ - select statement for multiplexing
│
├─ Need request-scoped cancellation?
│ └─ Context Pattern ✓
│ - context.WithCancel()
│ - context.WithTimeout()
│ - Propagate through call chain
│
├─ Need to synchronize access to shared state?
│ ├─ Read-heavy workload → sync.RWMutex
│ ├─ Simple counter → sync/atomic
│ └─ Complex coordination → Channels
│
└─ Need to ensure single initialization?
└─ sync.Once ✓
| Scenario | Pattern | Example |
|---|---|---|
| Wrap errors with context | fmt.Errorf("%w") | return fmt.Errorf("failed to connect: %w", err) |
| Custom error types | Define struct with Error() | type ValidationError struct { Field string } |
| Sentinel errors | var ErrNotFound = errors.New("not found") | if errors.Is(err, ErrNotFound) { ... } |
| Check error type | errors.As() |
HTTP Server Requirements
│
├─ Need full-featured framework with middleware?
│ └─ Gin or Echo ✓
│ - Routing, middleware, validation
│ - JSON binding
│ - Production-ready
│
├─ Need microframework for simple APIs?
│ └─ Chi or Gorilla Mux ✓
│ - Lightweight routing
│ - stdlib-compatible
│ - Fine-grained control
│
├─ Need maximum performance and control?
│ └─ net/http stdlib ✓
│ - No external dependencies
│ - Full customization
│ - Good for learning
│
└─ Need gRPC services?
└─ google.golang.org/grpc ✓
- Protocol Buffers
- Streaming support
- Cross-language
| Observation | Why Escalate | Example |
|---|---|---|
| Goroutine leak causing memory growth | Complex lifecycle management | "Memory grows indefinitely, suspect goroutines not terminating" |
| Race condition despite mutexes | Subtle synchronization bug | "go test -race shows data race in production code" |
| Context cancellation not propagating | Distributed system coordination | "Canceled requests still running after client disconnect" |
| Generics causing compile-time explosion | Type system complexity | "Generic function with constraints causing 10+ min compile time" |
| CGO memory corruption | Unsafe code interaction | "Segfaults when calling C library from Go" |
Scenario : Production-ready HTTP server with middleware and graceful shutdown
Step 1: Define server structure
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type Server struct {
httpServer *http.Server
logger *log.Logger
}
func NewServer(addr string, handler http.Handler) *Server {
return &Server{
httpServer: &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
},
logger: log.New(os.Stdout, "[SERVER] ", log.LstdFlags|log.Lmicroseconds),
}
}
func (s *Server) Start() error {
s.logger.Printf("Starting server on %s", s.httpServer.Addr)
if err := s.httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func (s *Server) Shutdown(ctx context.Context) error {
s.logger.Println("Shutting down server...")
return s.httpServer.Shutdown(ctx)
}
Step 2: Implement middleware
// Middleware for logging
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Wrap response writer to capture status code
wrapped := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(wrapped, r)
log.Printf("%s %s %d %s", r.Method, r.URL.Path, wrapped.statusCode, time.Since(start))
})
}
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// Middleware for panic recovery
func RecoveryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("Panic recovered: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
// Middleware for request timeout
func TimeoutMiddleware(timeout time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
r = r.WithContext(ctx)
done := make(chan struct{})
go func() {
next.ServeHTTP(w, r)
close(done)
}()
select {
case <-done:
return
case <-ctx.Done():
http.Error(w, "Request Timeout", http.StatusRequestTimeout)
}
})
}
}
Step 3: Setup routes and graceful shutdown
func main() {
// Setup routes
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
// Simulate slow endpoint
time.Sleep(2 * time.Second)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"users": []}`))
})
// Apply middleware chain
handler := RecoveryMiddleware(LoggingMiddleware(TimeoutMiddleware(5 * time.Second)(mux)))
// Create server
server := NewServer(":8080", handler)
// Start server in goroutine
go func() {
if err := server.Start(); err != nil {
log.Fatalf("Server failed: %v", err)
}
}()
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
// Graceful shutdown with 30s timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Printf("Server shutdown error: %v", err)
}
log.Println("Server stopped")
}
Expected outcome :
Use case : Cancel all downstream operations when client disconnects
// Template: Context-aware HTTP handler
func HandleRequest(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Pass context to all downstream calls
result, err := fetchData(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
// Client disconnected
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(result)
}
func fetchData(ctx context.Context) (*Data, error) {
// Check context before expensive operation
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
// Simulate database call with timeout
resultChan := make(chan *Data, 1)
errChan := make(chan error, 1)
go func() {
// Actual database query
time.Sleep(2 * time.Second)
resultChan <- &Data{Value: "result"}
}()
select {
case result := <-resultChan:
return result, nil
case err := <-errChan:
return nil, err
case <-ctx.Done():
return nil, ctx.Err() // Canceled or timed out
}
}
Use case : Comprehensive test coverage with minimal code
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -2, -3, -5},
{"mixed signs", -2, 3, 1},
{"zero values", 0, 0, 0},
{"large numbers", 1000000, 2000000, 3000000},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)
}
})
}
}
What it looks like:
// WRONG: All goroutines reference same variable
for _, user := range users {
go func() {
fmt.Println(user.Name) // Captures loop variable by reference!
}()
}
// Prints last user's name multiple times!
Why it fails:
Correct approach:
// CORRECT: Pass variable as argument (Go 1.21 and earlier)
for _, user := range users {
go func(u User) {
fmt.Println(u.Name) // Each goroutine has own copy
}(user)
}
// CORRECT: Use local variable (Go 1.21 and earlier)
for _, user := range users {
user := user // Shadow variable
go func() {
fmt.Println(user.Name)
}()
}
// Go 1.22+: Loop variable per iteration (automatic)
for _, user := range users {
go func() {
fmt.Println(user.Name) // Now safe in Go 1.22+
}()
}
Weekly Installs
68
Repository
GitHub Stars
45
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode58
claude-code56
gemini-cli54
codex53
cursor51
github-copilot46
Go语言命名规范指南 - 代码规范与最佳实践
729 周安装
var valErr *ValidationError; if errors.As(err, &valErr) { ... } |
| Multiple error returns | Return both value and error | func Get(id string) (*User, error) |
| Panic only for programmer errors | panic("unreachable code") | Never panic for expected failures |