-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (65 loc) · 1.57 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
package lastword
import (
"context"
"fmt"
"net/http"
"os"
"cloud.google.com/go/datastore"
)
var project = os.Getenv("GCP_PROJECT")
var authToken = os.Getenv("AUTH_TOKEN")
var kind = os.Getenv("KIND")
type lastword struct {
Status string
}
func writeStatus(ctx context.Context, client *datastore.Client, key, status string) error {
k := datastore.NameKey(kind, key, nil)
_, err := client.Put(ctx, k, &lastword{Status: status})
return err
}
func getStatus(ctx context.Context, client *datastore.Client, key string) (string, error) {
k := datastore.NameKey(kind, key, nil)
var lw lastword
err := client.Get(ctx, k, &lw)
return lw.Status, err
}
func showError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, err.Error())
}
// LastWord is entrypoint
func LastWord(w http.ResponseWriter, r *http.Request) {
if r.FormValue("token") != authToken {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "need token param!")
return
}
ctx := context.Background()
client, err := datastore.NewClient(ctx, project)
if err != nil {
showError(w, err)
return
}
key := r.FormValue("key")
if key == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "need key param!")
return
}
if r.Method == http.MethodPost {
status := r.FormValue("status")
err := writeStatus(ctx, client, key, status)
if err != nil {
showError(w, err)
return
}
fmt.Fprintf(w, "wrote { %v: %v }", key, status)
return
}
status, err := getStatus(ctx, client, key)
if err != nil {
showError(w, err)
return
}
fmt.Fprintf(w, status)
}