A collection of Gin middleware handlers providing request ID tracking, client IP capture, timeouts, and security headers. Reuse for backend API scaffolding.
// Source: https://github.com/chenyme/grok2api | License: MIT | Copyright 2026 Chenyme
// Provided via justclaw.it.com; keep this notice with the code.
package middleware
import (
"context"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/chenyme/grok2api/backend/internal/infra/security"
"github.com/chenyme/grok2api/backend/internal/pkg/requestmeta"
"github.com/gin-gonic/gin"
)
const RequestIDKey = "requestId"
const maxRequestIDLength = 64
// RequestID 为每个请求生成稳定关联 ID,并写入响应头。
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
requestID := strings.TrimSpace(c.GetHeader("X-Request-ID"))
if !validRequestID(requestID) {
requestID, _ = security.NewOpaqueToken(12)
if requestID == "" {
requestID = "req-" + strconv.FormatInt(time.Now().UnixNano(
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key