grim/goserve
Clone
Summary
Browse
Changes
Graph
Rework the logging handler to output common log format
draft
2020-01-04, Gary Kramlich
210901358745
Rework the logging handler to output common log format
package
main
import
(
"fmt"
"net/http"
"strings"
"time"
)
func
basicHandler
(
h
http
.
Handler
)
http
.
Handler
{
return
http
.
HandlerFunc
(
func
(
w
http
.
ResponseWriter
,
r
*
http
.
Request
)
{
rw
:=
&
responseWriter
{
w
:
w
}
defer
func
()
{
addr
:=
r
.
RemoteAddr
// we use LastIndex so we can parse IPv6 addresses
if
idx
:=
strings
.
LastIndex
(
addr
,
":"
);
idx
!=
-
1
{
addr
=
addr
[:
idx
]
}
username
:=
"-"
if
user
,
_
,
ok
:=
r
.
BasicAuth
();
ok
&&
username
!=
""
{
username
=
user
}
fmt
.
Printf
(
"%s - %s [%s] \"%s %s %s\" %d %d\n"
,
addr
,
username
,
time
.
Now
().
Format
(
"02/Jan/2006:15:04:05 -0700"
),
r
.
Method
,
r
.
URL
.
Path
,
r
.
Proto
,
rw
.
StatusCode
(),
rw
.
Written
(),
)
}()
h
.
ServeHTTP
(
rw
,
r
)
})
}