-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
89 lines (65 loc) · 1.69 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
package main
import (
"fmt"
"log"
"os"
"github.com/gofiber/fiber/v2"
"github.com/joho/godotenv"
)
type Todo struct {
ID int `json:"id"`
Completed bool `json:"completed"`
Body string `json:"body"`
}
func main() {
fmt.Println("Hello world")
app := fiber.New()
err := godotenv.Load(".env")
if err != nil{
log.Fatal("Error loading .env file")
}
PORT := os.Getenv("PORT")
todos := []Todo{}
app.Get("/api/todos", func(c *fiber.Ctx) error {
return c.Status(200).JSON(todos)
})
app.Post("/api/todos", func(c *fiber.Ctx) error {
todo := &Todo{}
/*
err := c.BodyParser(todo)
if err != nil { // This is the condition being checked
return err
}
*/
if err := c.BodyParser(todo); err != nil { // err call a method and that likely return an error; if err is different than null, it has an error
return err
}
if todo.Body == "" {
return c.Status(400).JSON(fiber.Map{"error": "Todo body is required"})
}
todo.ID = len(todos) + 1
todos = append(todos, *todo)
return c.Status(201).JSON(todo)
})
app.Patch("/api/todos/:id", func(c *fiber.Ctx) error { // Update
id := c.Params("id")
for i, todo := range todos {
if fmt.Sprint(todo.ID) == id {
todos[i].Completed = true
return c.Status(200).JSON(todos[i])
}
}
return c.Status(404).JSON(fiber.Map{"error": "Todo not found"})
})
app.Delete("/api/todos/:id", func(c *fiber.Ctx) error {
id := c.Params("id")
for i, todo := range todos {
if fmt.Sprint(todo.ID) == id {
todos = append(todos[:i], todos[i+1:]...)
return c.Status(200).JSON(todos[i])
}
}
return c.Status(404).JSON(fiber.Map{"error": "Todo not found"})
})
log.Fatal(app.Listen(":"+PORT))
}