-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
99 lines (77 loc) · 1.98 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
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"net/http"
"os"
"drehnstrom.com/go-pets/petsdb"
)
var projectID string
func main() {
projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
log.Fatal(`You need to set the environment variable "GOOGLE_CLOUD_PROJECT"`)
}
log.Printf("GOOGLE_CLOUD_PROJECT is set to %s", projectID)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Port set to: %s", port)
fs := http.FileServer(http.Dir("assets"))
mux := http.NewServeMux()
// This serves the static files in the assets folder
mux.Handle("/assets/", http.StripPrefix("/assets/", fs))
// The rest of the routes
mux.HandleFunc("/", indexHandler)
mux.HandleFunc("/about", aboutHandler)
log.Printf("Webserver listening on Port: %s", port)
http.ListenAndServe(":"+port, mux)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
var pets []petsdb.Pet
pets, error := petsdb.GetPets()
if error != nil {
fmt.Print(error)
}
data := HomePageData{
PageTitle: "Pets Home Page",
Pets: pets,
}
var tpl = template.Must(template.ParseFiles("templates/index.html", "templates/layout.html"))
buf := &bytes.Buffer{}
err := tpl.Execute(buf, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println(err.Error())
return
}
buf.WriteTo(w)
log.Println("Home Page Served")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
data := AboutPageData{
PageTitle: "About Go Pets",
}
var tpl = template.Must(template.ParseFiles("templates/about.html", "templates/layout.html"))
buf := &bytes.Buffer{}
err := tpl.Execute(buf, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println(err.Error())
return
}
buf.WriteTo(w)
log.Println("About Page Served")
}
// HomePageData for Index template
type HomePageData struct {
PageTitle string
Pets []petsdb.Pet
}
// AboutPageData for About template
type AboutPageData struct {
PageTitle string
}