-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubscriber.go
56 lines (49 loc) · 1.16 KB
/
subscriber.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
package bucketSubscriber
import (
"context"
"database/sql"
"fmt"
"log"
"os"
// pq for postgres
_ "github.com/lib/pq"
)
// GCSEvent ...
type GCSEvent struct {
Kind string `json:"kind"`
ID string `json:"id"`
Name string `json:"name"`
Bucket string `json:"bucket"`
}
var (
db *sql.DB
insertStatement = `INSERT INTO events (id, name, kind, bucket)
VALUES ($1, $2, $3, $4)`
connectionName = mustGetenv("CLOUDSQL_CONNECTION_NAME")
dbUser = mustGetenv("CLOUDSQL_USER")
dbPassword = mustGetenv("CLOUDSQL_PASSWORD")
dbName = mustGetenv("CLOUDSQL_DB_NAME")
dsn = fmt.Sprintf("user=%s password=%s dbname=%s host=/cloudsql/%s sslmode=disable", dbUser, dbPassword, dbName, connectionName)
)
func init() {
var err error
db, err = sql.Open("postgres", dsn)
if err != nil {
panic(err)
}
}
// Handler ...
func Handler(ctx context.Context, e GCSEvent) error {
_, err := db.Exec(insertStatement, e.ID, e.Name, e.Kind, e.Bucket)
if err != nil {
return err
}
return nil
}
func mustGetenv(k string) string {
v := os.Getenv(k)
if v == "" {
log.Panicf("%s environment variable not set.", k)
}
return v
}