Created
May 2, 2023 22:58
-
-
Save marcosuma/456b3244465be51c4cf271f579f4e3b1 to your computer and use it in GitHub Desktop.
Bramble observability plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package roundtripper | |
import ( | |
"encoding/json" | |
"errors" | |
"fmt" | |
log "github.com/sirupsen/logrus" | |
logf "github.com/sirupsen/logrus" | |
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace" | |
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" | |
"io" | |
"net/http" | |
httptrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http" | |
) | |
type observabilityTransport struct { | |
Proxy http.RoundTripper | |
AppName string | |
} | |
// NewObservabilityTransport implements the http.RoundTripper interface | |
func NewObservabilityTransport(appName string) func(http.RoundTripper) (http.RoundTripper, error) { | |
return func(proxy http.RoundTripper) (http.RoundTripper, error) { | |
if proxy == nil { | |
return nil, errors.New("proxy is not set") | |
} | |
rtOpts := []httptrace.RoundTripperOption{ | |
httptrace.RTWithServiceName(appName), | |
httptrace.WithAfter(func(res *http.Response, span ddtrace.Span) { | |
if res == nil || res.Body == nil { | |
err := fmt.Errorf("response payload is empty") | |
span.Finish(tracer.WithError(err)) | |
return | |
} | |
jsonResult := map[string]string{"errors": ""} | |
body, _ := io.ReadAll(res.Body) | |
_ = json.Unmarshal(body, &jsonResult) | |
log.Infof("JSON RESULT!!!: %s", jsonResult) | |
log.Infof("BODY RESPONSE!!!: %s", string(body)) | |
}), | |
} | |
return &observabilityTransport{ | |
Proxy: httptrace.WrapRoundTripper(proxy, rtOpts...), | |
AppName: appName, | |
}, nil | |
} | |
} | |
// RoundTrip returns a RoundTripper instance for DD tracing and monitoring | |
func (rt *observabilityTransport) RoundTrip(req *http.Request) ( | |
resp *http.Response, err error) { | |
response, responseErr := rt.Proxy.RoundTrip(req) | |
if responseErr != nil { | |
logf.Infof("observability RoundTrip responseErr!!!: %v", responseErr) | |
} | |
return response, responseErr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment