Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/docker-otel-lgtm
Path: blob/main/examples/go/main.go
401 views
1
package main
2
3
import (
4
"context"
5
"errors"
6
"log"
7
"net"
8
"net/http"
9
"os"
10
"os/signal"
11
"time"
12
13
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
14
)
15
16
func main() {
17
if err := run(); err != nil {
18
log.Fatalln(err)
19
}
20
}
21
22
func run() (err error) {
23
// Handle SIGINT (CTRL+C) gracefully.
24
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
25
defer stop()
26
27
// Set up OpenTelemetry.
28
otelShutdown, err := setupOTelSDK(ctx)
29
if err != nil {
30
return
31
}
32
// Handle shutdown properly so nothing leaks.
33
defer func() {
34
err = errors.Join(err, otelShutdown(context.Background()))
35
}()
36
37
// Start HTTP server.
38
srv := &http.Server{
39
Addr: ":8081",
40
BaseContext: func(_ net.Listener) context.Context { return ctx },
41
ReadTimeout: time.Second,
42
WriteTimeout: 10 * time.Second,
43
Handler: newHTTPHandler(),
44
}
45
srvErr := make(chan error, 1)
46
go func() {
47
srvErr <- srv.ListenAndServe()
48
}()
49
50
// Wait for interruption.
51
select {
52
case err = <-srvErr:
53
// Error when starting HTTP server.
54
return
55
case <-ctx.Done():
56
// Wait for first CTRL+C.
57
// Stop receiving signal notifications as soon as possible.
58
stop()
59
}
60
61
// When Shutdown is called, ListenAndServe immediately returns ErrServerClosed.
62
err = srv.Shutdown(context.Background())
63
return
64
}
65
66
func newHTTPHandler() http.Handler {
67
mux := http.NewServeMux()
68
69
// handleFunc is a replacement for mux.HandleFunc
70
// which enriches the handler's HTTP instrumentation with the pattern as the http.route.
71
handleFunc := func(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
72
// Configure the "http.route" for the HTTP instrumentation.
73
handler := otelhttp.WithRouteTag(pattern, http.HandlerFunc(handlerFunc))
74
mux.Handle(pattern, handler)
75
}
76
77
// Register handlers.
78
handleFunc("/rolldice", rolldice)
79
80
// Add HTTP instrumentation for the whole server.
81
handler := otelhttp.NewHandler(mux, "/")
82
return handler
83
}
84
85