// Middleware wraps the given next http.Handler. Requests made through this
// middleware are annotated with the given logger (to the r.Context()) and
// after the request has been service a _info_ logentry is triggered for the
// request served.
Middleware wraps the given next http.Handler. Requests made through this
middleware are annotated with the given logger (to the r.Context()) and
after the request has been service a _info_ logentry is triggered for the
request served.
// Middleware wraps the given next http . Handler . Requests made through this // middleware are annotated with the given logger ( to the r . Context () ) and // after the request has been service a _info_ logentry is triggered for the // request served .
func Middleware(next http.Handler, logger *zap.Logger) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestID := "r" + strconv.FormatInt(rand.Int63(), 36)
		l := logger.With(zap.String("rid", requestID))
		ww := &wrapper{ResponseWriter: w}
		r = r.WithContext(context.WithValue(r.Context(), keyLogger, l))
		r = r.WithContext(context.WithValue(r.Context(), keyRequestID, requestID))
		if r.Header.Get("X-Forwarded-For") != "" {
			r.RemoteAddr = strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0])
		}
		defer func() {
			logger.Info("served",
				zap.String("rid", requestID),
				zap.String("method", r.Method),
				zap.String("path", r.URL.Path),
				zap.String("remote", r.RemoteAddr),
				zap.Int("status", ww.Status()),
			)
		}()
		next.ServeHTTP(ww, r)
	})
}
func Middleware ( next http . Handler , logger * zap . Logger ) http . Handler { return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) { requestID := " " + strconv . FormatInt ( rand . Int63 ( ) , 36 ) l := logger . With ( zap . String ( " " , requestID ) ) ww := & wrapper { ResponseWriter : w } r = r . WithContext ( context . WithValue ( r . Context ( ) , keyLogger , l ) ) r = r . WithContext ( context . WithValue ( r . Context ( ) , keyRequestID , requestID ) ) if r . Header . Get ( " " ) != " " { r . RemoteAddr = strings . TrimSpace ( strings . Split ( r . Header . Get ( " " ) , " " ) [ 0 ] ) } defer func ( ) { logger . Info ( " " , zap . String ( " " , requestID ) , zap . String ( " " , r . Method ) , zap . String ( " " , r . URL . Path ) , zap . String ( " " , r . RemoteAddr ) , zap . Int ( " " , ww . Status ( ) ) , ) } ( ) next . ServeHTTP ( ww , r ) } ) }
Middleware wraps the given next http.Handler.
Middleware wraps the given next http . Handler .