Skip to content
go-api-reviewer logo

Go API Reviewer Skill

go-api-reviewer

WHEN: Go API review with Gin/Echo/Fiber/Chi, router patterns, middleware, request handling WHAT: Router organization + Middleware patterns + Request validation + Error responses + OpenAPI WHEN NOT: General Go → go-reviewer, Rust API → rust-api-reviewer

SKILL.md

Full skill instructions

Go API Reviewer Skill

Purpose

Reviews Go API projects using Gin, Echo, Fiber, or Chi for routing, middleware, and API patterns.

When to Use

  • Go REST API code review
  • Gin/​Echo/​Fiber/​Chi project review
  • Middleware implementation review
  • API request/​response handling
  • API documentation review

Project Detection

  • github.com/​gin-gonic/​gin import
  • github.com/​labstack/​echo import
  • github.com/​gofiber/​fiber import
  • github.com/​go-chi/​chi import
  • handlers/, routes/, middleware/ directories

Workflow

Step 1: Analyze Project

**Framework**: Gin v1.9+
**Router**: Group-based routing
**Middleware**: Auth, CORS, Logger, Recovery
**Validation**: go-playground/​validator
**Docs**: Swagger/​OpenAPI

Step 2: Select Review Areas

AskUserQuestion:

"Which areas to review?"
Options:
- Full API review (recommended)
- Router and handler patterns
- Middleware implementation
- Request validation
- Error handling and responses
multiSelect: true

Detection Rules

Router Organization

CheckRecommendationSeverity
All routes in mainUse router groupsMEDIUM
No versioningAdd /​api/​v1 prefixMEDIUM
Inconsistent namingFollow REST conventionsLOW
No route groupingGroup by resourceMEDIUM
// BAD: All routes in main.go
func main() {
    r := gin.Default()
    r.GET("/​users", getUsers)
    r.POST("/​users", createUser)
    r.GET("/​users/:id", getUser)
    r.GET("/​products", getProducts)
    // ... 50 more routes
}

// GOOD: Organized route groups (Gin)
func SetupRouter() *gin.Engine {
    r := gin.Default()

    api := r.Group("/​api/​v1")
    {
        users := api.Group("/​users")
        {
            users.GET("", listUsers)
            users.POST("", createUser)
            users.GET("/:id", getUser)
            users.PUT("/:id", updateUser)
            users.DELETE("/:id", deleteUser)
        }

        products := api.Group("/​products")
        {
            products.GET("", listProducts)
            products.GET("/:id", getProduct)
        }
    }

    return r
}

// GOOD: Separate route files
// routes/​users.go
func RegisterUserRoutes(rg *gin.RouterGroup) {
    users := rg.Group("/​users")
    h := NewUserHandler()

    users.GET("", h.List)
    users.POST("", h.Create)
    users.GET("/:id", h.Get)
}

Middleware Patterns

CheckRecommendationSeverity
Auth in handlerExtract to middlewareHIGH
No recovery middlewareAdd panic recoveryHIGH
No request IDAdd request ID middlewareMEDIUM
Middleware order wrongOrder: Logger → Recovery → AuthMEDIUM
// GOOD: Middleware stack (Gin)
func SetupMiddleware(r *gin.Engine) {
    // Order matters!
    r.Use(gin.Logger())
    r.Use(gin.Recovery())
    r.Use(RequestIDMiddleware())
    r.Use(CORSMiddleware())
}

// GOOD: Auth middleware
func AuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        token := c.GetHeader("Authorization")
        if token == "" {
            c.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
            return
        }

        claims, err := ValidateToken(token)
        if err != nil {
            c.AbortWithStatusJSON(401, gin.H{"error": "invalid token"})
            return
        }

        c.Set("user_id", claims.UserID)
        c.Next()
    }
}

// Usage
api := r.Group("/​api/​v1")
api.Use(AuthMiddleware())

// GOOD: Request ID middleware
func RequestIDMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        requestID := c.GetHeader("X-Request-ID")
        if requestID == "" {
            requestID = uuid.New().String()
        }
        c.Set("request_id", requestID)
        c.Header("X-Request-ID", requestID)
        c.Next()
    }
}

Request Validation

CheckRecommendationSeverity
Manual validationUse validator tagsMEDIUM
No binding errorsReturn validation errorsHIGH
No request DTOsDefine request structsMEDIUM
Missing required fieldsAdd binding:"required"HIGH
// GOOD: Request struct with validation
type CreateUserRequest struct {
    Name     string `json:"name" binding:"required,min=1,max=100"`
    Email    string `json:"email" binding:"required,email"`
    Age      int    `json:"age" binding:"gte=0,lte=150"`
    Role     string `json:"role" binding:"oneof=admin user guest"`
    Password string `json:"password" binding:"required,min=8"`
}

// GOOD: Handler with validation
func (h *UserHandler) Create(c *gin.Context) {
    var req CreateUserRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(400, gin.H{
            "error":   "validation_error",
            "details": formatValidationErrors(err),
        })
        return
    }

    user, err := h.service.Create(c.Request.Context(), &req)
    if err != nil {
        handleError(c, err)
        return
    }

    c.JSON(201, user)
}

// GOOD: Format validation errors
func formatValidationErrors(err error) map[string]string {
    errors := make(map[string]string)

    var ve validator.ValidationErrors
    if errors.As(err, &ve) {
        for _, e := range ve {
            field := strings.ToLower(e.Field())
            errors[field] = getErrorMessage(e)
        }
    }

    return errors
}

Error Handling

CheckRecommendationSeverity
Inconsistent error formatUse standard error responseHIGH
Internal errors exposedHide implementation detailsHIGH
No error codesAdd error codesMEDIUM
HTTP status inconsistentFollow REST conventionsMEDIUM
// GOOD: Standard error response
type ErrorResponse struct {
    Error   string            `json:"error"`
    Code    string            `json:"code,omitempty"`
    Details map[string]string `json:"details,omitempty"`
}

// GOOD: Custom errors
var (
    ErrNotFound     = &AppError{Code: "NOT_FOUND", Status: 404}
    ErrUnauthorized = &AppError{Code: "UNAUTHORIZED", Status: 401}
    ErrConflict     = &AppError{Code: "CONFLICT", Status: 409}
)

type AppError struct {
    Code    string
    Status  int
    Message string
}

func (e *AppError) Error() string {
    return e.Message
}

// GOOD: Error handler
func handleError(c *gin.Context, err error) {
    var appErr *AppError
    if errors.As(err, &appErr) {
        c.JSON(appErr.Status, ErrorResponse{
            Error: appErr.Message,
            Code:  appErr.Code,
        })
        return
    }

    // Log internal error, return generic message
    log.Printf("internal error: %v", err)
    c.JSON(500, ErrorResponse{
        Error: "Internal server error",
        Code:  "INTERNAL_ERROR",
    })
}

Framework-Specific (Echo)

// Echo example
func SetupEcho() *echo.Echo {
    e := echo.New()

    e.Use(middleware.Logger())
    e.Use(middleware.Recover())
    e.Use(middleware.RequestID())
    e.Use(middleware.CORS())

    api := e.Group("/​api/​v1")
    api.Use(AuthMiddleware)

    RegisterUserRoutes(api)

    return e
}

// Echo handler
func (h *UserHandler) Create(c echo.Context) error {
    var req CreateUserRequest
    if err := c.Bind(&req); err != nil {
        return echo.NewHTTPError(400, "invalid request")
    }

    if err := c.Validate(&req); err != nil {
        return err
    }

    user, err := h.service.Create(c.Request().Context(), &req)
    if err != nil {
        return err
    }

    return c.JSON(201, user)
}

Response Template

## Go API Code Review Results

**Project**: [name]
**Framework**: Gin 1.9 | **Go**: 1.22

### Router Organization
| Status | File | Issue |
|--------|------|-------|
| MEDIUM | main.go | 40+ routes in single file |

### Middleware
| Status | File | Issue |
|--------|------|-------|
| HIGH | handlers/​user.go | Auth check in handler, not middleware |

### Validation
| Status | File | Issue |
|--------|------|-------|
| HIGH | handlers/​user.go:34 | No request validation |

### Error Handling
| Status | File | Issue |
|--------|------|-------|
| HIGH | handlers/​product.go | Inconsistent error response format |

### Recommended Actions
1. [ ] Split routes into separate files by resource
2. [ ] Extract auth logic to middleware
3. [ ] Add request struct validation
4. [ ] Implement standard error response format

Best Practices

  1. Router: Group by resource, version API
  2. Middleware: Proper order, reusable
  3. Validation: Use validator tags
  4. Errors: Standard format, hide internals
  5. Docs: Generate OpenAPI from code

Integration

  • go-reviewer: General Go patterns
  • security-scanner: API security
  • api-documenter: OpenAPI documentation

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View