-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (62 loc) · 1.35 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 sample
import (
"fmt"
"log"
"net/http"
"os"
"cloud.google.com/go/logging"
)
// User user info
type User struct {
// Name user name
Name string `json:"name"`
}
// Hello just say "Hello"
func Hello(w http.ResponseWriter, r *http.Request) {
project := mustGetenv("PROJECT")
ctx := r.Context()
// Get logging client
client, err := logging.NewClient(ctx, project)
if err != nil {
log.Fatal("Failed to get logging client")
}
// Parse query string
names, ok := r.URL.Query()["name"]
var name string
if !ok || len(names[0]) < 1 {
name = "World"
} else {
name = names[0]
}
user := User{Name: name}
// Get logger
logger := client.Logger("sample-logger-1")
// logging
logger.Log(logging.Entry{
Payload: user,
Severity: logging.Info,
Labels: map[string]string{"bigquery-export-type": "sample"},
})
logger.Log(logging.Entry{
Payload: "warning",
Severity: logging.Warning,
})
logger.Log(logging.Entry{
Payload: "error",
Severity: logging.Error,
})
// Validate http method
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("Only GET method is allowed"))
}
msg := fmt.Sprintf("Hello %s", name)
w.Write([]byte(msg))
}
func mustGetenv(key string) string {
val := os.Getenv(key)
if val == "" {
log.Fatalf("Environment variable named '%s' is empty", key)
}
return val
}