Fiber Logging And Project Structure Skill
Project Structure (Standard Go Layout)
- Organize all Fiber applications using:
cmd/<appname>/main.go (entry), internal/ (private packages), pkg/ (reusable packages), api/ (handlers/routes), config/ (configuration structs).
- Never put business logic in
cmd/ — keep main.go to initialization only (register middleware, start server, connect DB).
- Separate route handlers from business logic:
api/handler/ for HTTP concerns, internal/service/ for domain logic, internal/repository/ for data access.
Logging
- Use structured logging:
zerolog (preferred for Fiber) or zap. Never use fmt.Println or stdlib log in production handlers.
- Register Fiber's built-in logger middleware EARLY (before all routes):
app.Use(logger.New()).
- Fiber v3 logger middleware: import from
github.com/gofiber/fiber/v3/middleware/logger.
- Add correlation IDs in middleware using
ctx.Locals("requestID", uuid.New()) and include in every log entry.
- Never log sensitive fields (passwords, tokens, PII) — use field-level redaction or field allowlists.
Middleware Registration Order
- Register global middleware before routes: Logger → RequestID → CORS → RateLimiter → Auth → Routes.
- Middleware registered via
app.Use() applies to all subsequent routes; placement matters.
- Route-specific middleware: apply as a second argument to
app.Get("/path", authMiddleware, handler).
Environment Configuration
- Load config at startup via
viper, envconfig, or godotenv — never read os.Getenv() scattered in handlers.
- Define a typed config struct:
type Config struct { Port string \env:"PORT" envDefault:"3000"` }`.
- Provide
.env.example with all required variables; never commit .env files.
- Fail fast on missing required config: panic or
log.Fatal during startup if required env vars are absent.
Error Handling
- Return
fiber.NewError(fiber.StatusBadRequest, "message") from handlers for HTTP errors.
- Use a global error handler via
app.Config().ErrorHandler to produce consistent JSON error responses.
- Never expose internal error details or stack traces in production error responses.
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/requestid"
"myapp/internal/config"
"myapp/api/routes"
)
func main() {
cfg := config.Load() // typed config, fails fast on missing vars
app := fiber.New(fiber.Config{
ErrorHandler: func(c *fiber.Ctx, err error) error {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
},
})
// Middleware: register BEFORE routes
app.Use(requestid.New())
app.Use(logger.New(logger.Config{
Format: "${time} ${method} ${path} ${status} ${latency}\n",
}))
routes.Register(app) // all routes in internal/api/routes/
log.Fatal(app.Listen(cfg.Port))
}
// internal/config/config.go — typed config
type Config struct {
Port string `env:"PORT" envDefault:":3000"`
DBUrl string `env:"DATABASE_URL,required"`
}
</examples>
## Iron Laws
1. **ALWAYS** use structured logging (zerolog or logrus with JSON output) — never use `fmt.Println` or `log.Printf` in production Fiber applications; unstructured logs cannot be parsed by log aggregators.
2. **NEVER** put business logic in route handlers — always call a service/controller layer; route handlers must only handle HTTP concerns (parsing, validation, response writing).
3. **ALWAYS** use Fiber's `ctx.Locals()` for request-scoped values (user ID, trace ID) — never pass request-scoped data via global variables or function parameters down the call stack.
4. **NEVER** commit sensitive configuration directly in code — use `envconfig`, `viper`, or environment variables with a `.env.example` template; loaded secrets must never appear in logs.
5. **ALWAYS** organize project structure into `cmd/`, `internal/`, `pkg/` conventions — Fiber projects that put all code in root packages become unmaintainable at scale.
## Anti-Patterns
| Anti-Pattern | Why It Fails | Correct Approach |
| ------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `fmt.Println` for logging in Fiber handlers | Unstructured; no log levels; no correlation IDs; breaks log aggregation | Use zerolog or logrus with `zap.String("key", value)` structured fields |
| Business logic in route handlers | Logic becomes untestable and non-reusable; couples HTTP layer to domain | Move to service layer; handler calls service method, formats response |
| Global state for request context | Concurrent requests overwrite each other's context; race conditions | Use `ctx.Locals("key", value)` for all request-scoped data |
| Hardcoded config values | No environment-specific deployments; credentials in source history | Use `envconfig` or `viper` with `.env.example`; never commit real values |
| All files in project root | Impossible to separate public/internal APIs; package import cycles | Use standard Go layout: `cmd/`, `internal/`, `pkg/`, `api/` |
## Memory Protocol (MANDATORY)
**Before starting:**
```bash
cat .claude/context/memory/learnings.md
After completing: Record any new patterns or exceptions discovered.
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
1---2name: fiber-logging-and-project-structure3version: 1.2.04verified: true5lastVerifiedAt: '2026-03-01'6category: 'Frameworks'7agents: [developer, golang-pro]8tags: [fiber, go, logging, structure, middleware, zerolog, viper, clean-architecture]9description: Applies best practices for logging (zerolog/zap), project structure (cmd/internal/pkg), middleware registration order, and environment configuration in Go Fiber v2/v3 applications.10model: sonnet11invoked_by: both12user_invocable: true13tools: [Read, Write, Edit]14globs: cmd/main.go15best_practices:16 - Follow the guidelines consistently17 - Apply rules during code review18 - Use as reference when writing new code19error_handling: graceful20streaming: supported21source: builtin22trust_score: 10023provenance_sha: 6f97772f668a260724metadata:25 source: https://skillmd.com/skills/oimiragieo/fiber-logging-and-project-structure26---2728# Fiber Logging And Project Structure Skill2930<identity>31You are a coding standards expert specializing in fiber logging and project structure.32You help developers write better code by applying established guidelines and best practices.33</identity>3435<capabilities>36- Review code for guideline compliance37- Suggest improvements based on best practices38- Explain why certain patterns are preferred39- Help refactor code to meet standards40</capabilities>4142<instructions>43When reviewing or writing Go Fiber code, apply these guidelines:4445**Project Structure (Standard Go Layout)**4647- Organize all Fiber applications using: `cmd/<appname>/main.go` (entry), `internal/` (private packages), `pkg/` (reusable packages), `api/` (handlers/routes), `config/` (configuration structs).48- Never put business logic in `cmd/` — keep `main.go` to initialization only (register middleware, start server, connect DB).49- Separate route handlers from business logic: `api/handler/` for HTTP concerns, `internal/service/` for domain logic, `internal/repository/` for data access.5051**Logging**5253- Use structured logging: `zerolog` (preferred for Fiber) or `zap`. Never use `fmt.Println` or stdlib `log` in production handlers.54- Register Fiber's built-in logger middleware EARLY (before all routes): `app.Use(logger.New())`.55- Fiber v3 logger middleware: import from `github.com/gofiber/fiber/v3/middleware/logger`.56- Add correlation IDs in middleware using `ctx.Locals("requestID", uuid.New())` and include in every log entry.57- Never log sensitive fields (passwords, tokens, PII) — use field-level redaction or field allowlists.5859**Middleware Registration Order**6061- Register global middleware before routes: Logger → RequestID → CORS → RateLimiter → Auth → Routes.62- Middleware registered via `app.Use()` applies to all subsequent routes; placement matters.63- Route-specific middleware: apply as a second argument to `app.Get("/path", authMiddleware, handler)`.6465**Environment Configuration**6667- Load config at startup via `viper`, `envconfig`, or `godotenv` — never read `os.Getenv()` scattered in handlers.68- Define a typed config struct: `type Config struct { Port string \`env:"PORT" envDefault:"3000"\` }`.69- Provide `.env.example` with all required variables; never commit `.env` files.70- Fail fast on missing required config: panic or `log.Fatal` during startup if required env vars are absent.7172**Error Handling**7374- Return `fiber.NewError(fiber.StatusBadRequest, "message")` from handlers for HTTP errors.75- Use a global error handler via `app.Config().ErrorHandler` to produce consistent JSON error responses.76- Never expose internal error details or stack traces in production error responses.77 </instructions>7879<examples>80```go81// cmd/api/main.go — minimal correct Fiber v2 entry point82package main8384import (85"log"86"github.com/gofiber/fiber/v2"87"github.com/gofiber/fiber/v2/middleware/logger"88"github.com/gofiber/fiber/v2/middleware/requestid"89"myapp/internal/config"90"myapp/api/routes"91)9293func main() {94cfg := config.Load() // typed config, fails fast on missing vars9596 app := fiber.New(fiber.Config{97 ErrorHandler: func(c *fiber.Ctx, err error) error {98 return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})99 },100 })101102 // Middleware: register BEFORE routes103 app.Use(requestid.New())104 app.Use(logger.New(logger.Config{105 Format: "${time} ${method} ${path} ${status} ${latency}\n",106 }))107108 routes.Register(app) // all routes in internal/api/routes/109 log.Fatal(app.Listen(cfg.Port))110111}112113// internal/config/config.go — typed config114type Config struct {115Port string \`env:"PORT" envDefault:":3000"\`116DBUrl string \`env:"DATABASE_URL,required"\`117}118119````120</examples>121122## Iron Laws1231241. **ALWAYS** use structured logging (zerolog or logrus with JSON output) — never use `fmt.Println` or `log.Printf` in production Fiber applications; unstructured logs cannot be parsed by log aggregators.1252. **NEVER** put business logic in route handlers — always call a service/controller layer; route handlers must only handle HTTP concerns (parsing, validation, response writing).1263. **ALWAYS** use Fiber's `ctx.Locals()` for request-scoped values (user ID, trace ID) — never pass request-scoped data via global variables or function parameters down the call stack.1274. **NEVER** commit sensitive configuration directly in code — use `envconfig`, `viper`, or environment variables with a `.env.example` template; loaded secrets must never appear in logs.1285. **ALWAYS** organize project structure into `cmd/`, `internal/`, `pkg/` conventions — Fiber projects that put all code in root packages become unmaintainable at scale.129130## Anti-Patterns131132| Anti-Pattern | Why It Fails | Correct Approach |133| ------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------ |134| `fmt.Println` for logging in Fiber handlers | Unstructured; no log levels; no correlation IDs; breaks log aggregation | Use zerolog or logrus with `zap.String("key", value)` structured fields |135| Business logic in route handlers | Logic becomes untestable and non-reusable; couples HTTP layer to domain | Move to service layer; handler calls service method, formats response |136| Global state for request context | Concurrent requests overwrite each other's context; race conditions | Use `ctx.Locals("key", value)` for all request-scoped data |137| Hardcoded config values | No environment-specific deployments; credentials in source history | Use `envconfig` or `viper` with `.env.example`; never commit real values |138| All files in project root | Impossible to separate public/internal APIs; package import cycles | Use standard Go layout: `cmd/`, `internal/`, `pkg/`, `api/` |139140## Memory Protocol (MANDATORY)141142**Before starting:**143144```bash145cat .claude/context/memory/learnings.md146````147148**After completing:** Record any new patterns or exceptions discovered.149150> ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.