-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
101 lines (78 loc) · 2.16 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
package main
import (
"html/template"
"net/http"
"strconv"
)
var tmpl *template.Template
type Todo struct {
Item string
Done bool
}
type PageData struct {
Title string
Todos []Todo
}
var todos []Todo
func todoHandler(w http.ResponseWriter, r *http.Request) {
data := PageData{
Title: "TODO List",
Todos: todos,
}
err := tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func addHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
newTask := r.FormValue("newTask")
if newTask != "" {
todos = append(todos, Todo{Item: newTask, Done: false})
}
http.Redirect(w, r, "/todo", http.StatusSeeOther)
}
func updateHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
index, err := strconv.Atoi(r.URL.Path[len("/update/"):])
if err != nil || index < 0 || index >= len(todos) {
http.Error(w, "Invalid task index", http.StatusBadRequest)
return
}
updatedTask := r.FormValue("updateTask")
done := r.FormValue("done") == "on"
todos[index].Item = updatedTask
todos[index].Done = done
http.Redirect(w, r, "/todo", http.StatusSeeOther)
}
func deleteHandler(w http.ResponseWriter, r *http.Request) {
index, err := strconv.Atoi(r.URL.Path[len("/delete/"):])
if err != nil || index < 0 || index >= len(todos) {
http.Error(w, "Invalid task index", http.StatusBadRequest)
return
}
todos = append(todos[:index], todos[index+1:]...)
http.Redirect(w, r, "/todo", http.StatusSeeOther)
}
func main() {
todos = []Todo{
{Item: "Install GO", Done: true},
{Item: "Learn Go", Done: false},
}
mux := http.NewServeMux()
tmpl = template.Must(template.ParseFiles("templates/index.gohtml"))
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
mux.HandleFunc("/todo", todoHandler)
mux.HandleFunc("/add", addHandler)
mux.HandleFunc("/update/", updateHandler)
mux.HandleFunc("/delete/", deleteHandler)
http.ListenAndServe(":8080", mux)
}