一键导入
tpl-backend-go-chi-gorm
Template do pack (backend/04-go-chi-gorm.md). Orienta o agente em APIs, servicos e arquitetura backend alinhado a esse contexto.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Template do pack (backend/04-go-chi-gorm.md). Orienta o agente em APIs, servicos e arquitetura backend alinhado a esse contexto.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Generate custom favicons from logos, text, or brand colours. Produces favicon.svg, favicon.ico, apple-touch-icon.png, icon-192/512.png, and web manifest. Use whenever the user wants a favicon, mentions replacing a CMS default favicon, converting a logo into a favicon, creating branded initials icons, or troubleshooting favicon not displaying / iOS black square / missing manifest.
"Get a second opinion from leading AI models on code, architecture, strategy, prompting, or anything. Queries models via OpenRouter, Gemini, or OpenAI APIs. Supports single opinion, multi-model consensus, and devil's advocate patterns. Use whenever the user says 'brains trust', 'second opinion', 'ask gemini', 'ask gpt', 'peer review', 'consult another model', 'challenge this', or 'devil's advocate'."
Run an independent code review using the OpenAI Codex CLI in headless mode. Gets a second opinion from a different model family (GPT-5/o3) on recent changes, a PR, a commit, or the whole app — covering bugs, regressions, security, data consistency, UX/state bugs, performance risks, and testing gaps. Saves a severity-prioritised report to .jez/reviews/. Triggers: 'codex review', 'review with codex', 'second opinion on this code', 'independent code review', 'what does codex think', 'get codex to review'.
Deep research and discovery before building something new. Explores local projects for reusable code, researches competitors, reads forums and reviews, analyses plugin ecosystems, investigates technical options, and produces a comprehensive research brief. Three depths: focused (30 min), wide (1-2 hours), deep (3-6 hours). Triggers: 'research this', 'deep research', 'discovery', 'explore the space', 'what should I build', 'competitive analysis', 'before I start building', 'research before coding'.
Plan and execute entire application builds. Generates phased delivery roadmaps, then executes them autonomously — phase by phase, committing at milestones, deploying, testing, and continuing until done or stuck. Modes: plan (generate roadmap), start (begin executing), resume (continue from where you left off), status (show progress). Triggers: 'roadmap', 'plan the build', 'start building', 'resume the build', 'keep going', 'build the whole thing', 'execute the roadmap', 'what phase are we on'.
Walk through a live web app AS a real user to find usability + behavioural bugs that static reviews miss. REQUIRES proof of interaction (typing, clicking, sending, observing) before any verdict — a sweep that didn't interact terminates with verdict 'Incomplete'. Walks threads, exercises every element, runs the multi-pane stress matrix, visual polish sweep, component perfection checklist, automated a11y (axe-core), pragmatic performance budget (LCP/CLS/INP), scenario battery (11 scenarios), and stress recipes including the real-flavour data battery. Hard gates: console errors/warnings = 0, network 5xx = 0, layout collapse = 0, axe Critical/Serious = 0, perf budget green. Audit-the-audit meta-check rejects rushed reports. Each finding has reproduction steps, evidence path, and suspected code location. Trigger with 'ux audit', 'walkthrough', 'qa sweep', 'audit the app', 'dogfood this', 'check all pages', 'find what's broken', 'stress the UI'.
| name | tpl-backend-go-chi-gorm |
| description | Template do pack (backend/04-go-chi-gorm.md). Orienta o agente em APIs, servicos e arquitetura backend alinhado a esse contexto. |
| metadata | {"version":"1.0.0","source_template":"backend/04-go-chi-gorm.md","generated_by":"install_pack_templates_as_claude_skills"} |
Skill gerado a partir do pack templates-claude-code. Arquivo de origem: backend/04-go-chi-gorm.md. Use como baseline e adapte ao projeto antes de mudancas grandes.
| Technology | Version | Purpose |
|---|---|---|
| Go | 1.22+ | Language + runtime |
| Chi | v5 | HTTP router + middleware |
| GORM | v2 | ORM + migrations |
| PostgreSQL | 16 | Primary database |
| pgx/v5 | 5.x | PostgreSQL driver |
| golang-jwt/jwt | v5 | JWT tokens |
| bcrypt | stdlib | Password hashing |
| testify | v1.9+ | Assertions + mocking |
| slog | stdlib (1.21+) | Structured logging |
| golangci-lint | 1.58+ | Linting suite |
| godotenv | 1.5+ | .env loader for dev |
cmd/
└── api/
└── main.go # Entry point: setup + server.ListenAndServe
internal/
├── config/
│ └── config.go # Config struct + Load() from env
├── server/
│ └── server.go # Chi router setup, middleware chain, routes
├── handlers/
│ └── users/
│ ├── handler.go # HTTP handler methods (thin, calls service)
│ └── handler_test.go
├── services/
│ └── users/
│ ├── service.go # Business logic interface + implementation
│ └── service_test.go
├── repositories/
│ └── users/
│ ├── repository.go # GORM queries implementing interface
│ └── repository_test.go
├── models/
│ └── user.go # GORM model structs
├── middleware/
│ ├── auth.go # JWT verification middleware
│ ├── logger.go # Request logging middleware
│ └── recover.go # Panic recovery middleware
├── dto/
│ └── users/
│ ├── request.go # Input structs with validate tags
│ └── response.go # Output structs (no sensitive fields)
└── database/
└── database.go # GORM db connection + AutoMigrate
go.mod
go.sum
.golangci.yml
Makefile
*Handler with service interface injected via constructorRepository interface — not the concrete structdb package-level variable)// FunctionName does X)time.Time with json:"created_at" (UTC, no timezone stored)Rule: Never ignore errors. Wrap with context. Return early on error.
// Good — wrap errors with context
func (s *UserService) GetByID(ctx context.Context, id string) (*models.User, error) {
user, err := s.repo.FindByID(ctx, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotFound // sentinel error
}
return nil, fmt.Errorf("UserService.GetByID: %w", err)
}
return user, nil
}
// Handler (convert service errors to HTTP responses)
func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
user, err := h.svc.GetByID(r.Context(), id)
if err != nil {
if errors.Is(err, service.ErrUserNotFound) {
respondError(w, http.StatusNotFound, "user not found")
return
}
slog.ErrorContext(r.Context(), "failed to get user", "error", err, "id", id)
respondError(w, http.StatusInternalServerError, "internal error")
return
}
respondJSON(w, http.StatusOK, toUserResponse(user))
}
// internal/repositories/users/repository.go
type UserRepository interface {
FindByID(ctx context.Context, id string) (*models.User, error)
FindByEmail(ctx context.Context, email string) (*models.User, error)
Create(ctx context.Context, user *models.User) error
Update(ctx context.Context, user *models.User) error
Delete(ctx context.Context, id string) error
}
context.Context for cancellation — always accept ctx context.Context as first paramerrgroup.Group or waitgroup)*gorm.DB is safe for concurrent use (connection pool)// internal/server/server.go
func NewRouter(cfg *config.Config, userHandler *userhandler.Handler) *chi.Mux {
r := chi.NewRouter()
// Global middlewares (order matters)
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(loggerMiddleware.New(slog.Default()))
r.Use(recoverMiddleware.New())
r.Use(chimiddleware.Timeout(30 * time.Second))
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
r.Route("/api/v1", func(r chi.Router) {
r.Post("/auth/login", userHandler.Login)
r.Post("/auth/register", userHandler.Register)
r.Group(func(r chi.Router) {
r.Use(authmiddleware.Authenticate(cfg.JWTSecret))
r.Get("/users/me", userHandler.Me)
r.Patch("/users/me", userHandler.UpdateMe)
})
})
return r
}
// internal/middleware/auth.go
func Authenticate(secret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
tokenStr := header[7:]
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return []byte(secret), nil
})
if err != nil || !token.Valid {
http.Error(w, `{"error":"invalid or expired token"}`, http.StatusUnauthorized)
return
}
claims := token.Claims.(jwt.MapClaims)
ctx := context.WithValue(r.Context(), ctxKeyUserID, claims["sub"])
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// internal/models/user.go
func (u *User) BeforeCreate(tx *gorm.DB) error {
u.ID = uuid.New().String()
hashed, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash password: %w", err)
}
u.Password = string(hashed)
return nil
}
| Trigger | Method | Route | Middleware | Handler |
|---|---|---|---|---|
| Register | POST | /api/v1/auth/register | — | UserHandler.Register |
| Login | POST | /api/v1/auth/login | — | UserHandler.Login |
| Refresh token | POST | /api/v1/auth/refresh | — | UserHandler.Refresh |
| Get my profile | GET | /api/v1/users/me | Authenticate | UserHandler.Me |
| Update profile | PATCH | /api/v1/users/me | Authenticate | UserHandler.UpdateMe |
| List users | GET | /api/v1/users | Authenticate, RequireAdmin | UserHandler.List |
| Get user | GET | /api/v1/users/{id} | Authenticate, RequireAdmin | UserHandler.Get |
| Delete user | DELETE | /api/v1/users/{id} | Authenticate, RequireAdmin | UserHandler.Delete |
| Health check | GET | /health | — | inline |
Before opening a PR, verify ALL of the following:
golangci-lint run ./... passes with zero warningsgo test ./... -race -count=1 passes — no race conditionsgo vet ./... cleango test ./... -coverprofile=cover.out ≥ 75%go build ./cmd/api/... compiles without warningsinterface{} — use any (Go 1.18+) or specific typesfunc F(ctx context.Context, ...)log.Fatal outside of main.gofmt.Errorf("repo.FindByID: %w", err)json tags — no default field name exposurepanic() for error handling — only for truly unrecoverable init failuresdb variables — inject via constructorinterface{} as a shortcut — define real types_, _ = someFunc() is forbiddentime.Sleep inside request handlers — use context deadlineshttp.DefaultClient for external requests (no timeout) — configure a clientos.Exit outside main.go-race flag in CI test runs