39 lines
1 KiB
Go
39 lines
1 KiB
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 - [%s] "%s %s %s" %d %d`, clientIP, currentTime.Format(time.RFC3339), method, route, httpVersion, responseInfo.ReturnCode, responseInfo.ContentLength)
|
|
}
|