main.go (view raw)
1package main
2
3import (
4 "net/http"
5 "strconv"
6
7 "github.com/charmbracelet/log"
8 "github.com/gin-gonic/gin"
9
10 todo "github.com/1set/todotxt"
11)
12
13var todoFilePath string = "todo.txt"
14
15func main() {
16 gin.SetMode(gin.DebugMode)
17 router := gin.Default()
18 router.LoadHTMLGlob("templates/*.html")
19 router.Static("/static", "static/")
20
21 router.GET("/", loadTasksList)
22 router.POST("/", loadTasksList)
23
24 router.Run()
25}
26
27func loadTasksList(c *gin.Context) {
28 taskList := getTaskList()
29
30 id := c.PostForm("taskId")
31 content := c.PostForm("taskContent")
32
33 if id != "" {
34 taskId, err := strconv.Atoi(id)
35 if err != nil {
36 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
37 return
38 }
39
40 if updatedTask, err := taskList.GetTask(taskId); err != nil {
41 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "taskId": taskId})
42 return
43 } else {
44 if c.PostForm("checked") == "on" {
45 updatedTask.Complete()
46 } else {
47 updatedTask.Reopen()
48 }
49 }
50 taskList.WriteToPath(todoFilePath)
51 } else if content != "" {
52 newTask, _ := todo.ParseTask(content)
53 taskList.AddTask(newTask)
54 taskList.WriteToPath(todoFilePath)
55 }
56
57 c.HTML(http.StatusOK, "tasks-list.html", gin.H{
58 "tasks": taskList,
59 })
60}
61
62func getTaskList() todo.TaskList {
63 if tasklist, err := todo.LoadFromPath(todoFilePath); err != nil {
64 log.Fatalf("Can't load file %s", todoFilePath)
65 return nil
66 } else {
67 return tasklist
68 }
69}