package reqlog import ( "bufio" "errors" "fmt" "net" "net/http" "strconv" "strings" "time" ) // SkipFunc 返回 true 时该请求不记录(静态资源、日志接口自身等)。 type SkipFunc func(*http.Request) bool // Middleware 记录每个请求的元数据。请求处理过程中业务代码可以通过 // context 上的 Record 补充账号、模型、上游错误等信息。 func Middleware(store *Store, skip SkipFunc) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if store == nil || (skip != nil && skip(r)) { next.ServeHTTP(w, r) return } rec := &Record{e: Entry{ Time: time.Now().Format("2006-01-02T15:04:05.000Z07:00"), Level: LevelInfo, Method: r.Method, Path: r.URL.Path, }} rec.e.ClientIP = clientIP(r) rec.e.UserAgent = truncate(r.UserAgent(), 200) if r.ContentLength > 0 { rec.e.ReqBytes = r.ContentLength } if v := strings.TrimSpace(r.Header.Get("X-Ds2-Source")); v != "" { rec.e.UserAgent = truncate(v+" | "+rec.e.UserAgent, 200) } if raw := bearerToken(r); raw != "" { rec.e.APIKey = MaskKey(raw) } start := time.Now() ww := &responseWriter{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(ww, r.WithContext(WithRecord(r.Context(), rec))) latency := time.Since(start) entry := rec.Snapshot() entry.Status = ww.status entry.LatencyMS = latency.Milliseconds() entry.RespBytes = ww.written if code := strings.TrimSpace(ww.Header().Get("X-Ds2-Error-Code")); code != "" { entry.ErrorCode = code } if entry.Status >= 500 { entry.Level = LevelError } else if entry.Status >= 400 { entry.Level = LevelWarn } store.Add(entry) }) } } func clientIP(r *http.Request) string { if r == nil { return "" } if ip := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); ip != "" { if idx := strings.IndexByte(ip, ','); idx >= 0 { ip = ip[:idx] } return strings.TrimSpace(ip) } if ip := strings.TrimSpace(r.Header.Get("X-Real-Ip")); ip != "" { return ip } host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)) if err != nil { return r.RemoteAddr } return host } func bearerToken(r *http.Request) string { auth := strings.TrimSpace(r.Header.Get("Authorization")) if len(auth) > 7 && strings.EqualFold(auth[:7], "bearer ") { return strings.TrimSpace(auth[7:]) } if key := strings.TrimSpace(r.Header.Get("X-Api-Key")); key != "" { return key } if key := strings.TrimSpace(r.Header.Get("X-Goog-Api-Key")); key != "" { return key } if key := strings.TrimSpace(r.URL.Query().Get("key")); key != "" && strings.HasPrefix(key, "ds2log_") { return key } return "" } type responseWriter struct { http.ResponseWriter status int written int64 wroteHeader bool } func (w *responseWriter) WriteHeader(status int) { if w.wroteHeader { return } w.status = status w.wroteHeader = true w.ResponseWriter.WriteHeader(status) } func (w *responseWriter) Write(b []byte) (int, error) { if !w.wroteHeader { w.WriteHeader(http.StatusOK) } n, err := w.ResponseWriter.Write(b) w.written += int64(n) return n, err } func (w *responseWriter) Flush() { if f, ok := w.ResponseWriter.(http.Flusher); ok { f.Flush() } } func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { h, ok := w.ResponseWriter.(http.Hijacker) if !ok { return nil, nil, errors.New("hijacking not supported") } return h.Hijack() } func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } // ParseLimit 统一解析 limit 参数,限制在 [1, max] 区间。 func ParseLimit(raw string, def, max int) int { v, err := strconv.Atoi(strings.TrimSpace(raw)) if err != nil || v <= 0 { return def } if v > max { return max } return v } func (w *responseWriter) String() string { return fmt.Sprintf("status=%d bytes=%d", w.status, w.written) }