-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
100 lines (90 loc) · 2.26 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"cloud.google.com/go/firestore"
"context"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
)
type User struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Age int32 `json:"age"`
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", indexHandler).Methods("GET")
r.HandleFunc("/users", putUserHandler).Methods("PUT")
r.HandleFunc("/users", getUserHandler).Methods("GET")
http.Handle("/", r)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
log.Printf("Open http://localhost:%s in the browser", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
version := os.Getenv("VERSION")
_, err := fmt.Fprintf(w, "Hello, World! %v", version)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
func putUserHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
projectID := os.Getenv("PROJECT_ID")
client, err := firestore.NewClient(ctx, projectID)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
defer client.Close()
var u *User
err = json.NewDecoder(r.Body).Decode(&u)
if err != nil {
log.Fatalf("Failed to parse request body: %v", err)
}
user := User {
FirstName: u.FirstName,
LastName: u.LastName,
Age: u.Age,
}
_, _, err = client.Collection("users").Add(ctx, user)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Println(w)
}
func getUserHandler(w http.ResponseWriter, r *http.Request) {
projectID := os.Getenv("PROJECT_ID")
ctx := context.Background()
client, err := firestore.NewClient(ctx, projectID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
var user User
userList := []User{}
docs, err := client.Collection("users").Documents(ctx).GetAll()
if err != nil {
// handle error
}
for _, doc := range docs {
doc.DataTo(&user)
userList = append(userList, user)
}
w.Header().Set("Content-Type", "application/json")
hoge, _ := json.Marshal(userList)
fmt.Fprintln(w, string(hoge))
}