-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
87 lines (72 loc) · 2.38 KB
/
Copy pathmain.go
File metadata and controls
87 lines (72 loc) · 2.38 KB
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
package main
import (
"context"
"database/sql"
"fmt"
"log"
"net"
"os"
"time" // NEW IMPORT
"cloud.google.com/go/cloudsqlconn"
"contrib.go.opencensus.io/exporter/stackdriver" // NEW IMPORT
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
"go.opencensus.io/stats/view" // NEW IMPORT
)
func main() {
var (
dbUser = os.Getenv("DB_USER")
dbPwd = os.Getenv("DB_PASS")
dbName = os.Getenv("DB_NAME")
instanceConnectionName = os.Getenv("INSTANCE_CONNECTION_NAME")
usePrivate = os.Getenv("PRIVATE_IP")
)
// ===================================================================
// START: METRICS EXPORTER CONFIGURATION
// ===================================================================
// 1. Create the Stackdriver exporter
exporter, err := stackdriver.NewExporter(stackdriver.Options{
ProjectID: "jinphou-playground",
})
if err != nil {
log.Fatalf("Failed to create Stackdriver exporter: %v", err)
}
defer exporter.Flush() // Flush exporter before the application exits
// 2. Register the exporter with OpenCensus
view.RegisterExporter(exporter)
// 3. Set the reporting period
view.SetReportingPeriod(60 * time.Second)
// ===================================================================
// END: METRICS EXPORTER CONFIGURATION
// ===================================================================
d, err := cloudsqlconn.NewDialer(context.Background())
if err != nil {
log.Fatalf("cloudsqlconn.NewDialer: %v", err)
}
// ... rest of the code is the same
var opts []cloudsqlconn.DialOption
if usePrivate != "" {
opts = append(opts, cloudsqlconn.WithPrivateIP())
}
dsn := fmt.Sprintf("user=%s password=%s dbname=%s", dbUser, dbPwd, dbName)
config, err := pgx.ParseConfig(dsn)
if err != nil {
log.Fatalf("pgx.ParseConfig: %v", err)
}
config.DialFunc = func(ctx context.Context, network, instance string) (net.Conn, error) {
return d.Dial(ctx, instanceConnectionName, opts...)
}
db, err := sql.Open("pgx", stdlib.RegisterConnConfig(config))
if err != nil {
log.Fatalf("sql.Open: %v", err)
}
defer db.Close()
log.Println("Pinging database...")
err = db.PingContext(context.Background())
if err != nil {
log.Fatalf("failed to ping database: %v", err)
}
log.Println("Successfully connected to the database!")
log.Println("Application is now running and exporting metrics...")
select {}
}