-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
185 lines (153 loc) · 4.62 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
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
package main
import (
"fmt"
"github.com/rs/cors"
"html"
"html/template"
"log"
"net/http"
"os"
"strings"
)
func greeting() string {
person := getPerson()
podName := getPodName()
return fmt.Sprintf("hello %s from %s", person, podName)
}
func getPodName() string {
podName := os.Getenv("POD_NAME")
if podName == "" {
podName = "local process"
}
return podName
}
func getPerson() string {
person := os.Getenv("PERSON")
if person == "" {
person = "you"
}
return person
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
// use the greeting function to get the greeting message
message := greeting()
log.Printf("Greeting:%s", message)
_, err := fmt.Fprintf(w, message)
if err != nil {
return
}
})
mux.HandleFunc("/", serveFrontend)
mux.HandleFunc("/list", handleList)
mux.HandleFunc("/add", handleAdd)
mux.HandleFunc("/delete", handleDelete)
// Specify the port you want your server to listen to
port := "8080"
fmt.Printf("Server is starting on port %s\n", port)
fs := http.FileServer(http.Dir("static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
// CORS handler
handler := cors.New(cors.Options{
//Allow any domain... useful for a demo but not for production
AllowedOrigins: []string{"*"},
AllowCredentials: true,
Debug: true,
}).Handler(mux)
// Start the server and log if there is an error
if err := http.ListenAndServe(":"+port, handler); err != nil {
log.Fatalf("Failed to start server: %+v", err)
}
}
type PageData struct {
Name string
PodName string
}
func serveFrontend(writer http.ResponseWriter, request *http.Request) {
t, _ := template.ParseFiles("static/index.html")
data := PageData{
Name: getPerson(),
PodName: getPodName(),
}
err := t.Execute(writer, data)
if err != nil {
return
}
}
func handleList(writer http.ResponseWriter, request *http.Request) {
key := "itemsList"
client := newRedisClient()
items, err := client.LRange(ctx, key, 0, -1).Result()
if err != nil {
http.Error(writer, "Failed to fetch items", http.StatusInternalServerError)
log.Fatalf("Failed to start server: %+v", err)
}
htmlResponse := generateHTMLforItems(items)
fmt.Fprintf(writer, htmlResponse)
}
func handleAdd(writer http.ResponseWriter, request *http.Request) {
key := "itemsList"
// assuming application/x-www-form-urlencoded data
if err := request.ParseForm(); err != nil {
http.Error(writer, "Invalid Form data", 400)
return
}
item := request.FormValue("item")
// use Redis client to add the item
client := newRedisClient()
if err := client.RPush(ctx, key, item).Err(); err != nil {
http.Error(writer, "Failed to add item", http.StatusInternalServerError)
return
}
writer.WriteHeader(http.StatusCreated)
items, err := client.LRange(ctx, key, 0, -1).Result()
if err != nil {
http.Error(writer, "Failed to fetch items", http.StatusInternalServerError)
log.Fatalf("Failed to start server: %+v", err)
}
htmlResponse := generateHTMLforItems(items)
fmt.Fprintf(writer, htmlResponse)
}
func generateHTMLforItems(items []string) string {
var htmlBuilder strings.Builder
htmlBuilder.WriteString("<ul class='items-list' id='items-list'>")
for _, item := range items {
safeItem := html.EscapeString(item)
htmlBuilder.WriteString(fmt.Sprintf("<li class='item'><span class='item-name'>%s</span> <button class='btn delete-btn' hx-post='/delete' hx-target='#items-list' hx-swap='outerHTML' hx-vals='{\"item\":\"%s\"}'>Delete</button></li>", safeItem, safeItem))
}
htmlBuilder.WriteString("</ul>")
return htmlBuilder.String()
}
func handleDelete(writer http.ResponseWriter, request *http.Request) {
client := newRedisClient()
// For simplicity, we're reading the item to be deleted from the form data
if err := request.ParseForm(); err != nil {
http.Error(writer, "Failed to parse request", http.StatusBadRequest)
return
}
item := request.PostFormValue("item")
if item == "" {
http.Error(writer, "Item is required", http.StatusBadRequest)
return
}
// Assume 'itemsList' is the Redis list key
key := "itemsList"
// Remove the item from the list stored in Redis
_, err := client.LRem(ctx, key, 0, item).Result()
if err != nil {
http.Error(writer, "Failed to delete item", http.StatusInternalServerError)
return
}
writer.WriteHeader(http.StatusAccepted)
items, err := client.LRange(ctx, key, 0, -1).Result()
if err != nil {
http.Error(writer, "Failed to fetch items", http.StatusInternalServerError)
log.Fatalf("Failed to start server: %+v", err)
}
htmlResponse := generateHTMLforItems(items)
_, err = fmt.Fprintf(writer, htmlResponse)
if err != nil {
return
}
}