Debian Codegraph @

instrumentation/github.com/labstack/echo/otelecho/example_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3 package otelecho_test
4
5 import (
6 "errors"
7 "io"
8 "log"
9 "net/http"
10
11 "github.com/labstack/echo/v4"
12 "go.opentelemetry.io/otel/attribute"
13 "go.opentelemetry.io/otel/codes"
14 "go.opentelemetry.io/otel/trace"
15
16 "go.opentelemetry.io/contrib/instrumentation/github.com/labstack/echo/otelecho"
17 )
18
19 func ExampleMiddleware() {
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 // Create a new Echo instance
35 e := echo.New()
36
37 // Use the otelecho middleware with options
38 e.Use(otelecho.Middleware("server",
39 otelecho.WithSkipper(func(c echo.Context) bool {
40 // Skip tracing for health check endpoints
41 return c.Path() == "/health"
42 }),
43 ))
44
45 // Define a route with a handler that demonstrates tracing
46 e.POST("/hello/:name", func(c echo.Context) error {
47 ctx := c.Request().Context()
48
49 // Get the current span from context
50 span := trace.SpanFromContext(ctx)
51
52 // Create a child span for processing the name
53 ctx, nameSpan := span.TracerProvider().Tracer("exampleTracer").Start(ctx, "processName")
54
55 // Get the name parameter using Echo's built-in functionality
56 name := c.Param("name")
57
58 // Add the name as a span attribute
59 nameSpan.SetAttributes(attribute.String("name", name))
60 nameSpan.End()
61
62 // Read the request body
63 d, err := io.ReadAll(c.Request().Body)
64 if err != nil {
65 log.Println("error reading body: ", err)
66 // Record the error in the span and set its status
67 span.SetStatus(codes.Error, "failed to read request body")
68 return c.String(http.StatusBadRequest, "Bad request")
69 }
70
71 // Create another child span for processing the response
72 _, responseSpan := span.TracerProvider().Tracer("exampleTracer").Start(ctx, "createResponse")
73
74 // Create the response
75 response := "Hello, " + name + "!\nYou sent me this:\n" + string(d)
76
77 // Add information about the response size
78 responseSpan.SetAttributes(attribute.Int("response.size", len(response)))
79 responseSpan.End()
80
81 // Set the status of the main span to OK
82 span.SetStatus(codes.Ok, "")
83
84 return c.String(http.StatusOK, response)
85 })
86
87 // Add a health check endpoint that will be skipped by the tracer
88 e.GET("/health", func(c echo.Context) error {
89 return c.String(http.StatusOK, "OK")
90 })
91
92 // Start the server
93 err := e.Start(":7777")
94 if !errors.Is(err, http.ErrServerClosed) {
95 log.Fatal(err)
96 }
97 }
98
99 func ExampleMiddleware_withMetrics() {
100 // This example shows how to use the otelecho middleware with custom metrics attributes
101 // The middleware will automatically collect HTTP server metrics including:
102 // - http.server.request.duration
103 // - http.server.request.body.size
104 // - http.server.response.body.size
105
106 // Create a new Echo instance
107 e := echo.New()
108
109 // Use the otelecho middleware with metrics and custom attributes
110 e.Use(otelecho.Middleware("api-server",
111 otelecho.WithMetricAttributeFn(func(r *http.Request) []attribute.KeyValue {
112 // Add custom attributes from HTTP request
113 return []attribute.KeyValue{
114 attribute.Bool("custom.has_request_body", r.ContentLength != 0),
115 attribute.Bool("custom.has_content_type", r.Header.Get("Content-Type") != ""),
116 }
117 }),
118 otelecho.WithEchoMetricAttributeFn(func(c echo.Context) []attribute.KeyValue {
119 // Add custom attributes from Echo context
120 // If attributes are duplicated between this method and `WithMetricAttributeFn`, the attributes in this method will be used.
121 return []attribute.KeyValue{
122 attribute.Bool("custom.has_request_body", c.Request().ContentLength != 0),
123 attribute.Bool("custom.has_content_type", c.Request().Header.Get("Content-Type") != ""),
124 }
125 }),
126 ))
127
128 // Define routes
129 e.GET("/api/users/:id", func(c echo.Context) error {
130 userID := c.Param("id")
131 return c.JSON(http.StatusOK, map[string]any{
132 "id": userID,
133 "name": "User " + userID,
134 })
135 })
136
137 e.POST("/api/users", func(c echo.Context) error {
138 var user struct {
139 Name string `json:"name"`
140 Email string `json:"email"`
141 }
142
143 if err := c.Bind(&user); err != nil {
144 return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
145 }
146
147 return c.JSON(http.StatusCreated, map[string]any{
148 "id": "12345",
149 "name": user.Name,
150 "email": user.Email,
151 })
152 })
153
154 // Output:
155 }