From 09aad777f4da1f864e9593f83992bfd425376bef Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Thu, 26 Mar 2015 23:39:36 -0600 Subject: [PATCH] Proper host/port splitting; also log file perms --- middleware/log/log.go | 2 +- middleware/replacer.go | 24 +++++++++++++----------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/middleware/log/log.go b/middleware/log/log.go index 1b2aa7b8..331aa63f 100644 --- a/middleware/log/log.go +++ b/middleware/log/log.go @@ -43,7 +43,7 @@ func New(c middleware.Controller) (middleware.Middleware, error) { } else if outputFile == "stderr" { file = os.Stderr } else { - file, err = os.OpenFile(outputFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) + file, err = os.OpenFile(outputFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return err } diff --git a/middleware/replacer.go b/middleware/replacer.go index a8ed289b..b6194ad7 100644 --- a/middleware/replacer.go +++ b/middleware/replacer.go @@ -1,6 +1,7 @@ package middleware import ( + "net" "net/http" "strconv" "strings" @@ -13,11 +14,11 @@ import ( // NewReplacer to get one of these. type replacer map[string]string -// NewReplacer makes a new replacer based on r and rw. -// Do not create a new replacer until r and rw have all +// NewReplacer makes a new replacer based on r and rr. +// Do not create a new replacer until r and rr have all // the needed values, because this function copies those // values into the replacer. -func NewReplacer(r *http.Request, rw *responseRecorder) replacer { +func NewReplacer(r *http.Request, rr *responseRecorder) replacer { rep := replacer{ "{method}": r.Method, "{scheme}": func() string { @@ -32,24 +33,25 @@ func NewReplacer(r *http.Request, rw *responseRecorder) replacer { "{fragment}": r.URL.Fragment, "{proto}": r.Proto, "{remote}": func() string { - if idx := strings.Index(r.RemoteAddr, ":"); idx > -1 { - return r.RemoteAddr[:idx] // IP address only - } else { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { return r.RemoteAddr } + return host }(), "{port}": func() string { - if idx := strings.Index(r.Host, ":"); idx > -1 { - return r.Host[idx+1:] // port only + _, port, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return "" } - return "" + return port }(), "{uri}": r.RequestURI, "{when}": func() string { return time.Now().Format(timeFormat) }(), - "{status}": strconv.Itoa(rw.status), - "{size}": strconv.Itoa(rw.size), + "{status}": strconv.Itoa(rr.status), + "{size}": strconv.Itoa(rr.size), } // Header placeholders