|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + _ "github.com/go-sql-driver/mysql" |
| 9 | + "github.com/google/sqlcommenter/go/core" |
| 10 | + gosql "github.com/google/sqlcommenter/go/database/sql" |
| 11 | + httpnet "github.com/google/sqlcommenter/go/net/http" |
| 12 | + "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" |
| 13 | + sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 14 | +) |
| 15 | + |
| 16 | +func Index(w http.ResponseWriter, r *http.Request) { |
| 17 | + |
| 18 | + connection := "root:root@/gotest" |
| 19 | + exp, _ := stdouttrace.New(stdouttrace.WithPrettyPrint()) |
| 20 | + bsp := sdktrace.NewSimpleSpanProcessor(exp) // You should use batch span processor in prod |
| 21 | + tp := sdktrace.NewTracerProvider( |
| 22 | + sdktrace.WithSampler(sdktrace.AlwaysSample()), |
| 23 | + sdktrace.WithSpanProcessor(bsp), |
| 24 | + ) |
| 25 | + |
| 26 | + ctx, span := tp.Tracer("foo").Start(r.Context(), "parent-span-name") |
| 27 | + defer span.End() |
| 28 | + |
| 29 | + db, err := gosql.Open("mysql", connection, core.CommenterOptions{EnableDBDriver: true, EnableRoute: true, EnableAction: true, EnableFramework: true, EnableTraceparent: true}) |
| 30 | + if err != nil { |
| 31 | + fmt.Println(err) |
| 32 | + } else { |
| 33 | + db.ExecContext(ctx, "Select 11;") |
| 34 | + db.Exec("Select 2;") |
| 35 | + db.Prepare("Select 10") |
| 36 | + db.PrepareContext(ctx, "Select 10") |
| 37 | + } |
| 38 | + fmt.Fprintf(w, "Hello World!") |
| 39 | +} |
| 40 | + |
| 41 | +// middleware is used to intercept incoming HTTP calls and apply general functions upon them. |
| 42 | +func middleware(next http.Handler) http.Handler { |
| 43 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 44 | + ctx := core.ContextInject(r.Context(), httpnet.NewHTTPRequestExtractor(r, next)) |
| 45 | + log.Printf("HTTP request sent to %s from %v", r.URL.Path, next) |
| 46 | + next.ServeHTTP(w, r.WithContext(ctx)) |
| 47 | + }) |
| 48 | +} |
| 49 | + |
| 50 | +func main() { |
| 51 | + mux := http.NewServeMux() |
| 52 | + finalHandler := http.HandlerFunc(Index) |
| 53 | + mux.Handle("/", middleware((finalHandler))) |
| 54 | + log.Fatal(http.ListenAndServe(":8080", mux)) |
| 55 | +} |
0 commit comments