Debian Codegraph @

examples/dice/instrumented/main.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Instrumented provides an example rolldice service that is instrumented with
5 // OpenTelemetry.
6 package main
7
8 import (
9 "context"
10 "errors"
11 "log"
12 "net"
13 "net/http"
14 "os"
15 "os/signal"
16 "time"
17
18 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
19 )
20
21 func main() {
22 if err := run(); err != nil {
23 log.Fatalln(err)
24 }
25 }
26
27 func run() error {
28 // Handle SIGINT (CTRL+C) gracefully.
29 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
30 defer stop()
31
32 // Set up OpenTelemetry.
33 otelShutdown, err := setupOTelSDK(ctx)
34 if err != nil {
35 return err
36 }
37 // Handle shutdown properly so nothing leaks.
38 defer func() {
39 err = errors.Join(err, otelShutdown(context.Background()))
40 }()
41
42 // Start HTTP server.
43 srv := &http.Server{
44 Addr: ":8080",
45 BaseContext: func(net.Listener) context.Context { return ctx },
46 ReadTimeout: time.Second,
47 WriteTimeout: 10 * time.Second,
48 Handler: newHTTPHandler(),
49 }
50 srvErr := make(chan error, 1)
51 go func() {
52 srvErr <- srv.ListenAndServe()
53 }()
54
55 // Wait for interruption.
56 select {
57 case err = <-srvErr:
58 // Error when starting HTTP server.
59 return err
60 case <-ctx.Done():
61 // Wait for first CTRL+C.
62 // Stop receiving signal notifications as soon as possible.
63 stop()
64 }
65
66 // When Shutdown is called, ListenAndServe immediately returns ErrServerClosed.
67 err = srv.Shutdown(context.Background())
68 return err
69 }
70
71 func newHTTPHandler() http.Handler {
72 mux := http.NewServeMux()
73
74 // Register handlers.
75 mux.Handle("/rolldice", http.HandlerFunc(rolldice))
76 mux.Handle("/rolldice/{player}", http.HandlerFunc(rolldice))
77
78 // Add HTTP instrumentation for the whole server.
79 handler := otelhttp.NewHandler(mux, "/")
80 return handler
81 }