-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
executable file
·191 lines (176 loc) · 5.66 KB
/
http.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package k8szoo
import (
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"errors"
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
//var store = sessions.NewCookieStore(os.Getenv("SESSION_KEY"))
var store = sessions.NewCookieStore([]byte("GO_SESS"))
func HealthHandler(response http.ResponseWriter, request *http.Request) {
response.Header().Add("Content-type", "text/plain")
fmt.Fprint(response, "I'm okay jack!")
}
func NotFoundHandler(response http.ResponseWriter, request *http.Request) {
response.Header().Add("X-Template-File", "html"+request.URL.Path)
tmpl := template.Must(template.ParseFiles("html/404.html"))
tmpl.Execute(response, nil)
}
func CSSHandler(response http.ResponseWriter, request *http.Request) {
response.Header().Add("Content-type", "text/css")
tmpl := template.Must(template.ParseFiles("html/cover.css"))
tmpl.Execute(response, nil)
}
func getAnimalFromSession(response http.ResponseWriter, request *http.Request) (int, error) {
session, err := store.Get(request, "session-name")
if err != nil {
return -1, err
}
var animalID int
if session.Values["chosenAnimal"] == nil {
animalID, _ = ReserveRandomAnimal()
//name := Animals[animalID].AnimalName
fmt.Printf("[Existing session] Reserving %s (%d) for %s\n", "something", animalID, session.ID)
session.Values["chosenAnimal"] = animalID
} else {
sessionAnimalID := session.Values["chosenAnimal"]
var ok bool
if animalID, ok = sessionAnimalID.(int); !ok {
return -1, errors.New("Conversion error")
}
if IsAnimalReserved(Animals[animalID].AnimalName) == false {
fmt.Printf("[New session] Reserving %s (%d) for %s\n", Animals[animalID].AnimalName, animalID, session.ID)
err = ReserveAnimalByName(Animals[animalID].AnimalName)
if err != nil {
animalID, _ = ReserveRandomAnimal()
session.Values["chosenAnimal"] = animalID
}
} else {
fmt.Printf("Session %s has %s (%d) reserved.\n", session.ID, Animals[animalID].AnimalName, animalID)
}
return animalID, nil
}
err = session.Save(request, response)
if err != nil {
return -1, err
}
return animalID, nil
}
func RandomAnimalHandler(response http.ResponseWriter, request *http.Request) {
type TemplateData struct {
Animal AnimalData
Templates []string
TotalCount int
AvailCount int
}
animalID, err := getAnimalFromSession(response, request)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
tmpl := template.Must(template.ParseFiles(filepath.FromSlash("html/index.html")))
animal := Animals[animalID]
templates, err := filepath.Glob(filepath.FromSlash("./html/example/*.yaml"))
if err != nil {
templates = []string{}
}
for i, _ := range templates {
thistemplate := strings.Split(templates[i], string(os.PathSeparator))
templates[i] = thistemplate[len(thistemplate)-1]
}
data := TemplateData{
Animal: animal,
Templates: templates,
TotalCount: len(Animals),
AvailCount: len(AvailableAnimals),
}
tmpl.Execute(response, data)
}
func TemplateHandler(response http.ResponseWriter, request *http.Request) {
animalID, err := getAnimalFromSession(response, request)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
response.Header().Add("X-Template-File", "html"+request.URL.Path)
// tmpl, err := template.New("html"+request.URL.Path).Funcs(template.FuncMap{
// "ToUpper": strings.ToUpper,
// "ToLower": strings.ToLower,
// }).ParseFiles("html"+request.URL.Path)
_ = strings.ToLower("Hello")
if strings.Index(request.URL.Path, "/") < 0 {
http.Error(response, "No slashes wat - "+request.URL.Path, http.StatusInternalServerError)
return
}
basenameSlice := strings.Split(request.URL.Path, "/")
basename := basenameSlice[len(basenameSlice)-1]
//fmt.Fprintf(response, "%q", basenameSlice)
tmpl, err := template.New(basename).Funcs(template.FuncMap{
"ToUpper": strings.ToUpper,
"ToLower": strings.ToLower,
}).ParseFiles("html" + request.URL.Path)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
// NotFoundHandler(response, request)
// return
}
err = tmpl.Execute(response, Animals[animalID])
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
}
func ReleaseHandler(response http.ResponseWriter, request *http.Request) {
session, err := store.Get(request, "session-name")
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
animalID, err := getAnimalFromSession(response, request)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
animal := Animals[animalID]
err = ReleaseAnimalByName(animal.AnimalName)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
session.Values["chosenAnimal"] = nil
err = session.Save(request, response)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(response, request, "/", http.StatusSeeOther)
return
}
func HandleHTTP() {
r := mux.NewRouter()
loggedRouter := handlers.LoggingHandler(os.Stdout, r)
r.NotFoundHandler = http.HandlerFunc(NotFoundHandler)
r.HandleFunc("/", RandomAnimalHandler)
r.HandleFunc("/healthz", HealthHandler)
r.HandleFunc("/release", ReleaseHandler)
r.HandleFunc("/example/{.*}", TemplateHandler)
r.HandleFunc("/cover.css", CSSHandler)
http.Handle("/", r)
srv := &http.Server{
Handler: loggedRouter,
Addr: "0.0.0.0:5353",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
fmt.Println("Listening on 0.0.0.0:5353")
copy(AvailableAnimals, Animals)
srv.ListenAndServe()
}