-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
76 lines (65 loc) · 1.58 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
package main
import (
"encoding/json"
"flowers-server/config"
"flowers-server/models"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
func newRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/flower", getWaterings).Methods("GET")
r.HandleFunc("/flower", createNewWatering).Methods("POST")
return r
}
func main() {
envs := config.ReturnEnvs()
fmt.Println(envs)
const (
databaseName = "postgres"
password = "password"
user = "postgres"
instanceConnection = "${flowers-app-259015:europe-west1:flower-database}-p"
)
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable",
instanceConnection,
user,
password,
databaseName)
config.InitDB(dsn)
r := newRouter()
http.ListenAndServe(":8080", r)
}
func getWaterings(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), 405)
return
}
waterings, error := models.GetAllWaterings()
if error != nil {
http.Error(w, http.StatusText(500), 500)
return
}
js, err := json.Marshal(waterings)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("content-type", "application/json")
w.Write(js)
}
func createNewWatering(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
watering, err := models.CreateNewWatering(body)
js, err := json.Marshal(watering)
w.Header().Set("content-type", "application/json")
w.Write(js)
}