agentleFS
mmNalakammNalaka/nm-skills/skills/go-api/SKILL.md

go-api

Skill1 starsChanged 6 months agoMITView on GitHub

Use for Golang web API work — enforces handler/service/repo layering, error wrapping, interfaces, context propagation, and no global state.

The file

Show its rules and text

We split this skill into the rules it gives an agent

18 rules. About 0 are common, 8 are distinctive, and 10 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈8

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 10

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Always wrap errors with context:

    line 48
  2. Very specific:

    Use errors.Is() and errors.As() in handlers to map to HTTP status codes — never do this in services.

    line 71
  3. Very specific:

    Use context.WithTimeout for external calls

    line 99
  4. Very specific:

    Prefer net/http stdlib + chi router

    line 103
  5. Distinctive:

    Avoid heavy frameworks (no gin, no echo — keep it replaceable)

    line 104
  6. Very specific:

    Use chi.URLParam(r, "id") for path params

    line 105
  7. Very specific:

    Use go-playground/validator struct tags:

    line 110
  8. Distinctive:

    Use a shared package — never build envelope inline:

    line 129
  9. Very specific:

    Use log/slog (stdlib, Go 1.21+):

    line 139
  10. Very specific:

    Use errgroup.Group for parallel work with error aggregation

    line 157
  11. Distinctive:

    Avoid raw goroutines without a WaitGroup or channel for synchronization

    line 158
  12. Very specific:

    Always pass context.Context to goroutine work for cancellation

    line 159
  13. Distinctive:

    No global variables for dependencies (db, logger, config) — inject via structs

    line 163
  14. Very specific:

    No bare errors.New("something") in service or repository without wrapping caller context

    line 164
  15. Distinctive:

    No business logic in handlers

    line 165
  16. Distinctive:

    No SQL in services

    line 166
  17. Very specific:

    No heavy frameworks replacing net/http

    line 168
  18. Distinctive:

    Never discard context — always propagate

    line 169

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Golang Web API

Conventions for Go web API development. These apply for the entire session once activated.

Recommended model: Sonnet

Includes all standards from the api-design skill.


Package and Layer Structure

Three layers per feature, each in its own file:

internal/
  users/
    handler.go      # HTTP: parse request, call service, write response
    service.go      # Business logic: no HTTP, no SQL
    repository.go   # DB: raw queries only
    types.go        # Domain types, request/response structs
  shared/
    response/
      response.go   # JSON response helpers
    middleware/
      auth.go
      logging.go
    errors/
      errors.go     # AppError, sentinel errors
cmd/
  api/
    main.go

Handler (thin): Decode request → validate → call service → encode response. No business logic.

Service: Pure business rules. No http.Request/http.ResponseWriter. No SQL. Returns domain types and errors.

Repository: SQL/DB only. No business rules. Takes context.Context as first arg.

Error Handling

Always wrap errors with context:

// In repository
return nil, fmt.Errorf("userRepo.FindByID: %w", err)

// In service
return nil, fmt.Errorf("userService.GetUser: %w", err)

Define typed errors for domain conditions:

var ErrNotFound = errors.New("not found")
var ErrConflict = errors.New("conflict")

type ValidationError struct {
    Field   string
    Message string
}
func (e *ValidationError) Error() string { return fmt.Sprintf("%s: %s", e.Field, e.Message) }

Use errors.Is() and errors.As() in handlers to map to HTTP status codes — never do this in services.

Interfaces and Dependency Injection

  • Accept interfaces, return concrete types
  • Define interfaces where they are used (not where implemented)
  • Inject all dependencies via struct fields; no global state
type UserRepository interface {
    FindByID(ctx context.Context, id string) (*User, error)
    Create(ctx context.Context, input CreateUserInput) (*User, error)
}

type UserService struct {
    repo   UserRepository
    logger *slog.Logger
}

func NewUserService(repo UserRepository, logger *slog.Logger) *UserService {
    return &UserService{repo: repo, logger: logger}
}

Context

  • context.Context is the first parameter of every service and repository method
  • Propagate context from handler through to DB call — never discard it
  • Use context.WithTimeout for external calls

HTTP Layer

  • Prefer net/http stdlib + chi router
  • Avoid heavy frameworks (no gin, no echo — keep it replaceable)
  • Use chi.URLParam(r, "id") for path params
  • Decode JSON body: json.NewDecoder(r.Body).Decode(&input) — always check error

Validation

Use go-playground/validator struct tags:

type CreateUserInput struct {
    Email string `json:"email" validate:"required,email"`
    Name  string `json:"name"  validate:"required,min=1,max=100"`
}

Validate in handler before calling service:

if err := validate.Struct(input); err != nil {
    // map to 400 response
}

Response Helpers

Use a shared package — never build envelope inline:

// internal/shared/response/response.go
func JSON(w http.ResponseWriter, status int, data any) { ... }
func Error(w http.ResponseWriter, status int, code, message string) { ... }

Logging

Use log/slog (stdlib, Go 1.21+):

slog.InfoContext(ctx, "user created", "userID", user.ID, "requestID", r.Header.Get("X-Request-Id"))

Log at service/handler boundary only. Repositories should not log.

Graceful Shutdown

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// start server, then wait on ctx.Done()

Concurrency

  • Use errgroup.Group for parallel work with error aggregation
  • Avoid raw goroutines without a WaitGroup or channel for synchronization
  • Always pass context.Context to goroutine work for cancellation

What NOT to do

  • No global variables for dependencies (db, logger, config) — inject via structs
  • No bare errors.New("something") in service or repository without wrapping caller context
  • No business logic in handlers
  • No SQL in services
  • No http.Request passed to services
  • No heavy frameworks replacing net/http
  • Never discard context — always propagate

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.