← 返回 Skills 市场
anderskev

Go Middleware

作者 Kevin Anderson · GitHub ↗ · v2.3.1 · MIT-0
cross-platform ✓ 安全检测通过
170
总下载
0
收藏
1
当前安装
2
版本数
在 OpenClaw 中安装
/install go-middleware
功能描述
Idiomatic Go HTTP middleware patterns with context propagation, structured logging via slog, centralized error handling, and panic recovery. Use when writing...
使用说明 (SKILL.md)

Go HTTP Middleware

Quick Reference

Topic Reference
Context keys, request IDs, user metadata references/context-propagation.md
slog setup, logging middleware, child loggers references/structured-logging.md
AppHandler pattern, domain errors, recovery references/error-handling-middleware.md

Middleware Signature

All middleware follows the standard func(http.Handler) http.Handler pattern. This is the composable building block for cross-cutting concerns in Go HTTP servers.

// Standard middleware signature
func RequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-ID")
        if id == "" {
            id = uuid.New().String()
        }
        ctx := context.WithValue(r.Context(), requestIDKey, id)
        w.Header().Set("X-Request-ID", id)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// Type-safe context keys
type contextKey string
const requestIDKey contextKey = "request_id"

func RequestIDFromContext(ctx context.Context) string {
    id, _ := ctx.Value(requestIDKey).(string)
    return id
}

Key points:

  • Accept http.Handler, return http.Handler -- always
  • Call next.ServeHTTP(w, r) to pass control to the next handler
  • Work before the call (pre-processing) or after (post-processing) or both
  • Use r.WithContext(ctx) to propagate new context values downstream

Context Propagation

Use context.WithValue for request-scoped data that crosses API boundaries (request IDs, authenticated users, tenant IDs). Always use typed keys to avoid collisions.

type contextKey string

const (
    requestIDKey contextKey = "request_id"
    userKey      contextKey = "user"
)

Provide typed helper functions for extraction:

func RequestIDFromContext(ctx context.Context) string {
    id, _ := ctx.Value(requestIDKey).(string)
    return id
}

See references/context-propagation.md for user metadata patterns, downstream propagation, and timeouts.

Structured Logging

Use slog (standard library, Go 1.21+) for structured logging in middleware. Wrap http.ResponseWriter to capture the status code.

func Logger(logger *slog.Logger) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            start := time.Now()
            wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}

            next.ServeHTTP(wrapped, r)

            logger.Info("request completed",
                "method", r.Method,
                "path", r.URL.Path,
                "status", wrapped.status,
                "duration_ms", time.Since(start).Milliseconds(),
                "request_id", RequestIDFromContext(r.Context()),
            )
        })
    }
}

See references/structured-logging.md for JSON/text handler setup, log levels, and child loggers.

Centralized Error Handling

Define a custom handler type that returns error so handlers don't need to write error responses themselves:

type AppHandler func(w http.ResponseWriter, r *http.Request) error

func (fn AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if err := fn(w, r); err != nil {
        handleError(w, r, err)
    }
}

Map domain errors to HTTP status codes in a single handleError function. Never leak internal error details to clients.

See references/error-handling-middleware.md for the full pattern with AppError, errors.As, and JSON responses.

Recovery Middleware

Catch panics to prevent a single bad request from crashing the server:

func Recovery(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if rec := recover(); rec != nil {
                slog.Error("panic recovered",
                    "panic", rec,
                    "stack", string(debug.Stack()),
                    "request_id", RequestIDFromContext(r.Context()),
                )
                writeJSON(w, 500, map[string]string{"error": "internal server error"})
            }
        }()
        next.ServeHTTP(w, r)
    })
}

Recovery must be the outermost middleware so it catches panics from all inner middleware and handlers. See references/error-handling-middleware.md for details.

Middleware Chain Ordering

Apply middleware outermost-first. The first middleware in the chain wraps all others.

// Nested style (outermost first)
handler := Recovery(
    RequestID(
        Logger(
            Auth(
                router,
            ),
        ),
    ),
)

// Or with a chain helper
func Chain(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
    for i := len(middleware) - 1; i >= 0; i-- {
        h = middleware[i](h)
    }
    return h
}

handler := Chain(router, Recovery, RequestID, Logger(slog.Default()), Auth)

Recommended Order

  1. Recovery -- outermost; catches panics from all inner middleware
  2. RequestID -- assign early so all subsequent middleware can reference it
  3. Logger -- logs the completed request with ID and status
  4. Auth -- after logging so failed auth attempts are recorded
  5. Application-specific middleware -- rate limiting, CORS, etc.

Gates (check before merge or review)

Use these sequenced checks for objective pass/fail; do not replace them with “I verified mentally.”

  1. Recovery position
    • Locate where the server builds the middleware chain (e.g. main, router Use, or a Chain helper).
    • Pass: Recovery wraps all other middleware and the final handler per Middleware Chain Ordering (outermost in nested style, or correct Chain argument order for your helper). Cite file path and the full chain snippet.
  2. Status-aware middleware uses a wrapped ResponseWriter
    • If middleware logs or records HTTP status after the handler runs, it must pass a wrapper into next.ServeHTTP, not the original writer alone.
    • Pass: snippet shows next.ServeHTTP(wrapped, r) (or equivalent) when status is observed after next returns.
  3. Every forward path calls next
    • Scan each middleware’s control flow.
    • Pass: no branch drops the request without calling next.ServeHTTP unless that branch intentionally sends a response (e.g. auth failure); those short-circuits are obvious in code review.

Anti-patterns

Using string or int context keys

// BAD: collisions with other packages
ctx = context.WithValue(ctx, "user", user)

// GOOD: unexported typed key
type contextKey string
const userKey contextKey = "user"
ctx = context.WithValue(ctx, userKey, user)

Writing response before calling next

// BAD: writes response then continues chain
func Bad(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK) // too early!
        next.ServeHTTP(w, r)
    })
}

Forgetting to call next.ServeHTTP

// BAD: swallows the request
func Bad(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println("got request")
        // forgot next.ServeHTTP(w, r)
    })
}

Storing large objects in context

Context values should be small, request-scoped metadata (IDs, tokens, user structs). Never store database connections, file handles, or large payloads.

Using context.WithValue for function parameters

If a function needs a value to do its job, pass it as an explicit parameter. Context is for cross-cutting metadata that passes through APIs, not for avoiding function signatures.

Recovery middleware in the wrong position

If recovery is not the outermost middleware, panics in outer middleware will crash the server. Always apply recovery first.

安全使用建议
This skill is a documentation-only guide for Go HTTP middleware and appears internally consistent. Before installing/using it in production, consider: (1) provenance — the source/homepage are missing (verify the author or prefer a known upstream library/repo), (2) licensing — check if the snippets carry a license you can use, and (3) integration details — examples show propagating request IDs to downstream HTTP calls and logging; ensure you do not accidentally log sensitive fields (the docs already warn about that). Because it’s documentation-only, it cannot execute code by itself, but copy-pasted snippets should be reviewed and tested in your codebase.
能力标签
cryptocan-make-purchases
能力评估
Purpose & Capability
The name/description match the SKILL.md and the three reference documents. There are no unexpected binaries, env vars, or config paths requested — everything in the files is about middleware, context, logging, error handling, and recovery, which is consistent with the stated purpose.
Instruction Scope
Runtime instructions and code examples are narrowly scoped to implementing middleware patterns (RequestID, Logger, Recovery, AppHandler, context usage, etc.). Examples showing propagation to downstream HTTP calls are normal for middleware docs. The instructions do not direct reading unrelated files, harvesting environment variables, or sending data to unknown external endpoints.
Install Mechanism
This is an instruction-only skill with no install spec and no code files to execute. That presents minimal installation risk — nothing is downloaded or written to disk by the skill itself.
Credentials
The skill declares no required environment variables or credentials. The docs show typical use of an environment string to select logger configuration, which is reasonable and proportional to the topic.
Persistence & Privilege
The skill does not request always:true, does not modify other skills or system settings, and does not require persistent presence. Default autonomous invocation settings are unchanged and appropriate for an instruction-only skill.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install go-middleware
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /go-middleware 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v2.3.1
- Added a new "Gates (check before merge or review)" section outlining sequenced, objective checks for middleware correctness. - Gates cover: Recovery middleware position; proper use of response writer wrappers; and ensuring all middleware call `next.ServeHTTP` in every forward path. - No logic/code changes; documentation only. - Existing anti-patterns, middleware signature, and usage patterns remain unchanged.
v2.3.0
- Added a comprehensive SKILL.md with detailed documentation and best practices for Go HTTP middleware. - Covers context propagation, structured logging with slog, centralized error handling, and recovery middleware. - Provides code samples, recommended middleware chain order, and anti-patterns to avoid. - Includes quick references to more in-depth documentation for each major topic.
元数据
Slug go-middleware
版本 2.3.1
许可证 MIT-0
累计安装 1
当前安装数 1
历史版本数 2
常见问题

Go Middleware 是什么?

Idiomatic Go HTTP middleware patterns with context propagation, structured logging via slog, centralized error handling, and panic recovery. Use when writing... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 170 次。

如何安装 Go Middleware?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install go-middleware」即可一键安装,无需额外配置。

Go Middleware 是免费的吗?

是的,Go Middleware 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Go Middleware 支持哪些平台?

Go Middleware 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Go Middleware?

由 Kevin Anderson(@anderskev)开发并维护,当前版本 v2.3.1。

💬 留言讨论