grim/goserve

Parents e739eed19905
Children 0750e24e8e5c
Use the X-Forwarded-For header if we have it, and unwrap ipv6 addresses
  • +24 -5
    middleware.go
  • --- a/middleware.go Sat Jan 04 05:14:53 2020 -0600
    +++ b/middleware.go Sat Jan 04 09:17:21 2020 -0600
    @@ -7,6 +7,29 @@
    "time"
    )
    +func getAddr(r *http.Request) string {
    + // check for the X-Forwarded-For header and use if it we have it
    + if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
    + return fwd
    + }
    +
    + // Request.RemoteAddr is ipv4:port or [ipv6]:port so we have to trim off
    + // the extra bits.
    + addr := r.RemoteAddr
    +
    + // we use LastIndex so we can parse IPv6 addresses
    + if idx := strings.LastIndex(addr, ":"); idx != -1 {
    + addr = addr[:idx]
    + }
    +
    + // if the ipv6 was wrapped in [] we need to unwrap it
    + if idx := strings.Index(addr, "]"); idx != -1 {
    + addr = addr[1:idx]
    + }
    +
    + return addr
    +}
    +
    func basicHandler(h http.Handler, notFoundFile string) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    rw := &responseWriter{
    @@ -18,11 +41,7 @@
    // implement the NCSA Combined Log Format
    // http://publib.boulder.ibm.com/tividd/td/ITWSA/ITWSA_info45/en_US/HTML/guide/c-logs.html#combined
    - addr := r.RemoteAddr
    - // we use LastIndex so we can parse IPv6 addresses
    - if idx := strings.LastIndex(addr, ":"); idx != -1 {
    - addr = addr[:idx]
    - }
    + addr := getAddr(r)
    username := "-"
    if user, _, ok := r.BasicAuth(); ok && username != "" {