-
Notifications
You must be signed in to change notification settings - Fork 10
/
handlers.go
201 lines (161 loc) · 5.2 KB
/
handlers.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
192
193
194
195
196
197
198
199
200
201
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"strings"
"time"
)
var tmpl *template.Template
/* var funcMap = template.FuncMap{
"equal": func(n int) bool { return n == 5 },
"inc": func(n int) int { return n + 1 },
} */
/* templates will be parsed once at package first import */
func init() {
if tmpl == nil {
if tmpl == nil {
tmpl = template.Must(tmpl.ParseGlob("views/layouts/*.html"))
template.Must(tmpl.ParseGlob("views/*.html"))
template.Must(tmpl.ParseGlob("views/partials/*.html"))
}
}
}
func ShowHomePage(w http.ResponseWriter, r *http.Request) {
year := time.Now().Year()
data := map[string]any{
"Title": "Go & HTMx Demo",
"Year": year,
}
tmpl.ExecuteTemplate(w, "index.html", data)
}
func ShowAboutPage(w http.ResponseWriter, r *http.Request) {
year := time.Now().Year()
data := map[string]any{
"Title": "About Me | Go & HTMx Demo",
"Year": year,
}
tmpl.ExecuteTemplate(w, "about.html", data)
}
func GetNotes(w http.ResponseWriter, r *http.Request) {
// time.Sleep(500 * time.Millisecond) // only to check how the spinner works
// fmt.Println("Time Zone: ", r.Header.Get("X-TimeZone"))
var intPage int
intPage, _ = strconv.Atoi(r.URL.Query().Get("page"))
if intPage == 0 {
intPage = 1
}
offset := (intPage - 1) * 5
note := new(Note)
notesSlice, err := note.GetAllNotes(offset)
if err != nil {
log.Fatalf("something went wrong: %s", err.Error())
}
convertedNotes := []ConvertedNote{}
for _, note := range notesSlice {
newConvertedNote := convertDateTime(note, r.Header.Get("X-TimeZone"))
convertedNotes = append(convertedNotes, newConvertedNote)
}
data := map[string]any{
"Notes": convertedNotes,
"IncPage": intPage + 1,
"ShowMore": len(convertedNotes) == 5,
}
tmpl.ExecuteTemplate(w, "note-list", data)
}
func AddNote(w http.ResponseWriter, r *http.Request) {
title := strings.Trim(r.PostFormValue("title"), " ")
description := strings.Trim(r.PostFormValue("description"), " ")
if len(title) == 0 || len(description) == 0 {
var errTitle, errDescription string
if len(title) == 0 {
errTitle = "Please enter a title in this field"
}
if len(description) == 0 {
errDescription = "Please enter a description in this field"
}
data := map[string]string{
"FormTitle": title,
"FormDescription": description,
"ErrTitle": errTitle,
"ErrDescription": errDescription,
}
w.Header().Set("HX-Retarget", "form")
w.Header().Set("HX-Reswap", "innerHTML")
tmpl.ExecuteTemplate(w, "new-note-form", data)
return
}
newNote := new(Note)
newNote.Title = title
newNote.Description = description
_, err := newNote.CreateNote()
if err != nil {
var message string
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
message = "The title is already in use 🔥!"
} else if strings.Contains(err.Error(), "CHECK constraint failed") {
message = "The title is longer than 64 characters 🔥!"
} else {
message = fmt.Sprintf("Something went wrong: %s 🔥!", err)
}
w.Header().Set("HX-Retarget", "body")
w.Header().Set("HX-Reswap", "beforeend")
tmpl.ExecuteTemplate(w, "modal", message)
return
}
w.Header().Set("HX-Location", "/")
}
func CompleteNote(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(r.URL.Query().Get("id"))
note := new(Note)
note.ID = id
recoveredNote, err := note.GetNoteById()
if err != nil {
// w.Header().Set("HX-Trigger", "{\"myEvent\":\"The requested note was not found 😱!\"}")
w.Header().Set("HX-Retarget", "body")
w.Header().Set("HX-Reswap", "beforeend")
tmpl.ExecuteTemplate(w, "modal", "The requested note was not found 😱!")
return
}
updatedNote, err := recoveredNote.UpdateNote()
if err != nil {
log.Fatalf("something went wrong: %s", err.Error())
}
tmpl.ExecuteTemplate(w, "note-list-element", convertDateTime(updatedNote, r.Header.Get("X-TimeZone")))
}
func RemoveNote(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(r.URL.Query().Get("id"))
note := new(Note)
note.ID = id
err := note.DeleteNote()
if err != nil {
w.Header().Set("HX-Retarget", "body")
w.Header().Set("HX-Reswap", "beforeend")
tmpl.ExecuteTemplate(w, "modal", "The requested note was not found 😱!")
return
}
w.Header().Set("HX-Location", "/")
}
/* HOW TO EXTRACT URL QUERY PARAMETERS IN GO. VER:
https://freshman.tech/snippets/go/extract-url-query-params/
Parsear parámetros. VER:
https://www.sitepoint.com/get-url-parameters-with-go/
https://www.golangprograms.com/how-do-you-set-headers-in-an-http-response-in-go.html
ALTERNATIVE FORM FOR MODAL:
{{ define "modal" }}
<div id="modal"
_="on closeModal add .closing then wait for animationend then remove me then reload() the location of the window end on myEvent from body put event.detail.value into #message then show me"
style="display: none;">
<div class="modal-underlay" _="on click trigger closeModal"></div>
<div class="modal-content relative bg-base-100 p-6 rounded-2xl">
<h3 class="font-bold text-lg">Go & HTMx Demo</h3>
<p id="message" class="py-4"></p>
<button _="on click trigger closeModal" class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">
✕
</button>
</div>
</div>
{{ end }}
*/