
Zero Skills
- 106 installs
- 81 repo stars
- Updated April 26, 2026
- zeromicro/zero-skills
Helps with ai & agent building tasks.
About
zero-skills is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- zero-skills
- AI & Agent Building
- AI-coding skill
Zero Skills by the numbers
- 106 all-time installs (skills.sh)
- +2 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #4,152 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/zeromicro/zero-skills --skill zero-skillsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 106 |
|---|---|
| repo stars | ★ 81 |
| Last updated | April 26, 2026 |
| Repository | zeromicro/zero-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
go-zero Skills for AI Agents
This skill provides comprehensive go-zero microservices framework knowledge, optimized for AI agents helping developers build production-ready services. It covers REST APIs, RPC services, database operations, resilience patterns, and troubleshooting.
🎯 When to Use This Skill
Invoke this skill when working with go-zero:
- Creating services: REST APIs, gRPC services, or microservices architectures
- Database integration: SQL, MongoDB, Redis, or connection pooling
- Production hardening: Circuit breakers, rate limiting, or error handling
- Debugging: Understanding errors, fixing configuration, or resolving issues
- Learning: Understanding go-zero patterns and best practices
📚 Knowledge Structure
This skill organizes go-zero knowledge into focused modules. Load specific guides as needed rather than reading everything at once:
Quick Start Guide
Link: Official go-zero Documentation Contains: Installation, first API service, basic commands, hello-world examples (refer to official docs)
Pattern Guides (Detailed Reference)
1. REST API Patterns
File: references/rest-api-patterns.md When to load: Creating HTTP endpoints, implementing CRUD operations, adding middleware Contains:
- Handler → Logic → Context three-layer architecture
- Request/response handling with proper types
- Middleware (auth, logging, metrics, CORS)
- Error handling with
httpx.Error()andhttpx.OkJson() - Complete CRUD examples with ✅ correct vs ❌ incorrect patterns
2. RPC Service Patterns
File: references/rpc-patterns.md When to load: Building gRPC services, service-to-service communication Contains:
- Protocol Buffers definition and code generation
- Service discovery with etcd/consul/kubernetes
- Load balancing strategies
- Client configuration and interceptors
- Error handling in RPC contexts
3. Database Patterns
File: references/database-patterns.md When to load: Implementing data persistence, caching, or complex queries Contains:
- SQL operations with sqlx (CRUD, transactions, batch inserts)
- MongoDB integration patterns
- Redis caching strategies and cache-aside pattern
- Model generation with
goctl model - Connection pooling and performance tuning
4. Resilience Patterns
File: references/resilience-patterns.md When to load: Production hardening, handling failures, managing system load Contains:
- Circuit breaker configuration (Breaker)
- Rate limiting and API throttling
- Load shedding under pressure
- Timeout and retry strategies
- Graceful shutdown and degradation
5. goctl Command Reference
File: references/goctl-commands.md When to load: Generating code with goctl, setting up new services, post-generation steps Contains:
- goctl installation and detection
- API/RPC/Model generation commands with exact flags
- Post-generation pipeline (mod tidy, import fixing, build verification)
- Config templates (API, RPC, production)
- Deployment templates (Dockerfile, Kubernetes, Docker Compose)
- Middleware and error handler templates
- API spec patterns (CRUD, JWT, mixed auth)
Supporting Resources
Best Practices
File: best-practices/overview.md When to load: Production deployment, code review, optimization Contains: Configuration management, logging, monitoring, security, performance
Troubleshooting
File: troubleshooting/common-issues.md When to load: Debugging errors, configuration issues, runtime problems Contains: Common error messages, solutions, configuration pitfalls, debugging tips
Claude Code Integration
File: getting-started/claude-code-guide.md When to load: Setting up Claude Code for zero-skills usage Contains: Installation, invocation methods, advanced features (subagents, dynamic context)
Tool Integration Guides
File: getting-started/README.md When to load: Setting up zero-skills with Cursor, GitHub Copilot, Windsurf, or Codex Contains: Feature comparison table, per-tool setup instructions (Claude Code, Cursor, Copilot, Windsurf, Codex)
🚀 Common Workflows
These workflows guide you through typical go-zero development tasks:
Creating a New REST API Service
Steps: 1. Define API specification in .api file with types and routes 2. Generate code: goctl api go -api user.api -dir . 3. Implement business logic in internal/logic/ layer 4. Add validation and error handling with httpx 5. Test endpoints with proper request/response handling
Detailed guide: references/rest-api-patterns.md
Implementing Database Operations
Steps: 1. Design database schema and create tables 2. Generate model: goctl model mysql datasource -url="..." -table="users" -dir="./model" 3. Inject model into ServiceContext in internal/svc/service_context.go 4. Use sqlx methods in logic layer (Insert, FindOne, Update, Delete) 5. Handle transactions and errors properly with ctx propagation
Detailed guide: references/database-patterns.md
Adding Middleware
Steps: 1. Create middleware function in internal/middleware/ directory 2. Define middleware in .api file or register programmatically 3. Implement authentication/authorization logic 4. Pass validated data through r.Context() 5. Handle errors with appropriate HTTP status codes
Detailed guide: references/rest-api-patterns.md
Building an RPC Service
Steps: 1. Define service in .proto file with messages and RPCs 2. Generate code: goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=. 3. Implement service logic in internal/logic/ 4. Configure service discovery (etcd/consul/kubernetes) 5. Test with RPC client and handle errors
Detailed guide: references/rpc-patterns.md
⚡ Key Principles
When generating or reviewing go-zero code, always apply these principles:
✅ Always Follow
- Three-layer separation: Keep Handler (routing) → Logic (business) → Model (data) distinct
- Structured errors: Use
httpx.Error(w, err)for HTTP errors, notfmt.Errorf - Configuration: Load with
conf.MustLoad(&c, *configFile)and inject via ServiceContext - Context propagation: Pass
ctx context.Contextthrough all layers for tracing and cancellation - Type safety: Define request/response types in
.apifiles, generate with goctl - goctl generation: Always use
goctlto generate boilerplate, never hand-write handlers/routes
❌ Never Do
- Put business logic directly in handlers (violates three-layer architecture)
- Return raw errors with
w.Write()orfmt.Fprintf()instead of using httpx helpers - Hard-code configuration values (ports, hosts, database credentials)
- Skip validation of user inputs or forget to check
err != nil - Modify generated code (customize via
logiclayer instead) - Bypass ServiceContext injection (leads to tight coupling and testing issues)
📖 Progressive Learning Path
Follow this path based on your needs:
🟢 New to go-zero?
1. Start here: Official go-zero Quick Start Install go-zero, create your first API, understand basic concepts
2. Add a database: references/database-patterns.md Connect to MySQL/PostgreSQL, generate models, implement CRUD
🟡 Building production services?
1. Review best practices: best-practices/overview.md Configuration, logging, monitoring, security checklist
2. Add resilience: references/resilience-patterns.md Circuit breakers, rate limiting, graceful degradation
3. Check common pitfalls: troubleshooting/common-issues.md Avoid typical mistakes and know how to debug issues
🔵 Extending capabilities?
1. Use with Claude Code: getting-started/claude-code-guide.md Learn advanced features like subagents, dynamic context, and argument passing Run demo projects to validate your environment
2. Verify knowledge: examples/verify-tutorial.sh Script to check if examples work correctly
🔗 Integration with go-zero AI Ecosystem
This skill is part of a two-layer ecosystem for AI-assisted go-zero development:
| Tool | Purpose | Best For |
|---|---|---|
| [ai-context](https://github.com/zeromicro/ai-context) | Concise workflow instructions (~5KB) | GitHub Copilot, Cursor, Windsurf |
| zero-skills (this repo) | Comprehensive knowledge base + goctl reference (~45KB) | All AI tools, deep learning, reference |
The AI runs goctl directly in the terminal for code generation — no separate MCP server needed. See references/goctl-commands.md for the complete command reference.
Usage in Claude Code:
- This skill loads automatically when working with go-zero projects
- Use
/zero-skillsto invoke manually for go-zero guidance - AI runs goctl commands directly in the terminal for code generation
- Reference specific pattern files when needed (Claude loads them on demand)
See getting-started/claude-code-guide.md for detailed usage instructions.
🌐 Additional Resources
- Official docs: go-zero.dev - Latest API reference and guides
- GitHub: zeromicro/go-zero - Source code and examples
- Community: Discussions, issues, and contributions welcome in the main repository
📝 Version Compatibility
- Target version: go-zero 1.5+
- Go version: Go 1.19 or later recommended
- Updates: Patterns updated regularly to reflect framework evolution
- Breaking changes: Check official docs for API changes between versions
---
Quick invocation: Use /zero-skills or ask "How do I [task] with go-zero?" Need help? Reference the specific pattern guide for detailed examples and explanations.
examples/demo-project/demo-workspace/
Best Practices
Code Organization
✅ Project Structure
service-name/
├── etc/
│ └── config.yaml # Configuration files
├── internal/
│ ├── config/
│ │ └── config.go # Config struct
│ ├── handler/
│ │ └── *handler.go # HTTP handlers (thin layer)
│ ├── logic/
│ │ └── *logic.go # Business logic (thick layer)
│ ├── middleware/
│ │ └── *middleware.go # Custom middlewares
│ ├── svc/
│ │ └── servicecontext.go # Dependency injection
│ ├── types/
│ │ └── types.go # Request/Response types
│ └── model/
│ └── *model.go # Database models
├── service.go # Entry point
└── service.api # API definitionKey Principles:
- Keep
handlerthin - only HTTP concerns - Put business logic in
logiclayer - Centralize dependencies in
svc - Generated code in
internal/, custom code alongside it
✅ File Naming
// Handlers: <resource><action>handler.go
createuserhandler.go
getuserhandler.go
updateuserhandler.go
// Logic: <resource><action>logic.go
createuserlogic.go
getuserlogic.go
updateuserlogic.go
// Models: <table>model.go
usermodel.go
ordermodel.go
productmodel.go
// Middleware: <purpose>middleware.go
authmiddleware.go
loggingmiddleware.go
ratelimitmiddleware.goConfiguration Management
✅ Configuration Pattern
// internal/config/config.go
type Config struct {
rest.RestConf // or zrpc.RpcServerConf for RPC
// Group related settings
Auth struct {
AccessSecret string
AccessExpire int64
}
Database struct {
DataSource string
Cache cache.CacheConf
}
Redis struct {
Host string
Type string
Pass string `json:",optional"`
}
// Use tags effectively
MaxUploadSize int64 `json:",default=10485760"` // 10MB
EnableFeature bool `json:",default=true"`
Environment string `json:",default=prod,options=[dev|test|prod]"`
}✅ Configuration File
# etc/service.yaml
Name: user-api
Host: 0.0.0.0
Port: 8888
Timeout: 30000
Auth:
AccessSecret: your-secret-key
AccessExpire: 3600
Database:
DataSource: "user:pass@tcp(localhost:3306)/db?parseTime=true"
Cache:
- Host: localhost:6379
Type: node
Redis:
Host: localhost:6379
Type: node
MaxUploadSize: 52428800 # 50MB
EnableFeature: true
Environment: prod✅ Environment Variables
// Support environment variable overrides
// Set in shell: export USER_API_PORT=9999
// Will override Port in config file
// Or use .env file with godotenv
import "github.com/joho/godotenv"
func main() {
_ = godotenv.Load() // Load .env file
var c config.Config
conf.MustLoad(*configFile, &c)
// ...
}Error Handling
✅ Error Definition
// Define errors at package level
var (
ErrUserNotFound = errors.New("user not found")
ErrInvalidInput = errors.New("invalid input")
ErrUnauthorized = errors.New("unauthorized")
ErrDuplicateEmail = errors.New("email already exists")
ErrInsufficientFunds = errors.New("insufficient funds")
)
// Or use custom error types
type BusinessError struct {
Code int
Message string
}
func (e *BusinessError) Error() string {
return e.Message
}✅ Error Wrapping
func (l *Logic) Operation() error {
user, err := l.svcCtx.UserModel.FindOne(l.ctx, id)
if err != nil {
// Wrap errors with context
return fmt.Errorf("failed to find user %d: %w", id, err)
}
// Use errors.Is for checking
if errors.Is(err, sqlc.ErrNotFound) {
return ErrUserNotFound
}
return nil
}✅ Error Response
// Custom error handler
httpx.SetErrorHandler(func(err error) (int, any) {
switch {
case errors.Is(err, ErrUserNotFound):
return http.StatusNotFound, map[string]string{
"code": "USER_NOT_FOUND",
"message": err.Error(),
}
case errors.Is(err, ErrInvalidInput):
return http.StatusBadRequest, map[string]string{
"code": "INVALID_INPUT",
"message": err.Error(),
}
case errors.Is(err, ErrUnauthorized):
return http.StatusUnauthorized, map[string]string{
"code": "UNAUTHORIZED",
"message": err.Error(),
}
default:
return http.StatusInternalServerError, map[string]string{
"code": "INTERNAL_ERROR",
"message": "internal server error",
}
}
})Logging
✅ Structured Logging
// Use logx for structured logging
import "github.com/zeromicro/go-zero/core/logx"
// In logic
func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (*types.CreateUserResponse, error) {
// Info level
l.Logger.Infof("creating user: %s", req.Email)
// With fields
l.Logger.WithFields(logx.Field("email", req.Email), logx.Field("age", req.Age)).
Info("user validation passed")
user, err := l.createUser(req)
if err != nil {
// Error level with context
l.Logger.Errorf("failed to create user %s: %v", req.Email, err)
return nil, err
}
// Success with result
l.Logger.Infow("user created successfully",
logx.Field("user_id", user.Id),
logx.Field("email", user.Email),
)
return &types.CreateUserResponse{Id: user.Id}, nil
}✅ Log Configuration
Log:
Mode: console # console or file
Level: info # debug, info, error, severe
Encoding: json # json or plain
Path: logs # for file mode
MaxSize: 100 # MB
MaxBackups: 30
MaxAge: 7 # days
Compress: true❌ Logging Anti-Patterns
// DON'T: Log sensitive information
l.Logger.Infof("user password: %s", password) // ❌
l.Logger.Infof("credit card: %s", ccNumber) // ❌
l.Logger.Infof("auth token: %s", token) // ❌
// DON'T: Log in loops without throttling
for _, item := range items {
l.Logger.Infof("processing %v", item) // ❌ Too verbose
}
// DON'T: Use print statements
fmt.Println("debug info") // ❌ Use l.Logger instead
log.Println("error") // ❌ Use l.Logger instead
// DO: Log summary
l.Logger.Infof("processing %d items", len(items)) // ✅Testing
✅ Unit Test Pattern
// logic_test.go
package logic
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
)
func TestCreateUserLogic_CreateUser(t *testing.T) {
tests := []struct {
name string
req *types.CreateUserRequest
wantErr bool
errMsg string
}{
{
name: "valid user",
req: &types.CreateUserRequest{
Name: "John Doe",
Email: "john@example.com",
Age: 25,
},
wantErr: false,
},
{
name: "invalid age",
req: &types.CreateUserRequest{
Name: "Jane Doe",
Email: "jane@example.com",
Age: 15,
},
wantErr: true,
errMsg: "age must be at least 18",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Setup
ctx := context.Background()
svcCtx := &svc.ServiceContext{
// Mock dependencies
}
logic := NewCreateUserLogic(ctx, svcCtx)
// Execute
resp, err := logic.CreateUser(tt.req)
// Assert
if tt.wantErr {
assert.Error(t, err)
if tt.errMsg != "" {
assert.Contains(t, err.Error(), tt.errMsg)
}
assert.Nil(t, resp)
} else {
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.Greater(t, resp.Id, int64(0))
}
})
}
}✅ Integration Test with Database
func TestUserModel_Integration(t *testing.T) {
// Setup test database
conn := sqlx.NewMysql("test:test@tcp(localhost:3306)/testdb")
model := NewUsersModel(conn, cache.CacheConf{})
ctx := context.Background()
// Cleanup after test
defer func() {
conn.Exec("DELETE FROM users WHERE email = ?", "test@example.com")
}()
// Test insert
user := &Users{
Name: "Test User",
Email: "test@example.com",
Age: 25,
}
result, err := model.Insert(ctx, user)
assert.NoError(t, err)
userId, _ := result.LastInsertId()
assert.Greater(t, userId, int64(0))
// Test find
found, err := model.FindOne(ctx, userId)
assert.NoError(t, err)
assert.Equal(t, user.Name, found.Name)
assert.Equal(t, user.Email, found.Email)
}✅ Mock Dependencies
import "go.uber.org/mock/gomock"
func TestWithMock(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// Create mock
mockModel := mock.NewMockUsersModel(ctrl)
// Set expectations
mockModel.EXPECT().
FindOne(gomock.Any(), int64(1)).
Return(&model.Users{
Id: 1,
Name: "John",
Email: "john@example.com",
}, nil)
// Use mock in test
svcCtx := &svc.ServiceContext{
UsersModel: mockModel,
}
logic := NewGetUserLogic(context.Background(), svcCtx)
resp, err := logic.GetUser(&types.GetUserRequest{Id: 1})
assert.NoError(t, err)
assert.Equal(t, "John", resp.Name)
}Performance
✅ Connection Pooling
// Reuse connections - initialized once in service context
func NewServiceContext(c config.Config) *ServiceContext {
// Single connection pool for entire service
conn := sqlx.NewMysql(c.DataSource)
// Single Redis client
rds := redis.MustNewRedis(c.Redis)
return &ServiceContext{
Config: c,
DB: conn,
Redis: rds,
UsersModel: model.NewUsersModel(conn, c.Cache),
}
}
// DON'T create connections in handlers or logic✅ Caching Strategy
// Cache read-heavy data
func (l *GetUserLogic) GetUser(req *types.GetUserRequest) (*types.GetUserResponse, error) {
// Automatic cache with model
user, err := l.svcCtx.UsersModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, err
}
return &types.GetUserResponse{
Id: user.Id,
Name: user.Name,
Email: user.Email,
}, nil
}
// Manual cache for complex queries
func (l *GetUserStatsLogic) GetUserStats(userId int64) (*Stats, error) {
cacheKey := fmt.Sprintf("user:stats:%d", userId)
var stats Stats
err := l.svcCtx.Redis.GetCtx(l.ctx, cacheKey, &stats)
if err == nil {
return &stats, nil
}
// Cache miss - fetch from DB
stats, err = l.fetchStatsFromDB(userId)
if err != nil {
return nil, err
}
// Cache for 1 hour
l.svcCtx.Redis.SetexCtx(l.ctx, cacheKey, stats, 3600)
return &stats, nil
}✅ Batch Operations
// Use MapReduce for parallel processing
import "github.com/zeromicro/go-zero/core/mr"
func (l *BatchLogic) ProcessUsers(userIds []int64) error {
_, err := mr.MapReduce(
func(source chan<- interface{}) {
for _, id := range userIds {
source <- id
}
},
func(item interface{}, writer mr.Writer, cancel func(error)) {
id := item.(int64)
if err := l.processUser(id); err != nil {
l.Logger.Errorf("failed to process user %d: %v", id, err)
}
},
func(pipe <-chan interface{}, writer mr.Writer, cancel func(error)) {
// Aggregate if needed
},
mr.WithWorkers(10),
)
return err
}❌ Performance Anti-Patterns
// DON'T: Query in loops (N+1 problem)
for _, orderId := range orderIds {
order, _ := l.svcCtx.OrderModel.FindOne(l.ctx, orderId) // ❌
orders = append(orders, order)
}
// DO: Batch query
orders, err := l.svcCtx.OrderModel.FindMany(l.ctx, orderIds) // ✅
// DON'T: Create goroutines without limit
for _, item := range items {
go l.process(item) // ❌ Unbounded goroutines
}
// DO: Use worker pool
workers := threading.NewTaskRunner(10) // ✅ Limited to 10
for _, item := range items {
item := item
workers.Schedule(func() {
l.process(item)
})
}
workers.Wait()Security
✅ Input Validation
// Use validation tags
type CreateUserRequest struct {
Name string `json:"name" validate:"required,min=2,max=50"`
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"required,gte=18,lte=120"`
Password string `json:"password" validate:"required,min=8"`
}
// Validate in logic
import "github.com/go-playground/validator/v10"
func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (*types.CreateUserResponse, error) {
validate := validator.New()
if err := validate.Struct(req); err != nil {
return nil, fmt.Errorf("validation failed: %w", err)
}
// Continue processing...
}✅ Password Handling
import "golang.org/x/crypto/bcrypt"
// Hash password before storing
func hashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
// Verify password
func checkPassword(hashedPassword, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}
// In logic
func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (*types.CreateUserResponse, error) {
// Hash password
hashedPassword, err := hashPassword(req.Password)
if err != nil {
return nil, err
}
user := &model.Users{
Name: req.Name,
Email: req.Email,
Password: hashedPassword, // Store hashed password
}
// Never log the password
l.Logger.Infof("creating user: %s", req.Email)
// ...
}✅ JWT Authentication
import "github.com/golang-jwt/jwt/v4"
func generateToken(userId int64, secret string, expire int64) (string, error) {
now := time.Now().Unix()
claims := make(jwt.MapClaims)
claims["userId"] = userId
claims["iat"] = now
claims["exp"] = now + expire
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secret))
}
func validateToken(tokenString, secret string) (int64, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil || !token.Valid {
return 0, errors.New("invalid token")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return 0, errors.New("invalid claims")
}
userId := int64(claims["userId"].(float64))
return userId, nil
}❌ Security Anti-Patterns
// DON'T: Store plain text passwords
user.Password = req.Password // ❌
// DON'T: Log sensitive data
l.Logger.Infof("password: %s", password) // ❌
l.Logger.Infof("token: %s", token) // ❌
// DON'T: Use weak secrets
secret := "123456" // ❌
// DON'T: Expose internal errors to clients
return nil, fmt.Errorf("database error: %v", err) // ❌
// DO: Return generic error
return nil, errors.New("internal server error") // ✅
// DON'T: Trust user input without validation
filePath := req.FilePath // ❌ Path traversal risk
// DO: Validate and sanitize
filePath := filepath.Clean(req.FilePath) // ✅Deployment
✅ Docker
# Dockerfile
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o service .
FROM alpine:latest
RUN apk --no-cache add ca-certificates tzdata
WORKDIR /app
COPY --from=builder /app/service .
COPY --from=builder /app/etc ./etc
EXPOSE 8888
CMD ["./service", "-f", "etc/config.yaml"]✅ Kubernetes
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-api
spec:
replicas: 3
selector:
matchLabels:
app: user-api
template:
metadata:
labels:
app: user-api
spec:
containers:
- name: user-api
image: user-api:latest
ports:
- containerPort: 8888
env:
- name: USER_API_MODE
value: "pro"
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /healthz
port: 8888
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8888
initialDelaySeconds: 5
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: user-api
spec:
selector:
app: user-api
ports:
- port: 8888
targetPort: 8888
type: ClusterIPSummary
Always Do:
1. Keep handlers thin, logic thick 2. Use structured logging with context 3. Handle all errors explicitly 4. Validate input thoroughly 5. Use connection pooling 6. Enable caching for read-heavy data 7. Write unit tests 8. Use transactions for atomic operations 9. Implement proper security measures 10. Monitor production metrics
Never Do:
1. Put business logic in handlers 2. Log sensitive information 3. Ignore errors 4. Create connections in handlers 5. Query in loops 6. Disable resilience features in production 7. Use global variables 8. Block without timeouts 9. Create unbounded goroutines 10. Trust user input without validation
Demo Project - GitHub Copilot with go-zero
This demo project demonstrates how to use GitHub Copilot + ai-context to develop go-zero applications.
Quick Start
Prerequisites
- Go 1.19+
- Git
- VS Code with GitHub Copilot extension
- goctl (will be installed automatically)
Setup Demo Project
# Run setup script
cd /Users/kevin/Develop/go/zero-skills/examples/demo-project
./setup-demo.shThe script will automatically: 1. ✅ Check and install dependencies (Go, goctl) 2. ✅ Create demo workspace directory 3. ✅ Configure GitHub Copilot (add ai-context submodule) 4. ✅ Generate go-zero API project using goctl 5. ✅ Create sample API definition (user management) 6. ✅ Generate complete project structure
Verify Configuration
cd demo-workspace
./verify-copilot.shYou should see:
✓ ai-context submodule exists
✓ copilot-instructions.md symlink exists
✓ Configuration file contains go-zero content
✓ go-zero project structure is correct
✓ All checks passed!Project Structure
demo-workspace/
├── .github/
│ ├── ai-context/ # ai-context submodule
│ └── copilot-instructions.md # -> ai-context/00-instructions.md
├── userapidemo/
│ ├── etc/
│ │ └── user-api.yaml # Configuration file
│ ├── internal/
│ │ ├── config/ # Config definitions
│ │ ├── handler/ # HTTP handler layer
│ │ │ ├── createuserhandler.go
│ │ │ ├── getuserhandler.go
│ │ │ └── listusershandler.go
│ │ ├── logic/ # Business logic layer
│ │ │ ├── createuserlogic.go
│ │ │ ├── getuserlogic.go
│ │ │ └── listuserslogic.go
│ │ ├── svc/ # Service context
│ │ │ └── servicecontext.go
│ │ └── types/ # Type definitions
│ │ └── types.go
│ ├── user.api # API definition file
│ ├── userapidemo.go # Main entry point
│ └── README.md # Project documentation
└── verify-copilot.sh # Verification scriptTesting GitHub Copilot
Test Scenario 1: Implement CreateUser Business Logic
1. Open the project in VS Code:
cd demo-workspace/userapidemo
code .2. Open file: internal/logic/createuserlogic.go
3. In the CreateUser method, try typing the following comment:
// Validate username is not empty4. Expected behavior:
- ✅ Copilot suggests go-zero error handling patterns
- ✅ Uses
errorxor standard error returns - ✅ Follows Logic layer responsibilities
- ✅ Correctly uses
reqandtypesdefinitions
5. Example implementation (Copilot might suggest):
func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (*types.CreateUserResponse, error) {
// Validate username is not empty
if req.Username == "" {
return nil, errors.New("username is required")
}
// Validate email format
if req.Email == "" {
return nil, errors.New("email is required")
}
// TODO: Save to database
user := types.User{
Id: 1,
Username: req.Username,
Email: req.Email,
CreateAt: time.Now().Format("2006-01-02 15:04:05"),
}
return &types.CreateUserResponse{
User: user,
}, nil
}Test Scenario 2: Add Middleware
1. Create new file: internal/middleware/auth.go
2. Type:
package middleware
import "net/http"
// JWT authentication middleware3. Expected behavior:
- ✅ Copilot suggests go-zero middleware pattern
- ✅ Returns
func(http.HandlerFunc) http.HandlerFunc - ✅ Proper error response handling
- ✅ Uses
httpxutilities
Test Scenario 3: Add Database Operations
1. Create comment:
// TODO: Add MySQL connection and user table operations2. Expected behavior:
- ✅ Copilot suggests using
sqlxorgo-zero/core/stores/sqlx - ✅ Suggests using
goctl modelfor code generation - ✅ Provides correct database configuration patterns
Comparison Test
Copilot WITH ai-context
// Input: Implement user creation
// Copilot suggests:
func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (*types.CreateUserResponse, error) {
// ✅ Correct parameter validation
// ✅ Uses go-zero error handling
// ✅ Return type matches types definitions
// ✅ Follows business logic in Logic layer principle
}Copilot WITHOUT ai-context
// Input: Implement user creation
// Copilot might suggest:
func CreateUser(w http.ResponseWriter, r *http.Request) {
// ❌ Business logic directly in handler
// ❌ Uses generic HTTP patterns, not go-zero compliant
// ❌ Error handling might use http.Error
}Verification
1. Check Copilot Configuration
# Confirm Copilot loaded the configuration
cat demo-workspace/.github/copilot-instructions.md | head -20
# Should see go-zero related instructions2. Test Code Suggestion Quality
When implementing business logic, observe Copilot suggestions:
- Does it follow three-layer architecture?
- Does it use correct error handling?
- Does it understand go-zero utilities?
3. Run the Project
cd demo-workspace/userapidemo
# Run the service
go run userapidemo.go -f etc/user-api.yaml
# Test API (in another terminal)
curl http://localhost:8888/api/usersCommon Issues
Q: Copilot not using go-zero patterns?
A: Check: 1. Is VS Code opened in the correct project directory? 2. Does .github/copilot-instructions.md file exist? 3. Restart VS Code to reload Copilot configuration
Q: Symlinks don't work on Windows?
A: On Windows, run with administrator privileges:
mklink .github\copilot-instructions.md .github\ai-context\00-instructions.mdOr copy the file directly:
copy .github\ai-context\00-instructions.md .github\copilot-instructions.mdQ: goctl command not found?
A: Install goctl:
go install github.com/zeromicro/go-zero/tools/goctl@latestCleanup
Delete the demo project:
rm -rf demo-workspaceMore Resources
- ai-context - GitHub Copilot instructions
- zero-skills - go-zero knowledge base
- go-zero Documentation
- Claude Code Guide
#!/bin/bash
# Demo project setup script for testing GitHub Copilot with go-zero
set -e
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'
PROJECT_NAME="userapidemo"
DEMO_DIR="$(pwd)/demo-workspace"
echo -e "${BLUE}================================================${NC}"
echo -e "${BLUE}go-zero AI Ecosystem Demo Project Setup${NC}"
echo -e "${BLUE}================================================${NC}"
echo ""
# Check dependencies
echo "Checking dependencies..."
if ! command -v go &> /dev/null; then
echo -e "${RED}Error: Go is not installed. Please install Go first.${NC}"
exit 1
fi
if ! command -v goctl &> /dev/null; then
echo -e "${YELLOW}Warning: goctl not installed, installing...${NC}"
go install github.com/zeromicro/go-zero/tools/goctl@latest
fi
echo -e "${GREEN}✓ Dependencies check completed${NC}"
echo ""
# Create demo directory
echo "Creating demo project directory: $DEMO_DIR"
mkdir -p "$DEMO_DIR"
cd "$DEMO_DIR"
# Initialize git repository
if [ ! -d ".git" ]; then
git init -q
echo -e "${GREEN}✓ Git repository initialized${NC}"
fi
# Configure GitHub Copilot (add ai-context)
echo ""
echo "Configuring GitHub Copilot..."
if [ ! -d ".github/ai-context" ]; then
git submodule add -q https://github.com/zeromicro/ai-context.git .github/ai-context 2>/dev/null || echo "Submodule already exists"
mkdir -p .github
ln -sf ai-context/00-instructions.md .github/copilot-instructions.md
echo -e "${GREEN}✓ GitHub Copilot configured${NC}"
echo -e " - Submodule: .github/ai-context"
echo -e " - Instructions: .github/copilot-instructions.md"
else
echo -e "${YELLOW}⚠ GitHub Copilot already configured${NC}"
fi
# Create project structure
echo ""
echo "Creating go-zero API project structure..."
if [ -d "$PROJECT_NAME" ]; then
echo -e "${YELLOW}⚠ Project exists, removing and recreating...${NC}"
rm -rf "$PROJECT_NAME"
fi
mkdir -p "$PROJECT_NAME"
cd "$PROJECT_NAME"
# Create API definition file
echo ""
echo "Creating API definition file..."
cat > user.api << 'EOF'
syntax = "v1"
info (
title: "User Service API"
desc: "User management API"
author: "go-zero"
version: "1.0"
)
type (
// User information
User {
Id int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
CreateAt string `json:"create_at"`
}
// Create user request
CreateUserRequest {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
// Create user response
CreateUserResponse {
User User `json:"user"`
}
// Get user request
GetUserRequest {
Id int64 `path:"id"`
}
// Get user response
GetUserResponse {
User User `json:"user"`
}
// List users request
ListUsersRequest {
Page int `form:"page,default=1"`
PageSize int `form:"page_size,default=10"`
}
// List users response
ListUsersResponse {
Users []User `json:"users"`
Total int64 `json:"total"`
}
)
service user-api {
@doc "Create user"
@handler CreateUser
post /api/users (CreateUserRequest) returns (CreateUserResponse)
@doc "Get user details"
@handler GetUser
get /api/users/:id (GetUserRequest) returns (GetUserResponse)
@doc "List users"
@handler ListUsers
get /api/users (ListUsersRequest) returns (ListUsersResponse)
}
EOF
echo -e "${GREEN}✓ API definition file created: user.api${NC}"
# Generate code
echo ""
echo "Generating go-zero code..."
goctl api go -api user.api -dir . -style go_zero
echo -e "${GREEN}✓ Code generation completed${NC}"
# Initialize go module
echo ""
echo "Initializing Go module..."
if [ ! -f "go.mod" ]; then
go mod init $PROJECT_NAME
fi
go mod tidy
echo -e "${GREEN}✓ Go module initialized${NC}"
# Create .gitignore
cat > .gitignore << 'EOF'
# Binaries
*.exe
*.exe~
*.dll
*.so
*.dylib
*.test
*.out
userapidemo
# Go workspace
go.work
go.work.sum
# IDE
.idea/
.vscode/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
EOF
echo -e "${GREEN}✓ .gitignore created${NC}"
# Build project to verify
echo ""
echo "Building project to verify..."
if go build -o userapidemo .; then
echo -e "${GREEN}✓ Build successful${NC}"
rm -f userapidemo # Clean up binary
else
echo -e "${RED}✗ Build failed${NC}"
exit 1
fi
# Create README
cat > README.md << 'EOF'
# User API Demo - go-zero with GitHub Copilot
This is a go-zero demo project configured with GitHub Copilot + ai-context.
## Project Structure
```
userapidemo/
├── etc/ # Configuration files
├── internal/
│ ├── handler/ # HTTP handlers
│ ├── logic/ # Business logic
│ ├── svc/ # Service context
│ └── types/ # Type definitions
├── user.api # API definition file
└── userapidemo.go # Main entry point
```
## Running the Service
```bash
# Run the service
go run userapidemo.go -f etc/user-api.yaml
# The service will start on http://localhost:8888
```
## Testing with curl
```bash
# Create a user
curl -X POST http://localhost:8888/api/users \
-H "Content-Type: application/json" \
-d '{"username":"john","email":"john@example.com","password":"secret"}'
# Get user by ID
curl http://localhost:8888/api/users/1
# List users
curl http://localhost:8888/api/users?page=1&page_size=10
```
## Testing GitHub Copilot
### Scenario 1: Implement CreateUser Logic
1. Open `internal/logic/createuserlogic.go` in VS Code
2. In the `CreateUser` method, try typing:
```go
// TODO: Validate username is not empty
```
3. **Expected behavior**:
- ✅ Copilot suggests go-zero error handling
- ✅ Uses proper error returns
- ✅ Follows Logic layer responsibilities
- ✅ Correctly uses `req` and `types` definitions
### Scenario 2: Add Database Model
1. Try creating a comment in the project:
```go
// TODO: Add MySQL user table model
```
2. **Expected behavior**:
- Copilot suggests using `goctl model` commands
- Suggests proper model structure
- Includes database connection in ServiceContext
### Scenario 3: Add Middleware
1. Create `internal/middleware/auth.go`
2. Try typing:
```go
// TODO: JWT authentication middleware
```
3. **Expected behavior**:
- Copilot suggests middleware pattern
- Includes proper context handling
- Shows how to register in routes
## Implementation Tips
The business logic should be implemented in the `internal/logic/` directory:
- **createuserlogic.go**: Validate input, create user, return response
- **getuserlogic.go**: Fetch user by ID, handle not found
- **listuserslogic.go**: Paginate users, return list with total count
Use the Handler → Logic → Model three-layer architecture.
## Resources
- [go-zero Official Docs](https://go-zero.dev)
- [zero-skills Pattern Guides](https://github.com/zeromicro/zero-skills)
- [ai-context Instructions](https://github.com/zeromicro/ai-context)
EOF
echo -e "${GREEN}✓ README.md created${NC}"
# Return to demo-workspace root
cd "$DEMO_DIR"
# Create verification script
cat > verify-copilot.sh << 'EOF'
#!/bin/bash
# Verification script for GitHub Copilot configuration
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'
echo "Verifying GitHub Copilot configuration..."
echo ""
# Check 1: ai-context submodule exists
if [ -d ".github/ai-context" ]; then
echo -e "${GREEN}✓${NC} ai-context submodule exists"
else
echo -e "${RED}✗${NC} ai-context submodule does not exist"
exit 1
fi
# Check 2: copilot-instructions.md symlink exists
if [ -L ".github/copilot-instructions.md" ]; then
echo -e "${GREEN}✓${NC} copilot-instructions.md symlink exists"
else
echo -e "${RED}✗${NC} copilot-instructions.md symlink does not exist"
exit 1
fi
# Check 3: Configuration file contains go-zero content
if grep -q "go-zero" .github/copilot-instructions.md; then
echo -e "${GREEN}✓${NC} Configuration file contains go-zero content"
else
echo -e "${RED}✗${NC} Configuration file does not contain go-zero content"
exit 1
fi
# Check 4: Project structure is correct
if [ -d "userapidemo/internal" ]; then
echo -e "${GREEN}✓${NC} go-zero project structure is correct"
else
echo -e "${RED}✗${NC} go-zero project structure is incorrect"
exit 1
fi
echo ""
echo -e "${GREEN}✓ All checks passed!${NC}"
echo ""
echo "You can now open the project in VS Code and GitHub Copilot will use go-zero context!"
echo ""
echo " cd $(pwd)/userapidemo"
echo " code ."
EOF
chmod +x verify-copilot.sh
echo ""
echo -e "${BLUE}================================================${NC}"
echo -e "${GREEN}✓ Demo project setup completed!${NC}"
echo -e "${BLUE}================================================${NC}"
echo ""
echo "Project location: $DEMO_DIR/$PROJECT_NAME"
echo ""
echo "Next steps:"
echo ""
echo "1. Verify configuration:"
echo -e " ${YELLOW}cd $DEMO_DIR && ./verify-copilot.sh${NC}"
echo ""
echo "2. Open project in VS Code:"
echo -e " ${YELLOW}cd $DEMO_DIR/$PROJECT_NAME${NC}"
echo -e " ${YELLOW}code .${NC}"
echo ""
echo "3. Test GitHub Copilot:"
echo " - Open internal/logic/createuserlogic.go"
echo " - Try implementing the CreateUser method"
echo " - Copilot will provide go-zero compliant suggestions based on ai-context"
echo ""
echo "4. Run the service:"
echo -e " ${YELLOW}go run userapidemo.go -f etc/user-api.yaml${NC}"
echo ""
Examples
English | 简体中文
This directory contains example scripts and demo code for zero-skills tutorials.
demo-project/
A complete GitHub Copilot + go-zero demo project. Automatically creates a go-zero project configured with ai-context to verify AI-assisted development.
完整的 GitHub Copilot + go-zero 演示项目。自动创建配置了 ai-context 的 go-zero 项目,用于验证 AI 辅助开发效果。
Quick start / 快速开始:
cd demo-project
./setup-demo.shDocumentation / 详细文档: demo-project/README.md
Features / 包含功能:
- ✅ Auto-configure GitHub Copilot (ai-context submodule) / 自动配置 GitHub Copilot(ai-context submodule)
- ✅ Create a complete go-zero REST API project / 创建完整的 go-zero REST API 项目
- ✅ Multiple test scenarios for verifying Copilot results / 提供多个测试场景验证 Copilot 效果
- ✅ Verification script to confirm correct setup / 包含验证脚本确认配置正确
verify-tutorial.sh
Validates the completeness and correctness of AI tool ecosystem configuration tutorials.
验证 AI 工具生态配置教程的完整性和正确性。
Features / 功能:
- ✅ Test GitHub Copilot configuration (submodule + symlink) / 测试 GitHub Copilot 配置(submodule + 符号链接)
- ✅ Test Cursor configuration (.cursorrules) / 测试 Cursor 配置(.cursorrules)
- ✅ Test Windsurf configuration (.windsurfrules) / 测试 Windsurf 配置(.windsurfrules)
- ✅ Test submodule update functionality / 测试 submodule 更新功能
- ✅ Verify ai-context content structure / 验证 ai-context 内容结构
- ✅ Verify zero-skills pattern references / 验证 zero-skills 模式引用
Usage / 使用方法:
# Run the verification script / 运行验证脚本
./examples/verify-tutorial.sh
# Or with an absolute path / 或者使用绝对路径
bash /path/to/zero-skills/examples/verify-tutorial.shTest coverage / 测试内容:
1. GitHub Copilot configuration test / GitHub Copilot 配置测试
- Add ai-context as submodule to
.github/ai-context/ 添加 ai-context 为 submodule 到.github/ai-context - Create symlink to
.github/copilot-instructions.md/ 创建符号链接到.github/copilot-instructions.md - Verify file content includes go-zero related content / 验证文件内容包含 go-zero 相关内容
2. Cursor configuration test / Cursor 配置测试
- Add ai-context as submodule to
.cursorrules/ 添加 ai-context 为 submodule 到.cursorrules - Verify directory structure and markdown files / 验证目录结构和 markdown 文件
- Confirm content loads correctly / 确认内容正确加载
3. Windsurf configuration test / Windsurf 配置测试
- Add ai-context as submodule to
.windsurfrules/ 添加 ai-context 为 submodule 到.windsurfrules - Verify directory structure and markdown files / 验证目录结构和 markdown 文件
- Confirm content loads correctly / 确认内容正确加载
4. Submodule update test / Submodule 更新测试
- Run
git submodule update --remote/ 执行git submodule update --remote - Verify update works correctly / 验证更新功能正常工作
5. Content structure validation / 内容结构验证
- Check ai-context includes required sections / 检查 ai-context 包含必需的章节
- Confirm documentation structure is complete / 确认文档结构完整
6. zero-skills reference validation / zero-skills 引用验证
- Verify all pattern document links exist / 验证所有模式文档链接存在
- Confirm references correctly point to zero-skills repository / 确认引用正确指向 zero-skills 仓库
Sample output / 输出示例:
================================================
零技能 AI 工具生态配置验证脚本
Zero-Skills AI Ecosystem Tutorial Verification
================================================
✓ 创建测试目录: /tmp/zero-skills-demo-12345
=== 测试 1: GitHub Copilot 配置 ===
✓ PASS: GitHub Copilot 配置
Submodule 添加成功,符号链接创建成功,内容验证通过
[更多测试输出...]
================================================
测试总结 / Test Summary
================================================
总测试数 / Total Tests: 6
通过 / Passed: 6
失败 / Failed: 0
✓ 所有测试通过!教程验证成功!Cleanup / 清理测试目录:
The script creates a temporary directory under /tmp. Delete it after testing:
脚本会在 /tmp 下创建临时测试目录,测试完成后可以删除:
# 脚本会输出清理命令,例如:
rm -rf /tmp/zero-skills-demo-12345Notes / 注意事项:
- Requires a Git environment / 脚本需要 Git 环境
- Requires network access to clone ai-context / 需要网络连接以克隆 ai-context 仓库
- Runs directly on macOS/Linux / macOS/Linux 系统可直接运行
- Windows users should run in Git Bash or WSL / Windows 用户建议在 Git Bash 或 WSL 中运行
Contributing / 贡献
Contributions of new example scripts are welcome! Please ensure:
欢迎添加更多示例脚本!请确保:
1. Scripts include clear comments / 脚本包含清晰的注释 2. Usage instructions are provided / 提供使用说明 3. Error handling is included / 包含错误处理 4. Functionality is verified / 验证功能正确性
#!/bin/bash
# Demo script to verify AI ecosystem tutorial configurations
set -e # Exit on error
DEMO_DIR="/tmp/zero-skills-demo-$$"
RESULTS_FILE="$DEMO_DIR/verification-results.txt"
# Color definitions
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo "================================================"
echo "Zero-Skills AI Ecosystem Tutorial Verification"
echo "================================================"
echo ""
# Create temporary directory
mkdir -p "$DEMO_DIR"
echo "✓ Created test directory: $DEMO_DIR"
echo ""
# Log result function
log_result() {
local test_name=$1
local status=$2
local message=$3
if [ "$status" = "PASS" ]; then
echo -e "${GREEN}✓ PASS${NC}: $test_name"
else
echo -e "${RED}✗ FAIL${NC}: $test_name"
fi
echo " $message"
echo "$test_name: $status - $message" >> "$RESULTS_FILE"
echo ""
}
# Test 1: GitHub Copilot Configuration
test_github_copilot() {
echo "=== Test 1: GitHub Copilot Configuration ==="
local test_dir="$DEMO_DIR/copilot-test"
mkdir -p "$test_dir"
cd "$test_dir"
# Initialize git repository
git init -q
# Add ai-context as submodule
if git submodule add -q https://github.com/zeromicro/ai-context.git .github/ai-context 2>/dev/null; then
# Create symlink
mkdir -p .github
ln -s ai-context/00-instructions.md .github/copilot-instructions.md
# Verify file exists
if [ -L ".github/copilot-instructions.md" ] && [ -e ".github/copilot-instructions.md" ]; then
# Verify content
if grep -q "go-zero" .github/copilot-instructions.md; then
log_result "GitHub Copilot Configuration" "PASS" "Submodule added, symlink created, content verified"
return 0
else
log_result "GitHub Copilot Configuration" "FAIL" "File content does not contain go-zero related content"
return 1
fi
else
log_result "GitHub Copilot Configuration" "FAIL" "Symlink creation failed or file does not exist"
return 1
fi
else
log_result "GitHub Copilot Configuration" "FAIL" "Submodule add failed"
return 1
fi
}
# Test 2: Cursor Configuration
test_cursor() {
echo "=== Test 2: Cursor Configuration ==="
local test_dir="$DEMO_DIR/cursor-test"
mkdir -p "$test_dir"
cd "$test_dir"
# Initialize git repository
git init -q
# Add ai-context as submodule
if git submodule add -q https://github.com/zeromicro/ai-context.git .cursorrules 2>/dev/null; then
# Verify directory and file exist
if [ -d ".cursorrules" ] && [ -f ".cursorrules/00-instructions.md" ]; then
# Verify content
if grep -q "go-zero" .cursorrules/00-instructions.md; then
# Count .md files
md_count=$(find .cursorrules -name "*.md" -type f | wc -l)
log_result "Cursor Configuration" "PASS" "Submodule added, found $md_count .md files"
return 0
else
log_result "Cursor Configuration" "FAIL" "File content does not contain go-zero related content"
return 1
fi
else
log_result "Cursor Configuration" "FAIL" ".cursorrules directory or file does not exist"
return 1
fi
else
log_result "Cursor Configuration" "FAIL" "Submodule add failed"
return 1
fi
}
# Test 3: Windsurf Configuration
test_windsurf() {
echo "=== Test 3: Windsurf Configuration ==="
local test_dir="$DEMO_DIR/windsurf-test"
mkdir -p "$test_dir"
cd "$test_dir"
# Initialize git repository
git init -q
# Add ai-context as submodule
if git submodule add -q https://github.com/zeromicro/ai-context.git .windsurfrules 2>/dev/null; then
# Verify directory and file exist
if [ -d ".windsurfrules" ] && [ -f ".windsurfrules/00-instructions.md" ]; then
# Verify content
if grep -q "go-zero" .windsurfrules/00-instructions.md; then
# Count .md files
md_count=$(find .windsurfrules -name "*.md" -type f | wc -l)
log_result "Windsurf Configuration" "PASS" "Submodule added, found $md_count .md files"
return 0
else
log_result "Windsurf Configuration" "FAIL" "File content does not contain go-zero related content"
return 1
fi
else
log_result "Windsurf Configuration" "FAIL" ".windsurfrules directory or file does not exist"
return 1
fi
else
log_result "Windsurf Configuration" "FAIL" "Submodule add failed"
return 1
fi
}
# Test 4: Submodule Update
test_submodule_update() {
echo "=== Test 4: Submodule Update ==="
local test_dir="$DEMO_DIR/update-test"
mkdir -p "$test_dir"
cd "$test_dir"
# Initialize git repository and add submodule
git init -q
git submodule add -q https://github.com/zeromicro/ai-context.git .github/ai-context 2>/dev/null
# Record initial commit hash
cd .github/ai-context
initial_commit=$(git rev-parse HEAD)
cd ../..
# Try to update
if git submodule update --remote .github/ai-context 2>/dev/null; then
cd .github/ai-context
updated_commit=$(git rev-parse HEAD)
cd ../..
log_result "Submodule Update" "PASS" "Update successful (commit: ${updated_commit:0:8})"
return 0
else
log_result "Submodule Update" "FAIL" "Submodule update failed"
return 1
fi
}
# Test 5: Verify ai-context Content Structure
test_content_structure() {
echo "=== Test 5: Verify ai-context Content Structure ==="
local test_dir="$DEMO_DIR/content-test"
mkdir -p "$test_dir"
cd "$test_dir"
# Initialize and clone
git init -q
git submodule add -q https://github.com/zeromicro/ai-context.git .ai-context 2>/dev/null
# Verify key content
local required_sections=(
"Decision Tree"
"File Priority"
"Patterns"
"zero-skills"
)
local missing_sections=()
for section in "${required_sections[@]}"; do
if ! grep -q "$section" .ai-context/00-instructions.md; then
missing_sections+=("$section")
fi
done
if [ ${#missing_sections[@]} -eq 0 ]; then
log_result "Content Structure" "PASS" "All required sections exist"
return 0
else
log_result "Content Structure" "FAIL" "Missing sections: ${missing_sections[*]}"
return 1
fi
}
# Test 6: Verify zero-skills References
test_zero_skills_references() {
echo "=== Test 6: Verify zero-skills References ==="
local test_dir="$DEMO_DIR/reference-test"
mkdir -p "$test_dir"
cd "$test_dir"
# Initialize and clone
git init -q
git submodule add -q https://github.com/zeromicro/ai-context.git .ai-context 2>/dev/null
# Verify zero-skills links
local required_links=(
"rest-api-patterns.md"
"rpc-patterns.md"
"database-patterns.md"
"resilience-patterns.md"
)
local missing_links=()
for link in "${required_links[@]}"; do
if ! grep -q "$link" .ai-context/00-instructions.md; then
missing_links+=("$link")
fi
done
if [ ${#missing_links[@]} -eq 0 ]; then
log_result "zero-skills References" "PASS" "All pattern document references exist"
return 0
else
log_result "zero-skills References" "FAIL" "Missing references: ${missing_links[*]}"
return 1
fi
}
# Run all tests
main() {
echo "Running tests..."
echo ""
local total=0
local passed=0
# Run tests
test_github_copilot && ((passed++)) || true
((total++))
test_cursor && ((passed++)) || true
((total++))
test_windsurf && ((passed++)) || true
((total++))
test_submodule_update && ((passed++)) || true
((total++))
test_content_structure && ((passed++)) || true
((total++))
test_zero_skills_references && ((passed++)) || true
((total++))
# Output summary
echo "================================================"
echo "Test Summary"
echo "================================================"
echo "Total Tests: $total"
echo -e "Passed: ${GREEN}$passed${NC}"
echo -e "Failed: ${RED}$((total - passed))${NC}"
echo ""
if [ $passed -eq $total ]; then
echo -e "${GREEN}✓ All tests passed! Tutorial verified successfully!${NC}"
else
echo -e "${YELLOW}⚠ Some tests failed, please check the configuration${NC}"
fi
echo ""
echo "Detailed results saved to: $RESULTS_FILE"
echo "Test directory: $DEMO_DIR"
echo ""
# Auto-cleanup temporary directory
echo "Cleaning up temporary test directory..."
if rm -rf "$DEMO_DIR" 2>/dev/null; then
echo -e "${GREEN}✓ Temporary directory cleaned up${NC}"
else
echo -e "${YELLOW}⚠ Auto-cleanup failed, please delete manually:${NC} rm -rf $DEMO_DIR"
fi
echo ""
}
# Execute main function
main
Using zero-skills with Claude Code
This guide explains how to use zero-skills effectively with Claude Code, leveraging its advanced skills capabilities.
Table of Contents
- Quick Reference
- Installation
- Basic Usage
- Advanced Features
- Skill Pattern Examples
- Example Workflows
- Troubleshooting
- Best Practices
---
Quick Reference
Commands
| Command | Description |
|---|---|
/zero-skills | Load skill for go-zero help |
/zero-skills [query] | Load skill with specific question |
| Ask "What skills are available?" | Check loaded skills |
Key Principles
Always Do:
- Handler → Logic → Model separation
- Use
httpx.Error()for HTTP errors - Load config with
conf.MustLoad - Pass
ctxthrough all layers - Generate code with
goctl
Never Do:
- Put business logic in handlers
- Hard-code configuration
- Skip error handling
- Bypass ServiceContext injection
Pattern Guides
| Guide | When to Use |
|---|---|
| rest-api-patterns.md | REST APIs, handlers, middleware |
| rpc-patterns.md | gRPC services, service discovery |
| database-patterns.md | SQL, MongoDB, Redis, caching |
| resilience-patterns.md | Circuit breakers, rate limiting |
| common-issues.md | Debugging errors |
| overview.md | Production hardening |
Integration with Other Tools
| Tool | Purpose | Command/Usage |
|---|---|---|
| goctl | Code generation | goctl api go, goctl model, etc. |
| ai-context | Quick workflows | GitHub Copilot integration |
| zero-skills | Knowledge base | /zero-skills or automatic |
---
Installation
Option 1: Project-Level (Recommended for go-zero projects)
Add zero-skills to your project for automatic discovery:
cd your-gozero-project/
# Create skills directory
mkdir -p .claude/skills
# Clone zero-skills
git clone https://github.com/zeromicro/zero-skills.git .claude/skills/zero-skillsClaude Code automatically discovers skills in .claude/skills/ directories.
Option 2: Personal-Level (Available across all projects)
Install to your personal skills directory to use with any go-zero project:
# Create personal skills directory
mkdir -p ~/.claude/skills
# Clone zero-skills
git clone https://github.com/zeromicro/zero-skills.git ~/.claude/skills/zero-skillsOption 3: Enterprise-Level (For organizations)
Distribute via managed settings (requires Claude for Enterprise): 1. Add skill to your organization's managed settings 2. All team members get the skill automatically 3. See Claude Code IAM documentation
Basic Usage
Automatic Invocation
Claude automatically loads the skill when you:
- Open or edit
.apifiles (REST API definitions) - Open or edit
.protofiles (gRPC definitions) - Work with
go.modthat includesgithub.com/zeromicro/go-zero - Ask questions about go-zero
Example:
You: How do I create a REST API with go-zero?Claude loads zero-skills and provides detailed guidance from references/rest-api-patterns.md.
Manual Invocation
Invoke directly with /zero-skills:
/zero-skillsOr with arguments:
/zero-skills Create a user management API with authentication
/zero-skills How do I implement rate limiting?
/zero-skills Explain the three-layer architectureCheck Skill Availability
You: What skills are available?Claude lists all loaded skills. Look for zero-skills in the output.
Advanced Features
Dynamic Context Injection
Skills can execute shell commands to gather live project data using !command`` syntax.
Example: Find existing services
---
name: check-services
---
Current services in this project:
- API services: !`find . -name "*.api" -type f`
- RPC services: !`find . -name "*.proto" -type f`
- Config files: !`find . -name "*-api.yaml" -o -name "*-rpc.yaml"`The commands execute before Claude sees the prompt, injecting actual file paths.
See skill-patterns/analyze-project.md for a complete example.
Subagent Workflows
Use context: fork to run skills in isolated subagent contexts:
Explore Agent (Read-Only Analysis)
---
name: analyze-gozero-project
context: fork
agent: Explore
---
Analyze the go-zero project structure and identify issues...Benefits:
- Isolated context (no conversation history leakage)
- Read-only tools prevent accidental modifications
- Focused analysis without distractions
See skill-patterns/analyze-project.md for details.
Plan Agent (Architecture Design)
---
name: plan-microservices
context: fork
agent: Plan
---
Plan a microservices architecture for: $ARGUMENTSBenefits:
- Optimized for planning and design
- No code execution (prevents premature implementation)
- Fresh perspective on architecture
See skill-patterns/plan-architecture.md for details.
Tool Restrictions
Control which tools Claude can use with allowed-tools:
---
name: safe-gozero-review
allowed-tools:
- Read
- Grep
- Glob
---
Review go-zero code without making changes...Available tool categories:
Read: Read filesGrep: Search file contentsGlob: Find files by patternBash(goctl *): Run goctl commands onlyWrite: Create/modify files
Argument Passing
Skills can accept arguments for customization:
---
name: generate-api-service
argument-hint: [service-name] [port]
---
Generate service: $0 on port $1Usage:
/generate-api-service user 8080
/generate-api-service order 8081Access arguments:
$0or$ARGUMENTS[0]: First argument$1or$ARGUMENTS[1]: Second argument$ARGUMENTS: All arguments combined${CLAUDE_SESSION_ID}: Current session ID
See skill-patterns/generate-service.md for details.
Skill Pattern Examples
See skill-patterns/ for advanced skill patterns:
- [analyze-project.md](../skill-patterns/analyze-project.md) - Explore agent with dynamic context
- [generate-service.md](../skill-patterns/generate-service.md) - Argument passing patterns
- [plan-architecture.md](../skill-patterns/plan-architecture.md) - Plan agent for design
- [README.md](../skill-patterns/README.md) - Full guide with best practices
Example Workflows
Workflow 1: Building a New REST API
Step 1: Manual invocation for planning
/zero-skills Create a user management REST API with CRUD operationsClaude: 1. Loads references/rest-api-patterns.md 2. Explains the .api file structure 3. Shows example definitions 4. Guides you through Handler → Logic → Model setup
Step 2: Implement with guidance
You: How do I handle authentication in middleware?Claude references references/rest-api-patterns.md and provides examples.
Step 3: Troubleshoot issues
You: I'm getting "http: named cookie not present" errorClaude loads troubleshooting/common-issues.md and diagnoses the problem.
Workflow 2: Analyzing an Existing Project
Use the analyze-project skill (in subagent):
You: Analyze this go-zero project for issuesClaude (automatically or if you have the analyze skill): 1. Forks to Explore agent 2. Finds all .api and .proto files 3. Checks architecture compliance 4. Identifies anti-patterns 5. Returns summary to main conversation
See skill-patterns/analyze-project.md for this skill template.
Workflow 3: Planning Microservices Architecture
Use the plan-microservices skill:
/plan-microservices e-commerce platform with user, product, cart, and order servicesClaude (using Plan agent): 1. Designs service boundaries 2. Specifies API vs RPC communication 3. Plans data storage strategy 4. Provides .api and .proto examples 5. Suggests implementation order
See skill-patterns/plan-architecture.md for this skill template.
Workflow 4: Using goctl in Terminal
Claude runs goctl commands directly in the terminal:
You: Create a user API service with database operationsClaude: 1. Uses zero-skills for patterns and structure 2. Writes the .api spec file 3. Runs goctl api go -api user.api -dir . --style go_zero in terminal 4. Runs goctl model mysql datasource ... for database models 5. Runs go mod tidy && go build ./... to verify 6. Implements business logic in internal/logic/
See references/goctl-commands.md for the complete command reference.
Troubleshooting
Skill Not Loading
Problem: Claude doesn't seem to have go-zero knowledge.
Solutions: 1. Check if skill is available: What skills are available? 2. Verify installation:
ls -la ~/.claude/skills/zero-skills/SKILL.md
# or
ls -la .claude/skills/zero-skills/SKILL.md3. Manually invoke: /zero-skills 4. Check frontmatter in SKILL.md (must have valid YAML)
Skill Not Triggering Automatically
Problem: Have to manually invoke with /zero-skills every time.
Solutions: 1. Improve the description in SKILL.md to match your queries 2. Use go-zero specific keywords: "api", "rpc", "goctl", "handler", "logic" 3. Work with .api or .proto files (triggers automatic loading)
Commands in Skill Not Executing
Problem: Dynamic context (!command``) not working.
Possible causes: 1. Commands execute before Claude sees them (this is by design) 2. Shell command errors are silent - check command syntax 3. Working directory might not be what you expect
Debug:
Current directory: !`pwd`
Go version: !`go version`
Files: !`ls -la`Subagent Not Working
Problem: context: fork skill doesn't run in isolation.
Solutions: 1. Verify context: fork in frontmatter 2. Specify agent type: agent: Explore or agent: Plan 3. Check allowed-tools (subagents need explicit tool permissions)
Skill Triggers Too Often
Problem: zero-skills loads even when not working with go-zero.
Solutions: 1. Make description more specific in SKILL.md 2. Add disable-model-invocation: true to prevent automatic loading 3. Only invoke manually with /zero-skills when needed
Quick Troubleshooting Table
| Problem | Solution |
|---|---|
| Skill not loading | Check: What skills are available? |
| Not auto-triggering | Invoke manually: /zero-skills |
| Need specific pattern | Ask: "Show me REST API middleware patterns" |
| Want to analyze project | Say: "Analyze this go-zero project" |
Best Practices
1. Use Specific Invocations
Instead of:
/zero-skills Help meBe specific:
/zero-skills Implement rate limiting for my API service2. Leverage Supporting Files
Don't load everything. Reference specific guides:
You: How do I implement database transactions?Claude loads just references/database-patterns.md, not the entire skill.
3. Combine Knowledge with Execution
Use zero-skills for knowledge, goctl for execution:
- zero-skills: "What pattern should I use?"
- goctl: "Generate the code" (AI runs in terminal)
4. Create Custom Skills
Build project-specific skills in .claude/skills/ that extend zero-skills:
.claude/
└── skills/
├── zero-skills/ # Base knowledge
└── myproject-gozero/ # Project-specific
└── SKILL.mdExample custom skill:
---
name: myproject-gozero
description: Project-specific go-zero patterns for MyProject
---
This project uses zero-skills patterns with these customizations:
- All APIs use JWT authentication (see internal/middleware/auth.go)
- Database models use soft deletes
- Service discovery via Kubernetes (not etcd)
For general patterns, see zero-skills. This skill covers project-specific overrides.5. Use Subagents for Complex Tasks
Create skills with context: fork for:
- Analysis: Use Explore agent for codebase review
- Planning: Use Plan agent for architecture design
- Isolation: Keep experimental or risky operations separate
Learning Path
1. New to go-zero? → Official Quick Start 2. Building APIs? → references/rest-api-patterns.md 3. Adding database? → references/database-patterns.md 4. Production ready? → best-practices/overview.md
Additional Resources
- Official docs: code.claude.com/docs/en/skills
- Agent Skills spec: agentskills.io
- go-zero docs: go-zero.dev
- goctl commands: references/goctl-commands.md
- ai-context: github.com/zeromicro/ai-context
Feedback and Contributions
Found an issue or want to improve zero-skills?
- Open an issue: github.com/zeromicro/zero-skills/issues
- Submit a PR: github.com/zeromicro/zero-skills/pulls
- Join the community: See main go-zero repository
---
Tips:
- Be specific: "Create a user API with authentication" > "Help me"
- Reference files: ".api files" or "REST API" trigger automatic loading
- Use goctl: AI runs goctl commands directly in the terminal for code generation
- Create custom skills: Extend for project-specific patterns
- Check examples: See skill-patterns/ for advanced usage
Need help? Just ask Claude: "How do I [task] with go-zero?"
Using zero-skills with Codex
This guide explains how to use zero-skills with OpenAI Codex, the AI coding agent from OpenAI.
Installation
Step 1: Clone zero-skills
cd your-gozero-project/
# Clone to a local directory
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skillsStep 2: Create AGENTS.md
Create AGENTS.md in your project root:
# go-zero Development Instructions
You are an expert in go-zero microservices framework development.
## Architecture
Follow the three-layer architecture strictly:
- **Handler**: HTTP routing and request/response handling only
- **Logic**: All business logic goes here, injected via ServiceContext
- **Model**: Data access and database operations, generated by goctl
## Code Patterns
### REST API Logicfunc (l UserLogic) GetUser(req types.GetUserReq) (*types.GetUserResp, error) { user, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id) if err != nil { return nil, err } return &types.GetUserResp{ Id: user.Id, Name: user.Name, }, nil }
### Error Handling
- Use `httpx.Error(w, err)` for HTTP errors
- Use `httpx.OkJson(w, resp)` for success responses
- Never use `fmt.Fprintf()` or `w.Write()` directly
### Configuration
- Load with `conf.MustLoad(&c, *configFile)`
- Never hard-code ports, hosts, or credentials
- Use environment-specific YAML files
### Context
- Always pass `ctx context.Context` through all layers
- Use context for tracing, cancellation, and timeouts
## Code Generation Commands
Generate API service code
goctl api go -api user.api -dir .
Generate RPC service code
goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.
Generate model from database
goctl model mysql datasource -url="user:pass@tcp(localhost:3306)/db" -table="users" -dir="./model"
## Key Rules
1. Never put business logic in handlers
2. Always use ServiceContext for dependency injection
3. Always pass ctx through all layers
4. Use goctl for code generation, never hand-write boilerplate
5. API definitions go in `.api` files; RPC definitions go in `.proto` files
## Pattern References
Detailed patterns are in `.ai-context/zero-skills/`:
- REST APIs: `references/rest-api-patterns.md`
- RPC services: `references/rpc-patterns.md`
- Database: `references/database-patterns.md`
- Resilience: `references/resilience-patterns.md`
- Troubleshooting: `troubleshooting/common-issues.md`Usage
Running Codex
Run Codex from your project directory:
codex "Create a user management REST API with go-zero including CRUD operations"Codex will read AGENTS.md automatically and apply go-zero patterns to all generated code.
Reference Pattern Files
For detailed patterns, tell Codex to read the relevant file:
Read .ai-context/zero-skills/references/rest-api-patterns.md and help me implement a user APIExample Tasks
Creating a REST API:
Create a user management REST API with CRUD operations following go-zero patternsAdding RPC service:
Add a gRPC user service following the go-zero rpc patterns in .ai-context/zero-skills/references/rpc-patterns.mdDatabase integration:
Read .ai-context/zero-skills/references/database-patterns.md and add MySQL support with caching to my user serviceTroubleshooting:
Read .ai-context/zero-skills/troubleshooting/common-issues.md and help me fix this error: ...Example Workflows
Creating a New Service
1. Define the API file:
Create a user.api file for a user management service with login, register, and profile endpoints2. Generate code:
goctl api go -api user.api -dir .3. Implement logic:
Implement the business logic for all user handlers following go-zero patternsAdding Database Support
1. Generate the model:
goctl model mysql datasource -url="user:pass@tcp(localhost:3306)/db" -table="users" -dir="./model"2. Wire it up:
Add the user model to ServiceContext and implement data access in the logic layerTips
Keep AGENTS.md Focused
Codex reads AGENTS.md for every task. Keep it concise:
- Core principles only
- Short code examples
- Reference external files for detailed patterns
Multi-file Tasks
Codex handles multi-file changes well. Describe the full feature:
Add JWT authentication to all protected API routes, following go-zero middleware patternsCombine with ai-context
For a richer context setup, use ai-context alongside zero-skills:
git clone https://github.com/zeromicro/ai-context.git .ai-context/ai-contextThen reference both in AGENTS.md:
Follow workflows from .ai-context/ai-context/
For detailed go-zero patterns, see .ai-context/zero-skills/Limitations
Compared to Claude Code, Codex:
- No native skills support (YAML frontmatter not used)
- No automatic skill loading by file type
- No subagent workflows
- Manual file references needed for detailed patterns
Troubleshooting
AGENTS.md Not Applied
Problem: Codex doesn't follow go-zero patterns.
Solutions: 1. Ensure AGENTS.md exists in the project root where you run codex 2. Check that the file is valid Markdown 3. Reference pattern files explicitly in your prompt
Context Too Large
Problem: Instructions are too long and patterns are ignored.
Solutions: 1. Keep AGENTS.md under 500 lines 2. Move detailed patterns to separate files in .ai-context/zero-skills/ 3. Reference them on demand in prompts
Using zero-skills with GitHub Copilot
This guide explains how to use zero-skills with GitHub Copilot in VS Code.
Installation
Step 1: Clone zero-skills
cd your-gozero-project/
# Clone to a local directory
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skillsStep 2: Create Copilot Instructions
Create .github/copilot-instructions.md in your project:
# go-zero Development Instructions
You are an expert in go-zero microservices framework development.
## Architecture
Follow the three-layer architecture strictly:
- **Handler**: HTTP routing and request/response handling only
- **Logic**: All business logic goes here
- **Model**: Data access and database operations
## Code Patterns
### REST API Handlerfunc (l UserLogic) GetUser(req types.GetUserReq) (*types.GetUserResp, error) { user, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id) if err != nil { return nil, err } return &types.GetUserResp{ Id: user.Id, Name: user.Name, }, nil }
### Error Handling
- Use `httpx.Error(w, err)` for errors
- Use `httpx.OkJson(w, resp)` for success
- Never use `fmt.Fprintf()` directly
### Configuration
- Use `conf.MustLoad(&c, *configFile)`
- Never hard-code values
## Commands
Generate API
goctl api go -api user.api -dir .
Generate model
goctl model mysql datasource -url="..." -table="users" -dir="./model"
## Key Rules
1. Never put business logic in handlers
2. Always use ServiceContext for dependencies
3. Always pass ctx through all layers
4. Use goctl for code generationUsage
Inline Suggestions
Copilot provides inline suggestions as you type. With the instructions file, it will follow go-zero patterns.
Copilot Chat
Use Copilot Chat for more complex questions:
How do I add middleware to my go-zero API?Reference Pattern Files
For detailed patterns, ask Copilot to read files:
@workspace Read .ai-context/zero-skills/references/rest-api-patterns.md and help me create a user APIExample Workflows
Creating a New API
1. Define the API file:
Help me create a user.api file for a user management service2. Generate code:
goctl api go -api user.api -dir .3. Implement logic:
Help me implement the GetUser logic following go-zero patternsAdding Database Support
1. Ask for model generation:
What goctl command should I use to generate a model for the users table?2. Implement data access:
Help me add the user model to ServiceContextTroubleshooting
I'm getting "http: named cookie not present" error in my go-zero APITips
Keep Instructions Concise
GitHub Copilot has token limits. Keep .github/copilot-instructions.md focused:
- Key principles only
- Short code examples
- Reference external files for details
Use @workspace
Reference your entire workspace:
@workspace What go-zero services do we have?Combine with ai-context
For minimal instructions, use ai-context:
# .github/copilot-instructions.md
Follow go-zero patterns from .ai-context/ai-context/
For detailed patterns, see .ai-context/zero-skills/references/Open Pattern Files
Keep pattern files open in editor tabs. Copilot uses open files as context.
Limitations
Compared to Claude Code, GitHub Copilot:
- No native skills support
- Limited instruction file size
- No automatic pattern loading
- No subagent workflows
- Primarily inline suggestions
Workspace Settings
Optionally configure in .vscode/settings.json:
{
"github.copilot.chat.codeGeneration.instructions": [
{
"text": "Follow go-zero three-layer architecture: Handler → Logic → Model"
},
{
"text": "Use httpx.Error() for errors and httpx.OkJson() for success responses"
},
{
"text": "Always use goctl for code generation"
}
]
}Troubleshooting
Instructions Not Applied
Problem: Copilot ignores go-zero patterns.
Solutions: 1. Verify .github/copilot-instructions.md exists 2. Restart VS Code 3. Open pattern files in editor tabs 4. Use explicit @workspace references
Suggestions Are Generic
Problem: Copilot gives generic Go code, not go-zero specific.
Solutions: 1. Add more go-zero examples to instructions 2. Reference pattern files explicitly 3. Keep go-zero files open in editor
Context Limit Reached
Problem: Instructions file is too large.
Solutions: 1. Keep instructions under 200 lines 2. Use ai-context for concise rules 3. Reference pattern files instead of inlining
Additional Resources
- GitHub Copilot Documentation
- Copilot Chat
- go-zero Official Docs
- zero-skills Pattern Guides
Using zero-skills with Cursor
This guide explains how to use zero-skills with Cursor, the AI-first code editor.
Installation
Step 1: Clone zero-skills
cd your-gozero-project/
# Clone to a local directory
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skillsStep 2: Create .cursorrules
Create .cursorrules in your project root:
# go-zero Development Rules
You are an expert in go-zero microservices framework development.
## Key Principles
Follow these go-zero patterns strictly:
### Architecture
- **Three-layer separation**: Handler (HTTP) → Logic (business) → Model (data)
- Never put business logic in handlers
- Always use ServiceContext for dependency injection
### Code Generation
- Use `goctl` for code generation, never hand-write boilerplate
- API definitions go in `.api` files
- RPC definitions go in `.proto` files
### Error Handling
- Use `httpx.Error(w, err)` for HTTP errors
- Use `httpx.OkJson(w, resp)` for success responses
- Never use `fmt.Fprintf()` or `w.Write()` directly
### Configuration
- Load config with `conf.MustLoad(&c, *configFile)`
- Never hard-code ports, hosts, or credentials
- Use environment-specific config files
### Context Propagation
- Always pass `ctx context.Context` through all layers
- Use context for tracing, cancellation, and timeouts
## Pattern References
When I need detailed patterns, I'll reference these files:
- REST APIs: .ai-context/zero-skills/references/rest-api-patterns.md
- RPC services: .ai-context/zero-skills/references/rpc-patterns.md
- Database: .ai-context/zero-skills/references/database-patterns.md
- Resilience: .ai-context/zero-skills/references/resilience-patterns.md
- Troubleshooting: .ai-context/zero-skills/troubleshooting/common-issues.md
## Common Commands
Generate API code
goctl api go -api user.api -dir .
Generate RPC code
goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.
Generate model from database
goctl model mysql datasource -url="user:pass@tcp(localhost:3306)/db" -table="users" -dir="./model"
Usage
Automatic Context
Cursor will apply these rules to all conversations in your project.
Reference Pattern Files
When you need detailed patterns, ask Cursor to read the specific file:
Read .ai-context/zero-skills/references/rest-api-patterns.md and help me implement a user APIExample Conversations
Creating a REST API:
Create a user management REST API with CRUD operations following go-zero patternsAdding middleware:
Help me add JWT authentication middleware to my go-zero APIDatabase integration:
Read the database patterns and help me add MySQL support to my user serviceTips
Keep Rules Concise
Cursor has context limits. Keep .cursorrules focused on key principles and reference pattern files for details.
Use @-mentions
Reference files directly in chat:
@.ai-context/zero-skills/references/database-patterns.md help me implement cachingCombine with ai-context
For even more concise rules, use ai-context:
git clone https://github.com/zeromicro/ai-context.git .ai-context/ai-contextThen reference it in .cursorrules:
Follow workflows from .ai-context/ai-context/
For detailed patterns, see .ai-context/zero-skills/Limitations
Compared to Claude Code, Cursor:
- No native skills support (YAML frontmatter ignored)
- No automatic loading by file type
- No subagent workflows
- No dynamic context injection
- Manual file references needed
Troubleshooting
Rules Not Applied
Problem: Cursor doesn't seem to follow go-zero patterns.
Solutions: 1. Check .cursorrules exists in project root 2. Restart Cursor after creating rules 3. Reference pattern files explicitly in chat
Context Too Large
Problem: Rules file is too long.
Solutions: 1. Keep .cursorrules under 500 lines 2. Move detailed patterns to separate files 3. Reference files with @-mentions
Outdated Patterns
Problem: Suggestions don't match latest go-zero.
Solutions: 1. Update zero-skills: cd .ai-context/zero-skills && git pull 2. Check go-zero version compatibility
Additional Resources
- Cursor Documentation
- go-zero Official Docs
- zero-skills Pattern Guides
Getting Started with zero-skills
This directory contains guides for using zero-skills with different AI coding tools.
Choose Your Tool
| Tool | Guide | Skills Support | Best For |
|---|---|---|---|
| Claude Code | claude-code-guide.md | Native | Full features, subagents, dynamic context |
| Cursor | cursor-guide.md | Via rules | IDE integration, fast responses |
| GitHub Copilot | copilot-guide.md | Via instructions | VS Code users, inline suggestions |
| Windsurf | windsurf-guide.md | Via rules | IDE integration, Cascade AI |
| Codex | codex-guide.md | Via AGENTS.md | CLI-based agentic coding tasks |
Feature Comparison
| Feature | Claude Code | Cursor | Copilot | Windsurf | Codex |
|---|---|---|---|---|---|
| Native skills support | Yes | No | No | No | No |
| YAML frontmatter | Yes | No | No | No | No |
| Subagent workflows | Yes | No | No | No | No |
Dynamic context (!cmd) | Yes | No | No | No | No |
| Project rules | .claude/ | .cursorrules | .github/ | .windsurfrules | AGENTS.md |
| Auto-load by file type | Yes | Manual | Manual | Manual | Manual |
| Tool restrictions | Yes | No | No | No | No |
Quick Comparison
Claude Code (Recommended for go-zero)
Pros:
- Native Agent Skills support
- Automatic skill loading
- Subagent workflows (Explore, Plan)
- Dynamic context injection
- Tool restrictions for safety
Cons:
- Requires Claude Code CLI
- Learning curve for advanced features
Best for: Comprehensive go-zero development with full automation.
Cursor
Pros:
- Fast IDE integration
- Good context awareness
- Project-wide rules
- Popular among developers
Cons:
- No native skills support
- Manual context loading
- Rules file can get large
Best for: Developers who prefer IDE-based AI assistance.
GitHub Copilot
Pros:
- Deep VS Code integration
- Inline suggestions
- Widely adopted
- Chat interface
Cons:
- Limited instruction size
- No structured skills
- Manual context management
Best for: VS Code users who want inline go-zero suggestions.
Windsurf
Pros:
- Cascade AI for complex tasks
- Good file context
- Project rules support
Cons:
- No native skills support
- Newer tool, evolving features
Best for: Developers who like Cascade AI's approach.
Codex
Pros:
- CLI-based agentic coding
- Reads
AGENTS.mdautomatically - Good at multi-file tasks
- Backed by OpenAI models
Cons:
- No native skills support
- No automatic skill loading by file type
- Manual file references needed
Best for: Developers who prefer a CLI-based AI coding agent.
Installation Overview
All tools follow a similar pattern:
# 1. Clone zero-skills to your project
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skills
# 2. Configure your tool (see specific guide)Then configure based on your tool:
| Tool | Configuration |
|---|---|
| Claude Code | Clone to .claude/skills/zero-skills/ |
| Cursor | Reference in .cursorrules |
| Copilot | Reference in .github/copilot-instructions.md |
| Windsurf | Reference in .windsurfrules |
Key Principles (All Tools)
Regardless of which tool you use, these go-zero principles apply:
Always:
- Handler → Logic → Model separation
- Use
httpx.Error()for HTTP errors - Load config with
conf.MustLoad - Pass
ctxthrough all layers - Generate code with
goctl
Never:
- Put business logic in handlers
- Hard-code configuration
- Skip error handling
- Bypass ServiceContext injection
Additional Resources
- [SKILL.md](../SKILL.md) - Main skill entry point
- [Pattern guides](../references/) - Detailed patterns
- [go-zero docs](https://go-zero.dev) - Official documentation
- [ai-context](https://github.com/zeromicro/ai-context) - Lightweight workflow instructions
Using zero-skills with Windsurf
This guide explains how to use zero-skills with Windsurf, the AI-powered IDE by Codeium.
Installation
Step 1: Clone zero-skills
cd your-gozero-project/
# Clone to a local directory
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skillsStep 2: Create .windsurfrules
Create .windsurfrules in your project root:
# go-zero Development Rules
You are an expert in go-zero microservices framework development.
## Key Principles
### Architecture
Follow the three-layer architecture strictly:
- **Handler**: HTTP routing only, no business logic
- **Logic**: All business logic, injected via ServiceContext
- **Model**: Data access, generated by goctl
### Code Generation
- Use `goctl` for all boilerplate generation
- API definitions: `.api` files
- RPC definitions: `.proto` files
- Models: `goctl model` command
### Error Handling// Correct httpx.Error(w, err) httpx.OkJson(w, resp)
// Wrong - never do this fmt.Fprintf(w, "error: %v", err) w.Write([]byte("error"))
### Configuration
- Load: `conf.MustLoad(&c, *configFile)`
- Never hard-code ports, hosts, or credentials
- Use environment-specific YAML files
### Context
- Always pass `ctx context.Context` through all layers
- Use for tracing, cancellation, timeouts
## Pattern References
Detailed patterns are in .ai-context/zero-skills/:
- REST APIs: references/rest-api-patterns.md
- RPC: references/rpc-patterns.md
- Database: references/database-patterns.md
- Resilience: references/resilience-patterns.md
## Common Commands
API generation
goctl api go -api user.api -dir .
RPC generation
goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.
Model generation
goctl model mysql datasource -url="user:pass@tcp(localhost:3306)/db" -table="users" -dir="./model"
Usage
Cascade AI
Windsurf's Cascade AI works well with go-zero patterns. Use it for:
Creating services:
Create a user management REST API with go-zero, including CRUD operationsComplex refactoring:
Refactor this handler to follow go-zero three-layer architectureMulti-file changes:
Add JWT authentication middleware to all API routesReference Pattern Files
For detailed patterns, reference the files:
Read .ai-context/zero-skills/references/database-patterns.md and help me add Redis cachingChat Interface
Use the chat for go-zero questions:
What's the correct way to handle errors in go-zero handlers?Example Workflows
Creating a New Service
1. Plan the service:
Help me plan a user management service with go-zero, including user registration, login, and profile management2. Generate API definition:
Create the user.api file with proper types and routes3. Generate code:
goctl api go -api user.api -dir .4. Implement logic:
Help me implement the login logic with password hashingAdding Database
1. Create schema:
Help me create a MySQL schema for the users table2. Generate model:
goctl model mysql datasource -url="..." -table="users" -dir="./model"3. Wire up ServiceContext:
Show me how to add the user model to ServiceContextAdding Resilience
Read .ai-context/zero-skills/references/resilience-patterns.md and help me add rate limiting to my APITips
Use Cascade for Complex Tasks
Cascade excels at multi-file changes. Use it for:
- Adding new features across multiple files
- Refactoring to proper architecture
- Implementing cross-cutting concerns (auth, logging)
Keep Rules Focused
.windsurfrules should be concise. For detailed patterns, reference the pattern files.
Combine with ai-context
For minimal rules:
git clone https://github.com/zeromicro/ai-context.git .ai-context/ai-contextReference in .windsurfrules:
Follow go-zero workflows from .ai-context/ai-context/
Detailed patterns: .ai-context/zero-skills/references/Limitations
Compared to Claude Code, Windsurf:
- No native skills support
- No YAML frontmatter parsing
- No subagent workflows
- No dynamic context injection
- Manual file references needed
Troubleshooting
Rules Not Applied
Problem: Windsurf ignores go-zero patterns.
Solutions: 1. Check .windsurfrules in project root 2. Restart Windsurf 3. Reference files explicitly
Cascade Timeout
Problem: Complex operations time out.
Solutions: 1. Break into smaller tasks 2. Provide more specific instructions 3. Reference pattern files for context
Generic Suggestions
Problem: Suggestions aren't go-zero specific.
Solutions: 1. Add more examples to .windsurfrules 2. Reference pattern files explicitly 3. Mention "go-zero" in prompts
Additional Resources
- Windsurf Documentation
- Cascade AI
- go-zero Official Docs
- zero-skills Pattern Guides
go-zero Skills - AI 助手的知识库
English | 简体中文
这是一个 Agent Skill(智能体技能),包含为 AI 编程助手优化的 go-zero 框架知识和模式,帮助开发者更高效地构建微服务应用。
什么是 Skill?
Skills 是包含指令、脚本和资源的文件夹,AI 智能体可以动态发现和加载,以更好地完成特定任务。这个 skill 教会 AI 智能体如何生成生产级的 go-zero 微服务代码。
目标
本 skill 使 AI 助手(Claude、GitHub Copilot、Cursor 等)能够:
- 生成符合 go-zero 规范的准确代码
- 理解三层架构(Handler → Logic → Model)
- 应用微服务开发最佳实践
- 高效排查常见问题
- 构建生产就绪的应用
快速安装
只需告诉你的 AI 助手:
Install zero-skills from https://github.com/zeromicro/zero-skills或者手动安装:
# 项目级别(推荐)
git clone https://github.com/zeromicro/zero-skills.git .claude/skills/zero-skills
# 个人级别(所有项目可用)
git clone https://github.com/zeromicro/zero-skills.git ~/.claude/skills/zero-skillsAgent Skill 结构
遵循 Agent Skills 规范 和 Claude Code skills 文档:
zero-skills/
├── SKILL.md # 入口文件,包含 YAML 元数据
├── getting-started/ # 快速开始指南
│ ├── README.md # 工具对比概览
│ ├── claude-code-guide.md # Claude Code(推荐)
│ ├── cursor-guide.md # Cursor IDE
│ ├── copilot-guide.md # GitHub Copilot
│ └── windsurf-guide.md # Windsurf IDE
├── references/ # 详细模式文档
│ ├── rest-api-patterns.md # REST API 开发模式
│ ├── rpc-patterns.md # gRPC 服务模式
│ ├── database-patterns.md # 数据库操作
│ └── resilience-patterns.md # 弹性和容错
├── best-practices/ # 生产级建议
├── troubleshooting/ # 常见问题和解决方案
├── skill-patterns/ # 高级技能示例(模板)
│ ├── analyze-project.md # Explore 代理示例
│ ├── generate-service.md # 参数传递示例
│ └── plan-architecture.md # Plan 代理示例
└── examples/ # 演示项目和验证脚本使用这个 Skill
在 Claude Code 中使用(推荐)
Claude Code 原生支持 Agent Skills 规范。本 skill 针对 Claude Code 进行了优化,支持高级功能:
项目级安装(Git Submodule)
将 zero-skills 添加到项目中以自动发现:
# 添加为 git submodule
git submodule add https://github.com/zeromicro/zero-skills.git .claude/skills/zero-skills
# 或直接克隆
git clone https://github.com/zeromicro/zero-skills.git .claude/skills/zero-skillsClaude Code 会自动发现 .claude/skills/ 目录中的 skills。
个人级安装
跨所有项目使用,安装到个人 skills 目录:
# 克隆到个人 skills 目录
git clone https://github.com/zeromicro/zero-skills.git ~/.claude/skills/zero-skills在 Claude Code 中的使用方式
- 自动加载:处理 go-zero 文件(
.api、.proto、包含 go-zero 的go.mod)时自动加载 - 手动调用:输入
/zero-skills直接调用获取 go-zero 指导 - 带参数调用:
/zero-skills 创建用户管理 API用于特定任务 - 检查可用性:询问 "What skills are available?" 查看是否已加载
高级功能
- 动态上下文:Skills 可以执行 shell 命令获取实时项目数据
- 子代理:使用
context: fork进行隔离的分析或规划任务 - 工具限制:
allowed-tools确保安全的只读操作 - 参见 skill-patterns/ 获取高级模式和模板
在 Claude Desktop 中使用
添加到 claude_desktop_config.json:
{
"mcpServers": {
"zero-skills": {
"command": "node",
"args": ["/path/to/skill-server.js", "/path/to/zero-skills"]
}
}
}在 GitHub Copilot 中使用
参见 copilot-guide.md 获取详细设置。快速开始:
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skills然后创建 .github/copilot-instructions.md 引用模式文件。
在 Cursor 中使用
参见 cursor-guide.md 获取详细设置。快速开始:
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skills然后创建 .cursorrules 引用模式文件。
在 Windsurf 中使用
参见 windsurf-guide.md 获取详细设置。快速开始:
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skills然后创建 .windsurfrules 引用模式文件。
与 go-zero AI 生态集成
zero-skills 是 go-zero AI 辅助开发两层生态的一部分:
| 工具 | 用途 | 大小 | 最适合 |
|---|---|---|---|
| [ai-context](https://github.com/zeromicro/ai-context) | 工作流指令和决策树 | ~5KB | GitHub Copilot, Cursor, Windsurf |
| zero-skills(本仓库) | 完整知识库 + goctl 参考 | ~45KB | 所有 AI 工具,深度学习,参考 |
AI 在终端中直接运行 goctl 生成代码——无需额外工具或服务器。完整命令参考见 references/goctl-commands.md。
它们如何协作
┌─────────────────────────────────────────────────────────────┐
│ AI 助手 │
│ (Claude Code, GitHub Copilot, Cursor, Windsurf) │
└────────────┬─────────────────────┬──────────────────────────┘
│ │
├─ 工作流层 ──────────┤
│ ai-context │ "做什么" - 快速决策
│ (~5KB) │ 每次交互都加载
│ │
└─ 知识层 ────────────┘
zero-skills "如何和为什么" - 详细模式
(~45KB) + goctl 命令参考
需要时加载使用场景
场景 1: Claude Code 用户(最佳体验)
- 使用:
zero-skills(本仓库)作为原生 skill - 优点:
- 来自模式指南的深度知识
- AI 在终端直接运行 goctl 命令
- 实时项目数据的动态上下文
- 复杂任务的子代理工作流
- 调用:
/zero-skills或处理 go-zero 时自动加载
场景 2: GitHub Copilot 用户
- 使用:
ai-context(通过.github/copilot-instructions.md加载) - 优点:快速内联建议,工作流指导,通过终端运行 goctl
场景 3: Cursor/Windsurf 用户
- 使用:
ai-context(在项目规则中)+zero-skills链接 - 优点:IDE 原生体验加 go-zero 指导,通过终端运行 goctl
参见 入门指南 获取每个工具的详细集成说明。
快速链接
Skill 文档:
- 📖 [SKILL.md](SKILL.md) - 主要 skill 入口和导航
- 📚 [go-zero 快速开始](https://go-zero.dev/docs/quick-start) - 官方 go-zero 框架教程
- 🎯 [高级示例](skill-patterns/) - 子代理,动态上下文等
入门指南:
- 💡 [Claude Code](getting-started/claude-code-guide.md) - 完整功能,子代理(推荐)
- 🖱️ [Cursor](getting-started/cursor-guide.md) - IDE 集成 .cursorrules
- 🤖 [GitHub Copilot](getting-started/copilot-guide.md) - VS Code 内联建议
- 🏄 [Windsurf](getting-started/windsurf-guide.md) - Cascade AI 集成
- 📋 [工具对比](getting-started/README.md) - 比较所有工具
贡献指南
欢迎贡献!请确保:
- 示例完整且经过测试
- 模式遵循官方 go-zero 约定
- 内容结构化,便于 AI 理解
- 包含正确(✅)和错误(❌)的示例对比
- 遵循 Agent Skills 规范
许可证
MIT License - 与 go-zero 框架相同
go-zero Skills for AI Agents
English | 简体中文
This is an Agent Skill containing structured knowledge and patterns for AI coding assistants to help developers work effectively with the go-zero framework.
What is a Skill?
Skills are folders of instructions, scripts, and resources that AI agents discover and load dynamically to perform better at specific tasks. This skill teaches AI agents how to generate production-ready go-zero microservices code.
Purpose
This skill enables AI agents (Claude, GitHub Copilot, Cursor, etc.) to:
- Generate accurate go-zero code following framework conventions
- Understand the three-layer architecture (Handler → Logic → Model)
- Apply best practices for microservices development
- Troubleshoot common issues efficiently
- Build production-ready applications
Quick Install
Just ask your AI agent:
Install zero-skills from https://github.com/zeromicro/zero-skillsOr manually:
# Project-level (recommended)
git clone https://github.com/zeromicro/zero-skills.git .claude/skills/zero-skills
# Personal-level (all projects)
git clone https://github.com/zeromicro/zero-skills.git ~/.claude/skills/zero-skillsAgent Skill Structure
Following the Agent Skills Spec and Claude Code skills documentation:
zero-skills/
├── SKILL.md # Entry point with YAML frontmatter
├── getting-started/ # Getting started guides
│ ├── README.md # Tool comparison overview
│ ├── claude-code-guide.md # Claude Code (recommended)
│ ├── cursor-guide.md # Cursor IDE
│ ├── copilot-guide.md # GitHub Copilot
│ └── windsurf-guide.md # Windsurf IDE
├── references/ # Detailed pattern documentation
│ ├── rest-api-patterns.md # REST API development patterns
│ ├── rpc-patterns.md # gRPC service patterns
│ ├── database-patterns.md # Database operations
│ └── resilience-patterns.md # Resilience and fault tolerance
├── best-practices/ # Production recommendations
├── troubleshooting/ # Common issues and solutions
├── skill-patterns/ # Advanced skill examples (templates)
│ ├── analyze-project.md # Explore agent example
│ ├── generate-service.md # Argument passing example
│ └── plan-architecture.md # Plan agent example
└── examples/ # Demo projects and verificationUsing This Skill
With Claude Code (Recommended)
Claude Code natively supports the Agent Skills specification. This skill is optimized for Claude Code with advanced features:
Project-Level Installation (Git Submodule)
Add zero-skills to your project for automatic discovery:
# Add as git submodule
git submodule add https://github.com/zeromicro/zero-skills.git .claude/skills/zero-skills
# Or clone directly
git clone https://github.com/zeromicro/zero-skills.git .claude/skills/zero-skillsClaude Code automatically discovers skills in .claude/skills/ directories.
Personal-Level Installation
To use across all your projects, install to your personal skills directory:
## Clone to personal skills directory
git clone https://github.com/zeromicro/zero-skills.git ~/.claude/skills/zero-skillsUsage in Claude Code
- Automatic: Claude loads the skill when you work with go-zero files (
.api,.proto,go.modwith go-zero) - Manual: Type
/zero-skillsto invoke directly for go-zero guidance - With arguments:
/zero-skills Create a user management APIfor specific tasks - Check availability: Ask "What skills are available?" to see if it's loaded
Advanced Features
- Dynamic context: Skills can execute shell commands to gather live project data
- Subagents: Use
context: forkfor isolated analysis or planning tasks - Tool restrictions:
allowed-toolsensures safe, read-only operations - See skill-patterns/ for advanced patterns and templates
With Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"zero-skills": {
"command": "node",
"args": ["/path/to/skill-server.js", "/path/to/zero-skills"]
}
}
}With GitHub Copilot
See copilot-guide.md for detailed setup. Quick start:
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skillsThen create .github/copilot-instructions.md referencing the patterns.
With Cursor
See cursor-guide.md for detailed setup. Quick start:
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skillsThen create .cursorrules referencing the patterns.
With Windsurf
See windsurf-guide.md for detailed setup. Quick start:
git clone https://github.com/zeromicro/zero-skills.git .ai-context/zero-skillsThen create .windsurfrules referencing the patterns.
Integration with go-zero AI Ecosystem
zero-skills is part of a two-layer ecosystem for AI-assisted go-zero development:
| Tool | Purpose | Size | Best For |
|---|---|---|---|
| [ai-context](https://github.com/zeromicro/ai-context) | Workflow instructions and decision trees | ~5KB | GitHub Copilot, Cursor, Windsurf |
| zero-skills (this repo) | Comprehensive knowledge base + goctl reference | ~45KB | All AI tools, deep learning, reference |
The AI runs goctl directly in the terminal for code generation — no separate tools or servers needed. See references/goctl-commands.md for the complete command reference.
How They Work Together
┌─────────────────────────────────────────────────────────────┐
│ AI Assistant │
│ (Claude Code, GitHub Copilot, Cursor, Windsurf) │
└────────────┬─────────────────────┬──────────────────────────┘
│ │
├─ Workflow Layer ────┤
│ ai-context │ "What to do" - Quick decisions
│ (~5KB) │ Loaded for every interaction
│ │
└─ Knowledge Layer ───┘
zero-skills "How & Why" - Detailed patterns
(~45KB) + goctl command reference
Loaded when neededUsage Scenarios
Scenario 1: Claude Code User (Best Experience)
- Uses:
zero-skills(this repo) as native skill - Benefits:
- Deep knowledge from pattern guides
- AI runs goctl commands directly in terminal
- Dynamic context with live project data
- Subagent workflows for complex tasks
- Invocation:
/zero-skillsor automatic when working with go-zero
Scenario 2: GitHub Copilot User
- Uses:
ai-context(loaded via.github/copilot-instructions.md) - Benefits: Quick inline suggestions, workflow guidance, goctl via terminal
Scenario 3: Cursor/Windsurf User
- Uses:
ai-context(in project rules) + links tozero-skills - Benefits: IDE-native experience with go-zero guidance, goctl via terminal
See Getting Started Guides for detailed integration instructions for each tool.
Quick Links
Skill Documentation:
- 📖 [SKILL.md](SKILL.md) - Main skill entry point and navigation
- 📚 [go-zero Quick Start](https://go-zero.dev/docs/quick-start) - Official go-zero framework tutorial
- 🎯 [Advanced Examples](skill-patterns/) - Subagents, dynamic context, etc.
Getting Started Guides:
- 💡 [Claude Code](getting-started/claude-code-guide.md) - Full features, subagents (recommended)
- 🖱️ [Cursor](getting-started/cursor-guide.md) - IDE integration with .cursorrules
- 🤖 [GitHub Copilot](getting-started/copilot-guide.md) - VS Code inline suggestions
- 🏄 [Windsurf](getting-started/windsurf-guide.md) - Cascade AI integration
- 📋 [Tool Comparison](getting-started/README.md) - Compare all tools
Contributing
Contributions are welcome! Please ensure:
- Examples are complete and tested
- Patterns follow official go-zero conventions
- Content is structured for AI consumption
- Include both correct (✅) and incorrect (❌) examples
- Follow the Agent Skills specification
License
MIT License - Same as go-zero framework
goctl Command Reference
This file is a skill for AI assistants. It teaches the AI to use goctl directly in the terminal
to generate go-zero code.
1. goctl Installation & Detection
Check if goctl is installed
which goctl && goctl --versionInstall goctl if not found
go install github.com/zeromicro/go-zero/tools/goctl@latestVerify installation
goctl --versionIf go install fails, check that $GOPATH/bin or $HOME/go/bin is in $PATH.
2. API Service
2.1 Create new API service
# Basic
goctl api new <service-name> --style go_zero
# With output directory
mkdir -p <output-dir> && cd <output-dir>
goctl api new <service-name> --style go_zero2.2 Generate code from .api spec
goctl api go -api <file>.api -dir . --style go_zeroSafe to re-run — goctl will NOT overwrite files with custom logic (handler/logic files are only created if they don't exist).
2.3 Create .api spec file
Write the .api spec manually following the go-zero API syntax. See API Spec Patterns below.
2.4 Validate .api spec
goctl api validate -api <file>.api3. RPC Service
3.1 Create new RPC service from .proto
goctl rpc protoc <file>.proto --go_out=. --go-grpc_out=. --zrpc_out=. --style go_zero3.2 Create simple RPC service
goctl rpc new <service-name> --style go_zero4. Database Model
4.1 From MySQL
# From live database
goctl model mysql datasource \
-url "user:pass@tcp(host:3306)/dbname" \
-table "<table-name>" \
-dir ./model \
--style go_zero
# With cache
goctl model mysql datasource \
-url "user:pass@tcp(host:3306)/dbname" \
-table "<table-name>" \
-dir ./model \
-cache \
--style go_zero4.2 From DDL file
goctl model mysql ddl -src <file>.sql -dir ./model --style go_zero
# With cache
goctl model mysql ddl -src <file>.sql -dir ./model -cache --style go_zero4.3 From PostgreSQL
goctl model pg datasource \
-url "postgres://user:pass@host:5432/dbname?sslmode=disable" \
-table "<table-name>" \
-dir ./model \
--style go_zero4.4 From MongoDB
goctl model mongo -type <TypeName> -dir ./model --style go_zero5. Post-Generation Pipeline
CRITICAL: After every goctl generation command, always run these steps:
Step 1: Initialize Go module (if new project)
# Only if go.mod doesn't exist
[ ! -f go.mod ] && go mod init <module-name>Step 2: Tidy dependencies
go mod tidyStep 3: Verify imports
Check that generated files have correct import paths matching the module in go.mod. If imports reference the wrong module path, fix them:
# Find files with wrong import path
grep -r "old/module/path" --include="*.go" -l
# Fix imports (replace old path with correct one)
find . -name "*.go" -exec sed -i '' "s|old/module/path|correct/module/path|g" {} +Step 4: Verify build
go build ./...If build fails, check:
- Missing imports → run
go mod tidyagain - Import path mismatch → fix module paths (Step 3)
- Style conflicts → check
--styleflag matches existing code
Step 5: Check naming style consistency
If the project already has generated files, check their naming convention:
# Check existing file names
ls internal/handler/ internal/logic/ internal/types/ 2>/dev/null- Files like
get_user_handler.go→ use--style go_zero - Files like
getuserhandler.go→ use--style gozero(or omit--style) - Files like
getUserHandler.go→ use--style goZero
Always match the existing style to avoid conflicts.
6. Config Templates
API service config (etc/<service>.yaml)
Name: <service-name>
Host: 0.0.0.0
Port: <port>
# Database (if needed)
MySQL:
DataSource: user:pass@tcp(localhost:3306)/dbname
# Auth (if needed)
Auth:
AccessSecret: "your-secret-key-change-in-production"
AccessExpire: 86400
# Cache (if needed)
Cache:
- Host: localhost:6379RPC service config (etc/<service>.yaml)
Name: <service-name>.rpc
ListenOn: 0.0.0.0:<port>
# Etcd for service discovery (if needed)
Etcd:
Hosts:
- localhost:2379
Key: <service-name>.rpc
# Database (if needed)
MySQL:
DataSource: user:pass@tcp(localhost:3306)/dbnameProduction config additions
# Logging
Log:
Mode: file
Path: logs
Level: error
Compress: true
KeepDays: 7
# Telemetry
Telemetry:
Name: <service-name>
Endpoint: http://localhost:14268/api/traces
Sampler: 1.0
# Prometheus
Prometheus:
Host: 0.0.0.0
Port: 9091
Path: /metrics7. Deployment Templates
Dockerfile
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server .
FROM alpine:3.19
RUN apk --no-cache add ca-certificates tzdata
WORKDIR /app
COPY --from=builder /app/server .
COPY etc/ etc/
EXPOSE <port>
CMD ["./server", "-f", "etc/<service>.yaml"]Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: <service-name>
labels:
app: <service-name>
spec:
replicas: 3
selector:
matchLabels:
app: <service-name>
template:
metadata:
labels:
app: <service-name>
spec:
containers:
- name: <service-name>
image: <registry>/<service-name>:latest
ports:
- containerPort: <port>
volumeMounts:
- name: config
mountPath: /app/etc
livenessProbe:
httpGet:
path: /health
port: <port>
initialDelaySeconds: 5
periodSeconds: 10
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
volumes:
- name: config
configMap:
name: <service-name>-config
---
apiVersion: v1
kind: Service
metadata:
name: <service-name>
spec:
selector:
app: <service-name>
ports:
- port: <port>
targetPort: <port>
type: ClusterIPDocker Compose (development)
version: '3.8'
services:
<service-name>:
build: .
ports:
- "<port>:<port>"
volumes:
- ./etc:/app/etc
depends_on:
- mysql
- redis
restart: unless-stopped
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: <dbname>
ports:
- "3306:3306"
volumes:
- mysql-data:/var/lib/mysql
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
mysql-data:8. Middleware Template
package middleware
import "net/http"
type <Name>Middleware struct{}
func New<Name>Middleware() *<Name>Middleware {
return &<Name>Middleware{}
}
func (m *<Name>Middleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// TODO: implement middleware logic
next(w, r)
}
}9. Error Handler Template
package errorx
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
type CodeError struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
func NewCodeError(code int, msg string) *CodeError {
return &CodeError{Code: code, Msg: msg}
}
func (e *CodeError) Error() string {
return e.Msg
}
// ErrorHandler is a custom error handler for go-zero REST server.
// Set it with: httpx.SetErrorHandler(errorx.ErrorHandler)
func ErrorHandler(err error) (int, any) {
switch e := err.(type) {
case *CodeError:
return http.StatusOK, e
default:
return http.StatusInternalServerError, CodeError{
Code: http.StatusInternalServerError,
Msg: err.Error(),
}
}
}10. Common goctl Flags Reference
| Flag | Description | Example |
|---|---|---|
--style | Naming convention for generated files | go_zero, gozero, goZero |
-dir | Output directory | -dir ./ |
-api | Path to .api spec file | -api user.api |
-cache | Generate with cache support (model only) | -cache |
-url | Database connection URL | -url "user:pass@tcp(host)/db" |
-table | Table name for model generation | -table users |
-src | Source DDL file path | -src schema.sql |
--home | Custom template directory | --home ~/.goctl/templates |
--remote | Remote template repo | --remote https://github.com/... |
API Spec Patterns
Basic CRUD
syntax = "v1"
type (
CreateRequest {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
}
CreateResponse {
Id int64 `json:"id"`
}
GetRequest {
Id int64 `path:"id"`
}
GetResponse {
Id int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
UpdateRequest {
Id int64 `path:"id"`
Name string `json:"name,optional"`
Email string `json:"email,optional"`
}
DeleteRequest {
Id int64 `path:"id"`
}
ListRequest {
Page int64 `form:"page,default=1"`
PageSize int64 `form:"pageSize,default=20"`
}
ListResponse {
Total int64 `json:"total"`
Items []GetResponse `json:"items"`
}
)
@server (
group: <resource>
prefix: /api/v1
)
service <service-name> {
@handler Create<Resource>
post /<resources> (CreateRequest) returns (CreateResponse)
@handler Get<Resource>
get /<resources>/:id (GetRequest) returns (GetResponse)
@handler Update<Resource>
put /<resources>/:id (UpdateRequest) returns (GetResponse)
@handler Delete<Resource>
delete /<resources>/:id (DeleteRequest)
@handler List<Resource>
get /<resources> (ListRequest) returns (ListResponse)
}JWT Protected Routes
@server (
jwt: Auth
group: <resource>
prefix: /api/v1
)
service <service-name> {
@handler GetProfile
get /profile returns (ProfileResponse)
}Mixed (public + protected)
// Public routes
@server (
group: auth
prefix: /api/v1
)
service <service-name> {
@handler Login
post /login (LoginRequest) returns (LoginResponse)
@handler Register
post /register (RegisterRequest) returns (RegisterResponse)
}
// Protected routes
@server (
jwt: Auth
group: user
prefix: /api/v1
)
service <service-name> {
@handler GetProfile
get /users/profile returns (ProfileResponse)
}Quick Reference: Full Workflow
1. Create .api spec file
2. goctl api go -api <file>.api -dir . --style go_zero
3. [ ! -f go.mod ] && go mod init <module>
4. go mod tidy
5. Verify imports match go.mod module path
6. go build ./...
7. Implement business logic in internal/logic/
8. Update config in etc/<service>.yaml
9. go run <service>.go -f etc/<service>.yamlExample: Deep Project Analysis with Subagent
This example demonstrates using context: fork with the Explore agent to perform thorough codebase analysis.
Skill Configuration
---
name: analyze-gozero-project
description: Analyze a go-zero project structure and identify issues
context: fork
agent: Explore
allowed-tools:
- Read
- Grep
- Glob
---
Analyze the go-zero project in the current workspace:
1. **Project Structure Analysis**
- Find all .api files: !`find . -name "*.api" -type f`
- Find all .proto files: !`find . -name "*.proto" -type f`
- Identify service entry points: !`find . -name "main.go" -type f`
2. **Architecture Validation**
- Check if three-layer architecture is followed
- Verify Handler → Logic → Model separation
- Look for business logic in handlers (anti-pattern)
3. **Configuration Review**
- Find all config files: !`find . -name "*-api.yaml" -o -name "*-rpc.yaml"`
- Check for hardcoded values in source files
- Verify proper use of conf.MustLoad
4. **Common Issues Detection**
- Search for `fmt.Errorf` in handlers (should use httpx.Error)
- Check if all handlers have corresponding logic files
- Verify proper error handling patterns
5. **Generate Report**
Provide a summary with:
- Service count and types (API/RPC)
- Architecture compliance score
- Specific issues found with file references
- Recommendations for improvementsHow Dynamic Context Works
The !command"` syntax executes shell commands before the skill content is sent to Claude. The output replaces the placeholder:
!find . -name "*.api"`` → Lists all API definition files!find . -name "*.proto"`` → Lists all Proto files!find . -name "*-api.yaml"`` → Lists all config files
This preprocessing happens instantly, giving Claude real project data instead of generic instructions.
Expected Behavior
1. Subagent runs in isolated context (no conversation history) 2. Shell commands execute and inject actual file paths 3. Explore agent uses read-only tools to analyze files 4. Results summarized and returned to main conversation
Use Cases
- Initial project audit: Understand a new codebase structure
- Code review automation: Check for common anti-patterns
- Architecture compliance: Verify go-zero conventions
- Onboarding: Generate project documentation for new developers