File size: 4,001 Bytes
7e312e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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)
}