-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_go_tutorial
More file actions
76 lines (59 loc) · 1.48 KB
/
main_go_tutorial
File metadata and controls
76 lines (59 loc) · 1.48 KB
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
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{}
if err := c.BodyParser(todo); err != nil {
return err
}
if todo.Body == "" {
return c.Status(400).JSON(fiber.Map{"msg": "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 {
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(fiber.Map{"success": "True"})
}
}
return c.Status(404).JSON(fiber.Map{"error": "Todo not found"})
})
log.Fatal(app.Listen(":" + PORT))
}