Skip to content

Instantly share code, notes, and snippets.

@TonPC64
Created February 24, 2022 14:39
Show Gist options
  • Save TonPC64/763ad305d309da7ddc2ec148f020530b to your computer and use it in GitHub Desktop.
Save TonPC64/763ad305d309da7ddc2ec148f020530b to your computer and use it in GitHub Desktop.
// 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