40 lines
1,021 B
Go
40 lines
1,021 B
Go
|
package middlewares
|
||
|
|
||
|
import (
|
||
|
"net"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"git.faercol.me/faercol/http-boot-server/bootserver/helpers"
|
||
|
"github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
var defaultResponseInfo = helpers.ResponseInfo{
|
||
|
ReturnCode: -1,
|
||
|
ContentLength: -1,
|
||
|
}
|
||
|
|
||
|
type LoggerMiddleware struct {
|
||
|
l *logrus.Logger
|
||
|
}
|
||
|
|
||
|
func (lm *LoggerMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||
|
responseInfo, ok := r.Context().Value(helpers.ResponseInfoKey).(helpers.ResponseInfo)
|
||
|
if !ok {
|
||
|
lm.l.Errorf("Failed to read response info from context, got %v", r.Context().Value("response_info"))
|
||
|
responseInfo = defaultResponseInfo
|
||
|
}
|
||
|
method := r.Method
|
||
|
route := r.RequestURI
|
||
|
currentTime := time.Now().UTC()
|
||
|
httpVersion := r.Proto
|
||
|
|
||
|
clientIP, _, err := net.SplitHostPort(r.RemoteAddr)
|
||
|
if err != nil {
|
||
|
lm.l.Errorf("Failed to read remote IP: %s", err.Error())
|
||
|
clientIP = "unknown"
|
||
|
}
|
||
|
|
||
|
lm.l.Infof(`%s - [%v] "%s %s %s" %d %d`, clientIP, currentTime, method, route, httpVersion, responseInfo.ReturnCode, responseInfo.ContentLength)
|
||
|
}
|