github.com/blend/go-sdk@v1.20220411.3/r2/opt_log_response.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 r2 9 10 import ( 11 "bytes" 12 "io" 13 "net/http" 14 "time" 15 16 "github.com/blend/go-sdk/logger" 17 ) 18 19 // OptLogResponse adds an OnResponse listener to log the response of a call. 20 func OptLogResponse(log logger.Triggerable) Option { 21 return OptOnResponse(func(req *http.Request, res *http.Response, startedUTC time.Time, err error) error { 22 if err != nil { 23 return nil 24 } 25 event := NewEvent(FlagResponse, 26 OptEventRequest(req), 27 OptEventResponse(res), 28 OptEventElapsed(time.Now().UTC().Sub(startedUTC)), 29 ) 30 31 logger.MaybeTriggerContext(req.Context(), log, event) 32 return nil 33 }) 34 } 35 36 // OptLogResponseWithBody adds an OnResponse listener to log the response of a call. 37 // It reads the contents of the response fully before emitting the event. 38 // Do not use this if the size of the responses can be large. 39 func OptLogResponseWithBody(log logger.Triggerable) Option { 40 return OptOnResponse(func(req *http.Request, res *http.Response, started time.Time, err error) error { 41 if err != nil { 42 return nil 43 } 44 defer res.Body.Close() 45 46 // read out the buffer in full 47 buffer := new(bytes.Buffer) 48 if _, err := io.Copy(buffer, res.Body); err != nil { 49 return err 50 } 51 // set the body to the read contents 52 res.Body = io.NopCloser(bytes.NewReader(buffer.Bytes())) 53 54 event := NewEvent(FlagResponse, 55 OptEventRequest(req), 56 OptEventResponse(res), 57 OptEventBody(buffer.Bytes()), 58 OptEventElapsed(time.Now().UTC().Sub(started)), 59 ) 60 61 logger.MaybeTriggerContext(req.Context(), log, event) 62 return nil 63 }) 64 }