|
| 1 | +package webserver |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + "sync" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +/* High performance access logging. */ |
| 14 | + |
| 15 | +const accessLogInitialGrow = 512 |
| 16 | + |
| 17 | +// captureWriter records status and body size for access logging. |
| 18 | +type captureWriter struct { |
| 19 | + http.ResponseWriter |
| 20 | + |
| 21 | + start time.Time |
| 22 | + status int |
| 23 | + size int64 |
| 24 | +} |
| 25 | + |
| 26 | +func (c *captureWriter) WriteHeader(code int) { |
| 27 | + if c.status == 0 { |
| 28 | + c.status = code |
| 29 | + } |
| 30 | + |
| 31 | + c.ResponseWriter.WriteHeader(code) |
| 32 | +} |
| 33 | + |
| 34 | +func (c *captureWriter) Write(p []byte) (int, error) { |
| 35 | + if c.status == 0 { |
| 36 | + c.status = http.StatusOK |
| 37 | + } |
| 38 | + |
| 39 | + n, err := c.ResponseWriter.Write(p) |
| 40 | + c.size += int64(n) |
| 41 | + |
| 42 | + return n, err //nolint:wrapcheck // delegate to underlying ResponseWriter |
| 43 | +} |
| 44 | + |
| 45 | +func (c *captureWriter) statusCode() int { |
| 46 | + if c.status == 0 { |
| 47 | + return http.StatusOK |
| 48 | + } |
| 49 | + |
| 50 | + return c.status |
| 51 | +} |
| 52 | + |
| 53 | +// Get returns the first value for a response header field. key must already be in |
| 54 | +// canonical form (http.CanonicalHeaderKey). Unlike Header.Get it does not allocate |
| 55 | +// or re-canonicalize key on each call. |
| 56 | +func (c *captureWriter) Get(key string) string { |
| 57 | + if v := c.Header()[key]; len(v) > 0 { |
| 58 | + return v[0] |
| 59 | + } |
| 60 | + |
| 61 | + return "" |
| 62 | +} |
| 63 | + |
| 64 | +//nolint:gochecknoglobals // one pool per process for hot-path access log strings.Builder reuse |
| 65 | +var alBuilder = sync.Pool{New: func() any { return &strings.Builder{} }} |
| 66 | + |
| 67 | +// accessLogWrap writes one Apache-style line per request to dst (same field order as the former alFmt). |
| 68 | +func accessLogWrap(next http.Handler, dst io.Writer) http.Handler { |
| 69 | + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 70 | + capture := &captureWriter{ResponseWriter: w, start: time.Now()} |
| 71 | + next.ServeHTTP(capture, req) |
| 72 | + capture.writeAccessLogLine(req, dst) |
| 73 | + }) |
| 74 | +} |
| 75 | + |
| 76 | +func (c *captureWriter) writeAccessLogLine(req *http.Request, dst io.Writer) { |
| 77 | + //nolint:forcetypeassert |
| 78 | + builder := alBuilder.Get().(*strings.Builder) // Get a string buffer: |
| 79 | + builder.Reset() // - reset it. |
| 80 | + builder.Grow(accessLogInitialGrow) // - grow it. |
| 81 | + c.writeAccessLogLinePrefix(builder, req) // - fill prefix. |
| 82 | + c.writeAccessLogLineTail(builder, req) // - fill suffix. |
| 83 | + _, _ = io.WriteString(dst, builder.String()) // - write it. |
| 84 | + alBuilder.Put(builder) // - put it back. |
| 85 | +} |
| 86 | + |
| 87 | +func (c *captureWriter) writeAccessLogLinePrefix(builder *strings.Builder, req *http.Request) { |
| 88 | + // %V |
| 89 | + builder.WriteString(req.Host) |
| 90 | + builder.WriteByte(' ') |
| 91 | + // %{X-Forwarded-For}i — computed like former fixForwardedFor (not raw header). |
| 92 | + builder.WriteString(ClientIPForLog(req)) |
| 93 | + builder.WriteByte(' ') |
| 94 | + // "%{X-Username}o" |
| 95 | + builder.WriteByte('"') |
| 96 | + builder.WriteString(c.Get("X-Username")) |
| 97 | + builder.WriteString("\" ") |
| 98 | + // %{X-UserID}o |
| 99 | + builder.WriteString(c.Get("X-Userid")) |
| 100 | + builder.WriteByte(' ') |
| 101 | + // %t — [02/Jan/2006:15:04:05 -0700] |
| 102 | + builder.WriteByte('[') |
| 103 | + builder.WriteString(c.start.Format("02/Jan/2006:15:04:05 -0700")) |
| 104 | + builder.WriteString("] ") |
| 105 | + // "%r" |
| 106 | + builder.WriteByte('"') |
| 107 | + builder.WriteString(req.Method) |
| 108 | + builder.WriteByte(' ') |
| 109 | + |
| 110 | + if req.RequestURI != "" { |
| 111 | + builder.WriteString(req.RequestURI) |
| 112 | + } else { |
| 113 | + builder.WriteString(req.URL.RequestURI()) |
| 114 | + } |
| 115 | + |
| 116 | + builder.WriteString(" HTTP/1.1\" ") |
| 117 | + // %>s |
| 118 | + builder.WriteString(strconv.Itoa(c.statusCode())) |
| 119 | + builder.WriteByte(' ') |
| 120 | + // %b — response body size (0 when none). |
| 121 | + builder.WriteString(strconv.FormatInt(c.size, 10)) |
| 122 | + |
| 123 | + builder.WriteByte(' ') |
| 124 | + // "%{Referer}i" "%{User-agent}i" query:... |
| 125 | + builder.WriteByte('"') |
| 126 | + builder.WriteString(RefererPathForLog(req.Header)) |
| 127 | + builder.WriteString("\" \"") |
| 128 | + builder.WriteString(req.UserAgent()) |
| 129 | + builder.WriteByte('"') |
| 130 | +} |
| 131 | + |
| 132 | +func (c *captureWriter) writeAccessLogLineTail(builder *strings.Builder, req *http.Request) { |
| 133 | + builder.WriteString(" req:") |
| 134 | + // %{ms}T — elapsed milliseconds (same as apache-logformat request duration). |
| 135 | + builder.WriteString(strconv.FormatInt(time.Since(c.start).Milliseconds(), 10)) |
| 136 | + builder.WriteString("ms age:") |
| 137 | + builder.WriteString(c.Get("Age")) |
| 138 | + builder.WriteString(" env:") |
| 139 | + builder.WriteString(c.Get("X-Environment")) |
| 140 | + builder.WriteString(" key:") |
| 141 | + |
| 142 | + masked, keyLenStr := c.maskedAPIKeyFromResponse() |
| 143 | + builder.WriteString(masked) |
| 144 | + builder.WriteByte('(') |
| 145 | + builder.WriteString(keyLenStr) |
| 146 | + builder.WriteString(") \"srv:") |
| 147 | + builder.WriteString(req.Header.Get("X-Server")) |
| 148 | + builder.WriteString("\"\n") |
| 149 | +} |
| 150 | + |
| 151 | +// maskedAPIKeyFromResponse returns maskAPIKey(w X-Api-Key) for the access log, or ("", "") |
| 152 | +// when the handler did not set that response header. |
| 153 | +func (c *captureWriter) maskedAPIKeyFromResponse() (string, string) { |
| 154 | + key := c.Get("X-Api-Key") |
| 155 | + if key == "" { |
| 156 | + return "", "" |
| 157 | + } |
| 158 | + |
| 159 | + return maskAPIKey(key) |
| 160 | +} |
| 161 | + |
| 162 | +// RefererPathForLog returns the path part of X-Original-Uri (no query string) truncated before the |
| 163 | +// API key segment (keyPosition), using the same strings.Split(path, "/") rules as GetAPIKeyFromURIPath. |
| 164 | +// If the path has fewer than keyPosition+1 segments, it returns the full path (still without query). |
| 165 | +// When X-Original-Uri is missing, empty, or only a query string, it returns "". |
| 166 | +func RefererPathForLog(header http.Header) string { |
| 167 | + pathPart, _, _ := strings.Cut(header.Get("X-Original-Uri"), "?") |
| 168 | + if pathPart == "" { |
| 169 | + return "" |
| 170 | + } |
| 171 | + |
| 172 | + var pos, segIdx int |
| 173 | + |
| 174 | + for seg := range strings.SplitSeq(pathPart, "/") { |
| 175 | + if segIdx == keyPosition { |
| 176 | + return strings.TrimSuffix(pathPart[:pos], "/") |
| 177 | + } |
| 178 | + |
| 179 | + pos += len(seg) |
| 180 | + if pos < len(pathPart) && pathPart[pos] == '/' { |
| 181 | + pos++ |
| 182 | + } |
| 183 | + |
| 184 | + segIdx++ |
| 185 | + } |
| 186 | + |
| 187 | + return pathPart |
| 188 | +} |
| 189 | + |
| 190 | +// ClientIPForLog returns the client IP for access logs (same rules as the former fixForwardedFor middleware). |
| 191 | +func ClientIPForLog(req *http.Request) string { |
| 192 | + forwarded := req.Header.Get("X-Forwarded-For") |
| 193 | + if forwarded == "" { |
| 194 | + host, _, err := net.SplitHostPort(req.RemoteAddr) |
| 195 | + if err != nil { |
| 196 | + return strings.Trim(req.RemoteAddr, "[]") |
| 197 | + } |
| 198 | + |
| 199 | + return host |
| 200 | + } |
| 201 | + |
| 202 | + return strings.TrimSpace(strings.Split(forwarded, ",")[0]) |
| 203 | +} |
0 commit comments