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
13func main() {
14 router := gin.Default()
15 config := getConfig()
16
17 router.LoadHTMLGlob("templates/*.html")
18 router.Static("/static", "static/")
19
20 router.GET("/", loadTasksList)
21 router.POST("/", loadTasksList)
22
23 server := http.Server{
24 Addr: ":4443",
25 Handler: router,
26 TLSConfig: getTLSConfig(config),
27 }
28 defer server.Close()
29 log.Fatal(server.ListenAndServeTLS("", ""))
30}
31
32func loadTasksList(c *gin.Context) {
33 config := getConfig() // TODO Fix: YAML config file is read for each request
34 taskList := getTaskList(config.TodoPath)
35
36 id := c.PostForm("taskId")
37 content := c.PostForm("taskContent")
38
39 if id != "" {
40 taskId, err := strconv.Atoi(id)
41 if err != nil {
42 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
43 return
44 }
45
46 if updatedTask, err := taskList.GetTask(taskId); err != nil {
47 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "taskId": taskId})
48 return
49 } else {
50 if c.PostForm("checked") == "on" {
51 updatedTask.Complete()
52 } else {
53 updatedTask.Reopen()
54 }
55 }
56 taskList.WriteToPath(config.TodoPath)
57 } else if content != "" {
58 newTask, _ := todo.ParseTask(content)
59 taskList.AddTask(newTask)
60 taskList.WriteToPath(config.TodoPath)
61 }
62
63 c.HTML(http.StatusOK, "tasks-list.html", gin.H{
64 "tasks": taskList,
65 })
66}
67
68func getTaskList(todoFilePath string) todo.TaskList {
69 if tasklist, err := todo.LoadFromPath(todoFilePath); err != nil {
70 log.Fatalf("Can't load file %s", todoFilePath)
71 return nil
72 } else {
73 return tasklist
74 }
75}