mirror of
https://github.com/zeromicro/go-zero.git
synced 2026-05-07 15:10:01 +08:00
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: kevwan <1918356+kevwan@users.noreply.github.com>
6.7 KiB
6.7 KiB
GitHub Copilot Instructions for go-zero
This document provides guidelines for GitHub Copilot when assisting with development in the go-zero project.
Project Overview
go-zero is a web and RPC framework with lots of built-in engineering practices designed to ensure the stability of busy services with resilience design. It has been serving sites with tens of millions of users for years.
Key Architecture Components
- REST API framework (
rest/) - HTTP service framework with middleware support - RPC framework (
zrpc/) - gRPC-based RPC framework with service discovery - Core utilities (
core/) - Foundational components including:- Circuit breakers, rate limiters, load shedding
- Caching, stores (Redis, MongoDB, SQL)
- Concurrency control, metrics, tracing
- Configuration management
- Code generation tool (
tools/goctl/) - CLI tool for generating code from API files
Coding Standards and Conventions
Code Style
- Follow Go conventions: Use
gofmtfor formatting, follow effective Go practices - Package naming: Use lowercase, single-word package names when possible
- Error handling: Always handle errors explicitly, use
errorx.BatchErrorfor multiple errors - Context propagation: Always pass
context.Contextas the first parameter for functions that may block - Configuration structures: Use struct tags with JSON annotations and default values
Example configuration pattern:
type Config struct {
Host string `json:",default=0.0.0.0"`
Port int `json:",default=8080"`
Timeout int `json:",default=3000"`
Optional string `json:",optional"`
}
Interface Design
- Small interfaces: Follow Go's preference for small, focused interfaces
- Context methods: Provide both context and non-context versions of methods
- Options pattern: Use functional options for complex configuration
Example:
func (c *Client) Get(key string, val any) error {
return c.GetCtx(context.Background(), key, val)
}
func (c *Client) GetCtx(ctx context.Context, key string, val any) error {
// implementation
}
Testing Patterns
- Test file naming: Use
*_test.gosuffix - Test function naming: Use
TestFunctionNamepattern - Use testify/assert: Prefer
assertpackage for assertions - Table-driven tests: Use table-driven tests for multiple scenarios
- Mock interfaces: Use
go.uber.org/mockfor mocking - Test helpers: Use
redistest,mongtesthelpers for database testing
Example test pattern:
func TestSomething(t *testing.T) {
tests := []struct {
name string
input string
expected string
wantErr bool
}{
{"valid case", "input", "output", false},
{"error case", "bad", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := SomeFunction(tt.input)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.expected, result)
})
}
}
Framework-Specific Guidelines
REST API Development
- API Definition: Use
.apifiles to define REST APIs - Handler pattern: Separate business logic into logic packages
- Middleware: Use built-in middlewares (tracing, logging, metrics, recovery)
- Response handling: Use
httpx.WriteJsonfor JSON responses - Error handling: Use
httpx.Errorfor HTTP error responses
RPC Development
- Protocol Buffers: Use protobuf for service definitions
- Service discovery: Integrate with etcd for service registration
- Load balancing: Use built-in load balancing strategies
- Interceptors: Implement interceptors for cross-cutting concerns
Database Operations
- SQL operations: Use
sqlxpackage for database operations - Caching: Implement caching patterns with
cachepackage - Transactions: Use proper transaction handling
- Connection pooling: Configure appropriate connection pools
Example cache pattern:
err := c.QueryRowCtx(ctx, &dest, key, func(ctx context.Context, conn sqlx.SqlConn) error {
return conn.QueryRowCtx(ctx, &dest, query, args...)
})
Configuration Management
- YAML configuration: Use YAML for configuration files
- Environment variables: Support environment variable overrides
- Validation: Include proper validation for configuration parameters
- Sensible defaults: Provide reasonable default values
Error Handling Best Practices
- Wrap errors: Use
fmt.Errorfwith%wverb to wrap errors - Custom errors: Define custom error types when needed
- Error logging: Log errors appropriately with context
- Graceful degradation: Implement fallback mechanisms
Performance Considerations
- Resource pools: Use connection pools and worker pools
- Circuit breakers: Implement circuit breaker patterns for external calls
- Rate limiting: Apply rate limiting to protect services
- Load shedding: Implement adaptive load shedding
- Metrics: Add appropriate metrics and monitoring
Security Guidelines
- Input validation: Validate all input parameters
- SQL injection prevention: Use parameterized queries
- Authentication: Implement proper JWT token handling
- HTTPS: Support TLS/HTTPS configurations
- CORS: Configure CORS appropriately for web APIs
Documentation Standards
- Package documentation: Include package-level documentation
- Function documentation: Document exported functions with examples
- API documentation: Maintain API documentation in sync
- README updates: Update README for significant changes
Common Patterns to Follow
Service Configuration
type ServiceConf struct {
Name string
Log logx.LogConf
Mode string `json:",default=pro,options=[dev,test,pre,pro]"`
// ... other common fields
}
Middleware Implementation
func SomeMiddleware() rest.Middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Pre-processing
next.ServeHTTP(w, r)
// Post-processing
}
}
}
Resource Management
Always implement proper resource cleanup using defer and context cancellation.
Build and Test Commands
- Build:
go build ./... - Test:
go test ./... - Test with race detection:
go test -race ./... - Format:
gofmt -w . - Generate code:
goctl api go -api *.api -dir .
Remember to run tests and ensure all checks pass before submitting changes. The project emphasizes high quality, performance, and reliability, so these should be primary considerations in all development work.