Created
February 24, 2022 14:39
-
-
Save TonPC64/763ad305d309da7ddc2ec148f020530b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// general http handler | |
func httpHandler(w http.ResponseWriter, r *http.Request) { | |
// get tracer provider from otel package and inject ctx to tracer | |
tracer := otel.GetTracerProvider().Tracer("httpHandler") | |
ctx, span := tracer.Start(r.Context(), "httpHandler") | |
defer span.End() | |
// create http client with transport for inject trace signal to http header automatically | |
client := &http.Client{ | |
Transport: otelhttp.NewTransport(nil), | |
} | |
// create http request with context for inject trace signal to http header in request | |
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://echo:8081", nil) | |
if err != nil { | |
// if error should set status to span | |
span.RecordError(err) | |
span.SetStatus(codes.Error, codes.Error.String()) | |
// write response like general handler | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte("new request error")) | |
return | |
} | |
// use client to call other service | |
res, err := client.Do(request) | |
if err != nil { | |
// if error should set status to span | |
span.RecordError(err) | |
span.SetStatus(codes.Error, codes.Error.String()) | |
// write response like general handler | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte("http request error")) | |
return | |
} | |
fmt.Println(res.Status) | |
if res.StatusCode != http.StatusOK { | |
// if error should set status to span | |
span.RecordError(err) | |
span.SetStatus(codes.Error, codes.Error.String()) | |
// write response like general handler | |
bb, _ := io.ReadAll(res.Body) | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write(bb) | |
return | |
} | |
w.Write([]byte("ok with tracing")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment