Debian Codegraph @

instrumentation/net/http/otelhttp/handler_example_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3 package otelhttp_test
4
5 import (
6 "context"
7 "fmt"
8 "io"
9 "log"
10 "net/http"
11 "strings"
12
13 "go.opentelemetry.io/otel/attribute"
14 "go.opentelemetry.io/otel/trace"
15
16 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
17 )
18
19 func ExampleNewHandler() {
20 /* curl -v -d "a painting" http://localhost:7777/hello/bob/ross
21 ...
22 * upload completely sent off: 10 out of 10 bytes
23 < HTTP/1.1 200 OK
24 < Traceparent: 00-76ae040ee5753f38edf1c2bd9bd128bd-dd394138cfd7a3dc-01
25 < Date: Fri, 04 Oct 2019 02:33:08 GMT
26 < Content-Length: 45
27 < Content-Type: text/plain; charset=utf-8
28 <
29 Hello, bob/ross!
30 You sent me this:
31 a painting
32 */
33
34 figureOutName := func(ctx context.Context, s string) (string, error) {
35 pp := strings.SplitN(s, "/", 2)
36 var err error
37 switch pp[1] {
38 case "":
39 err = fmt.Errorf("expected /hello/:name in %q", s)
40 default:
41 trace.SpanFromContext(ctx).SetAttributes(attribute.String("name", pp[1]))
42 }
43 return pp[1], err
44 }
45
46 var mux http.ServeMux
47 mux.Handle("/hello/", http.HandlerFunc(
48 func(w http.ResponseWriter, r *http.Request) {
49 ctx := r.Context()
50 labeler, _ := otelhttp.LabelerFromContext(ctx)
51
52 var name string
53 // Wrap another function in its own span
54 if err := func(ctx context.Context) error {
55 ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("exampleTracer").Start(ctx, "figureOutName")
56 defer span.End()
57
58 var err error
59 name, err = figureOutName(ctx, r.URL.Path[1:])
60 return err
61 }(ctx); err != nil {
62 log.Println("error figuring out name: ", err)
63 http.Error(w, err.Error(), http.StatusInternalServerError)
64 labeler.Add(attribute.Bool("error", true))
65 return
66 }
67
68 d, err := io.ReadAll(r.Body)
69 if err != nil {
70 log.Println("error reading body: ", err)
71 w.WriteHeader(http.StatusBadRequest)
72 labeler.Add(attribute.Bool("error", true))
73 return
74 }
75
76 n, err := io.WriteString(w, "Hello, "+name+"!\nYou sent me this:\n"+string(d))
77 if err != nil {
78 log.Printf("error writing reply after %d bytes: %s", n, err)
79 labeler.Add(attribute.Bool("error", true))
80 }
81 }),
82 )
83
84 if err := http.ListenAndServe(":7777",
85 otelhttp.NewHandler(&mux, "server",
86 otelhttp.WithMessageEvents(otelhttp.ReadEvents, otelhttp.WriteEvents),
87 ),
88 ); err != nil {
89 log.Fatal(err)
90 }
91 }