github.com/blend/go-sdk@v1.20220411.3/webutil/http_logged.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import (
    11  	"net/http"
    12  	"time"
    13  
    14  	"github.com/blend/go-sdk/logger"
    15  )
    16  
    17  // HTTPLogged returns a middleware that logs a request.
    18  func HTTPLogged(log logger.Triggerable) Middleware {
    19  	return func(action http.HandlerFunc) http.HandlerFunc {
    20  		return func(rw http.ResponseWriter, req *http.Request) {
    21  			start := time.Now()
    22  			w := NewStatusResponseWriter(rw)
    23  			defer func() {
    24  				responseEvent := NewHTTPRequestEvent(req,
    25  					OptHTTPRequestStatusCode(w.StatusCode()),
    26  					OptHTTPRequestContentLength(w.ContentLength()),
    27  					OptHTTPRequestElapsed(time.Since(start)),
    28  				)
    29  				if w.Header() != nil {
    30  					responseEvent.ContentType = w.Header().Get(HeaderContentType)
    31  					responseEvent.ContentEncoding = w.Header().Get(HeaderContentEncoding)
    32  				}
    33  				logger.MaybeTriggerContext(
    34  					req.Context(),
    35  					log,
    36  					responseEvent,
    37  				)
    38  			}()
    39  			action(w, req)
    40  		}
    41  	}
    42  }