-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
99 lines (80 loc) · 2.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/emanuelef/go-gin-honeycomb/otel_instrumentation"
"github.com/gin-gonic/gin"
_ "github.com/joho/godotenv/autoload"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
const externalURL = "https://pokeapi.co/api/v2/pokemon/ditto"
var tracer trace.Tracer
func init() {
tracer = otel.Tracer("github.com/emanuelef/go-gin-honeycomb/secondary")
}
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
func main() {
ctx := context.Background()
tp, exp, err := otel_instrumentation.InitializeGlobalTracerProvider(ctx)
// Handle shutdown to ensure all sub processes are closed correctly and telemetry is exported
defer func() {
_ = exp.Shutdown(ctx)
_ = tp.Shutdown(ctx)
}()
if err != nil {
log.Fatalf("failed to initialize OpenTelemetry: %e", err)
}
r := gin.New()
r.Use(gin.Recovery())
r.Use(otelgin.Middleware("secondary-server"))
r.GET("/hello", func(c *gin.Context) {
_, err := otelhttp.Get(c.Request.Context(), externalURL)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
resp, err := otelhttp.Get(c.Request.Context(), externalURL)
_, _ = io.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
// Get current span and add new attributes
span := trace.SpanFromContext(c.Request.Context())
span.SetAttributes(attribute.Bool("isTrue", true), attribute.String("stringAttr", "Ciao"))
// Create a child span
ctx, childSpan := tracer.Start(c.Request.Context(), "custom-span-secondary")
time.Sleep(10 * time.Millisecond)
resp, _ = otelhttp.Get(ctx, externalURL)
_, _ = io.ReadAll(resp.Body)
childSpan.End()
time.Sleep(20 * time.Millisecond)
c.JSON(resp.StatusCode, gin.H{})
})
host := getEnv("HOST", "localhost")
port := getEnv("PORT", "8082")
hostAddress := fmt.Sprintf("%s:%s", host, port)
err = r.Run(hostAddress)
if err != nil {
log.Printf("Starting router failed, %v", err)
}
}