-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (61 loc) · 1.54 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
meta "cloud.google.com/go/compute/metadata"
)
var (
logger = log.New(os.Stdout, "[BUTTONS] ", 0)
secret = mustEnvVar("SECRET", "")
project = mustEnvVar("PROJECT", "none")
topic = mustEnvVar("TOPIC", "clicks")
que *queue
)
func main() {
if project == "none" {
mc := meta.NewClient(&http.Client{Transport: userAgentTransport{
userAgent: "buttons",
base: http.DefaultTransport,
}})
p, err := mc.ProjectID()
if err != nil {
logger.Fatalf("Error creating metadata client: %v", err)
}
project = p
}
q, err := newQueue(context.Background(), project, topic)
if err != nil {
logger.Fatal(err)
}
que = q
http.HandleFunc("/", requestHandler)
port := fmt.Sprintf(":%s", mustEnvVar("PORT", "8080"))
if err := http.ListenAndServe(port, nil); err != nil {
logger.Fatal(err)
}
}
func mustEnvVar(key, fallbackValue string) string {
if val, ok := os.LookupEnv(key); ok {
logger.Printf("%s: %s", key, val)
return strings.TrimSpace(val)
}
if fallbackValue == "" {
logger.Fatalf("Required envvar not set: %s", key)
}
logger.Printf("%s: %s (not set, using default)", key, fallbackValue)
return fallbackValue
}
// GCP Metadata
// https://godoc.org/cloud.google.com/go/compute/metadata#example-NewClient
type userAgentTransport struct {
userAgent string
base http.RoundTripper
}
func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", t.userAgent)
return t.base.RoundTrip(req)
}