| 1 |
// Copyright 2013 The Gorilla Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package handlers |
| 6 |
|
| 7 |
import ( |
| 8 |
"io" |
| 9 |
"net" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"strconv" |
| 13 |
"time" |
| 14 |
"unicode/utf8" |
| 15 |
|
| 16 |
"github.com/felixge/httpsnoop" |
| 17 |
) |
| 18 |
|
| 19 |
// Logging |
| 20 |
|
| 21 |
// LogFormatterParams is the structure any formatter will be handed when time to log comes. |
| 22 |
type LogFormatterParams struct { |
| 23 |
Request *http.Request |
| 24 |
URL url.URL |
| 25 |
TimeStamp time.Time |
| 26 |
StatusCode int |
| 27 |
Size int |
| 28 |
} |
| 29 |
|
| 30 |
// LogFormatter gives the signature of the formatter function passed to CustomLoggingHandler. |
| 31 |
type LogFormatter func(writer io.Writer, params LogFormatterParams) |
| 32 |
|
| 33 |
// loggingHandler is the http.Handler implementation for LoggingHandlerTo and its |
| 34 |
// friends |
| 35 |
|
| 36 |
type loggingHandler struct { |
| 37 |
writer io.Writer |
| 38 |
handler http.Handler |
| 39 |
formatter LogFormatter |
| 40 |
} |
| 41 |
|
| 42 |
func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 43 |
t := time.Now() |
| 44 |
logger, w := makeLogger(w) |
| 45 |
url := *req.URL |
| 46 |
|
| 47 |
h.handler.ServeHTTP(w, req) |
| 48 |
if req.MultipartForm != nil { |
| 49 |
err := req.MultipartForm.RemoveAll() |
| 50 |
if err != nil { |
| 51 |
return |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
params := LogFormatterParams{ |
| 56 |
Request: req, |
| 57 |
URL: url, |
| 58 |
TimeStamp: t, |
| 59 |
StatusCode: logger.Status(), |
| 60 |
Size: logger.Size(), |
| 61 |
} |
| 62 |
|
| 63 |
h.formatter(h.writer, params) |
| 64 |
} |
| 65 |
|
| 66 |
func makeLogger(w http.ResponseWriter) (*responseLogger, http.ResponseWriter) { |
| 67 |
logger := &responseLogger{w: w, status: http.StatusOK} |
| 68 |
return logger, httpsnoop.Wrap(w, httpsnoop.Hooks{ |
| 69 |
Write: func(httpsnoop.WriteFunc) httpsnoop.WriteFunc { |
| 70 |
return logger.Write |
| 71 |
}, |
| 72 |
WriteHeader: func(httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc { |
| 73 |
return logger.WriteHeader |
| 74 |
}, |
| 75 |
}) |
| 76 |
} |
| 77 |
|
| 78 |
const lowerhex = "0123456789abcdef" |
| 79 |
|
| 80 |
func appendQuoted(buf []byte, s string) []byte { |
| 81 |
var runeTmp [utf8.UTFMax]byte |
| 82 |
for width := 0; len(s) > 0; s = s[width:] { //nolint: wastedassign //TODO: why width starts from 0and reassigned as 1 |
| 83 |
r := rune(s[0]) |
| 84 |
width = 1 |
| 85 |
if r >= utf8.RuneSelf { |
| 86 |
r, width = utf8.DecodeRuneInString(s) |
| 87 |
} |
| 88 |
if width == 1 && r == utf8.RuneError { |
| 89 |
buf = append(buf, `\x`...) |
| 90 |
buf = append(buf, lowerhex[s[0]>>4]) |
| 91 |
buf = append(buf, lowerhex[s[0]&0xF]) |
| 92 |
continue |
| 93 |
} |
| 94 |
if r == rune('"') || r == '\\' { // always backslashed |
| 95 |
buf = append(buf, '\\') |
| 96 |
buf = append(buf, byte(r)) |
| 97 |
continue |
| 98 |
} |
| 99 |
if strconv.IsPrint(r) { |
| 100 |
n := utf8.EncodeRune(runeTmp[:], r) |
| 101 |
buf = append(buf, runeTmp[:n]...) |
| 102 |
continue |
| 103 |
} |
| 104 |
switch r { |
| 105 |
case '\a': |
| 106 |
buf = append(buf, `\a`...) |
| 107 |
case '\b': |
| 108 |
buf = append(buf, `\b`...) |
| 109 |
case '\f': |
| 110 |
buf = append(buf, `\f`...) |
| 111 |
case '\n': |
| 112 |
buf = append(buf, `\n`...) |
| 113 |
case '\r': |
| 114 |
buf = append(buf, `\r`...) |
| 115 |
case '\t': |
| 116 |
buf = append(buf, `\t`...) |
| 117 |
case '\v': |
| 118 |
buf = append(buf, `\v`...) |
| 119 |
default: |
| 120 |
switch { |
| 121 |
case r < ' ': |
| 122 |
buf = append(buf, `\x`...) |
| 123 |
buf = append(buf, lowerhex[s[0]>>4]) |
| 124 |
buf = append(buf, lowerhex[s[0]&0xF]) |
| 125 |
case r > utf8.MaxRune: |
| 126 |
r = 0xFFFD |
| 127 |
fallthrough |
| 128 |
case r < 0x10000: |
| 129 |
buf = append(buf, `\u`...) |
| 130 |
for s := 12; s >= 0; s -= 4 { |
| 131 |
buf = append(buf, lowerhex[r>>uint(s)&0xF]) |
| 132 |
} |
| 133 |
default: |
| 134 |
buf = append(buf, `\U`...) |
| 135 |
for s := 28; s >= 0; s -= 4 { |
| 136 |
buf = append(buf, lowerhex[r>>uint(s)&0xF]) |
| 137 |
} |
| 138 |
} |
| 139 |
} |
| 140 |
} |
| 141 |
return buf |
| 142 |
} |
| 143 |
|
| 144 |
// buildCommonLogLine builds a log entry for req in Apache Common Log Format. |
| 145 |
// ts is the timestamp with which the entry should be logged. |
| 146 |
// status and size are used to provide the response HTTP status and size. |
| 147 |
func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte { |
| 148 |
username := "-" |
| 149 |
if url.User != nil { |
| 150 |
if name := url.User.Username(); name != "" { |
| 151 |
username = name |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
host, _, err := net.SplitHostPort(req.RemoteAddr) |
| 156 |
if err != nil { |
| 157 |
host = req.RemoteAddr |
| 158 |
} |
| 159 |
|
| 160 |
uri := req.RequestURI |
| 161 |
|
| 162 |
// Requests using the CONNECT method over HTTP/2.0 must use |
| 163 |
// the authority field (aka r.Host) to identify the target. |
| 164 |
// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT |
| 165 |
if req.ProtoMajor == 2 && req.Method == "CONNECT" { |
| 166 |
uri = req.Host |
| 167 |
} |
| 168 |
if uri == "" { |
| 169 |
uri = url.RequestURI() |
| 170 |
} |
| 171 |
|
| 172 |
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2) |
| 173 |
buf = append(buf, host...) |
| 174 |
buf = append(buf, " - "...) |
| 175 |
buf = append(buf, username...) |
| 176 |
buf = append(buf, " ["...) |
| 177 |
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...) |
| 178 |
buf = append(buf, `] "`...) |
| 179 |
buf = append(buf, req.Method...) |
| 180 |
buf = append(buf, " "...) |
| 181 |
buf = appendQuoted(buf, uri) |
| 182 |
buf = append(buf, " "...) |
| 183 |
buf = append(buf, req.Proto...) |
| 184 |
buf = append(buf, `" `...) |
| 185 |
buf = append(buf, strconv.Itoa(status)...) |
| 186 |
buf = append(buf, " "...) |
| 187 |
buf = append(buf, strconv.Itoa(size)...) |
| 188 |
return buf |
| 189 |
} |
| 190 |
|
| 191 |
// writeLog writes a log entry for req to w in Apache Common Log Format. |
| 192 |
// ts is the timestamp with which the entry should be logged. |
| 193 |
// status and size are used to provide the response HTTP status and size. |
| 194 |
func writeLog(writer io.Writer, params LogFormatterParams) { |
| 195 |
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size) |
| 196 |
buf = append(buf, '\n') |
| 197 |
_, _ = writer.Write(buf) |
| 198 |
} |
| 199 |
|
| 200 |
// writeCombinedLog writes a log entry for req to w in Apache Combined Log Format. |
| 201 |
// ts is the timestamp with which the entry should be logged. |
| 202 |
// status and size are used to provide the response HTTP status and size. |
| 203 |
func writeCombinedLog(writer io.Writer, params LogFormatterParams) { |
| 204 |
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size) |
| 205 |
buf = append(buf, ` "`...) |
| 206 |
buf = appendQuoted(buf, params.Request.Referer()) |
| 207 |
buf = append(buf, `" "`...) |
| 208 |
buf = appendQuoted(buf, params.Request.UserAgent()) |
| 209 |
buf = append(buf, '"', '\n') |
| 210 |
_, _ = writer.Write(buf) |
| 211 |
} |
| 212 |
|
| 213 |
// CombinedLoggingHandler return a http.Handler that wraps h and logs requests to out in |
| 214 |
// Apache Combined Log Format. |
| 215 |
// |
| 216 |
// See http://httpd.apache.org/docs/2.2/logs.html#combined for a description of this format. |
| 217 |
// |
| 218 |
// LoggingHandler always sets the ident field of the log to -. |
| 219 |
func CombinedLoggingHandler(out io.Writer, h http.Handler) http.Handler { |
| 220 |
return loggingHandler{out, h, writeCombinedLog} |
| 221 |
} |
| 222 |
|
| 223 |
// LoggingHandler return a http.Handler that wraps h and logs requests to out in |
| 224 |
// Apache Common Log Format (CLF). |
| 225 |
// |
| 226 |
// See http://httpd.apache.org/docs/2.2/logs.html#common for a description of this format. |
| 227 |
// |
| 228 |
// LoggingHandler always sets the ident field of the log to - |
| 229 |
// |
| 230 |
// Example: |
| 231 |
// |
| 232 |
// r := mux.NewRouter() |
| 233 |
// r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 234 |
// w.Write([]byte("This is a catch-all route")) |
| 235 |
// }) |
| 236 |
// loggedRouter := handlers.LoggingHandler(os.Stdout, r) |
| 237 |
// http.ListenAndServe(":1123", loggedRouter) |
| 238 |
func LoggingHandler(out io.Writer, h http.Handler) http.Handler { |
| 239 |
return loggingHandler{out, h, writeLog} |
| 240 |
} |
| 241 |
|
| 242 |
// CustomLoggingHandler provides a way to supply a custom log formatter |
| 243 |
// while taking advantage of the mechanisms in this package. |
| 244 |
func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler { |
| 245 |
return loggingHandler{out, h, f} |
| 246 |
} |