github.com/zak-blake/goa@v1.4.1/middleware/log_response.go (about)

     1  package middleware
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/goadesign/goa"
     7  
     8  	"context"
     9  )
    10  
    11  // loggingResponseWriter wraps an http.ResponseWriter and writes only raw
    12  // response data (as text) to the context logger. assumes status and duration
    13  // are logged elsewhere (i.e. by the LogRequest middleware).
    14  type loggingResponseWriter struct {
    15  	http.ResponseWriter
    16  	ctx context.Context
    17  }
    18  
    19  // Write will write raw data to logger and response writer.
    20  func (lrw *loggingResponseWriter) Write(buf []byte) (int, error) {
    21  	goa.LogInfo(lrw.ctx, "response", "body", string(buf))
    22  	return lrw.ResponseWriter.Write(buf)
    23  }
    24  
    25  // LogResponse creates a response logger middleware.
    26  // Only Logs the raw response data without accumulating any statistics.
    27  func LogResponse() goa.Middleware {
    28  	return func(h goa.Handler) goa.Handler {
    29  		return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
    30  			// chain a new logging writer to the current response writer.
    31  			resp := goa.ContextResponse(ctx)
    32  			resp.SwitchWriter(
    33  				&loggingResponseWriter{
    34  					ResponseWriter: resp.SwitchWriter(nil),
    35  					ctx:            ctx,
    36  				})
    37  
    38  			// next
    39  			return h(ctx, rw, req)
    40  		}
    41  	}
    42  }