-
Notifications
You must be signed in to change notification settings - Fork 52
/
main.go
78 lines (68 loc) · 1.94 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
package main
import (
"context"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
var serviceName string
func main() {
log.SetOutput(os.Stderr)
if os.Getenv("DEBUG") == "true" {
slog.SetLogLoggerLevel(slog.LevelDebug)
}
serviceName = "cncf-demo"
if os.Getenv("SERVICE_NAME") != "" {
serviceName = os.Getenv("SERVICE_NAME")
}
// OpenTelemetry
var err error
tp, err = initTracer()
if err != nil {
log.Fatal(err)
}
defer func() {
if err := tp.Shutdown(context.Background()); err != nil {
log.Printf("Error shutting down tracer provider: %v", err)
}
}()
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
// Server
log.Println("Starting server...")
router := gin.New()
router.Use(otelgin.Middleware(serviceName))
router.GET("/fibonacci", fibonacciHandler)
router.POST("/video", videoPostHandler)
router.GET("/videos", videosGetHandler)
router.GET("/ping", pingHandler)
router.GET("/", rootHandler)
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8080"
}
router.Run(fmt.Sprintf(":%s", port))
}
func httpErrorBadRequest(err error, span trace.Span, ctx *gin.Context) {
httpError(err, span, ctx, http.StatusBadRequest)
}
func httpErrorInternalServerError(err error, span trace.Span, ctx *gin.Context) {
httpError(err, span, ctx, http.StatusInternalServerError)
}
func httpStatusUnauthorized(err error, span trace.Span, ctx *gin.Context) {
httpError(err, span, ctx, http.StatusUnauthorized)
}
func httpError(err error, span trace.Span, ctx *gin.Context, status int) {
log.Println(err.Error())
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
ctx.String(status, err.Error())
}