-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
159 lines (123 loc) · 3.41 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/gofiber/fiber/v2"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Todo struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Completed bool `json:"completed"`
Body string `json:"body"`
}
var collection *mongo.Collection
var Id int = 0
func main() {
fmt.Println("Hello World")
if os.Getenv("ENV") != "production" {
err := godotenv.Load(".env")
if err != nil {
log.Fatal("Error loading .env file", err)
}
}
MONGODB_URI := os.Getenv("MONGODB_URI")
clientOptions := options.Client().ApplyURI(MONGODB_URI)
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(context.Background())
fmt.Println("Connected to MONGODB ATLAS")
collection = client.Database("golang_db").Collection("todos")
app := fiber.New()
// app.Use(cors.New(cors.Config{
// AllowOrigins: "http://localhost:5173",
// AllowHeaders: "Origin,Content-Type,Accept",
// }))
app.Get("/api/todos", getTodos)
app.Post("/api/todos", createTodos)
app.Patch("/api/todos/:id", updateTodos)
app.Delete("/api/todos/:id", deleteTodos)
port := os.Getenv("PORT")
if port == "" {
port = "5000"
}
if os.Getenv("ENV") == "production" {
app.Static("/", "./client/dist")
}
log.Fatal(app.Listen("0.0.0.0:" + port))
}
func getTodos(c *fiber.Ctx) error {
var todos []Todo
cursor, err := collection.Find(context.Background(), bson.M{})
if err != nil {
return err
}
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
var todo Todo
if err := cursor.Decode(&todo); err != nil {
return err
}
todos = append(todos, todo)
}
return c.JSON(todos)
}
func createTodos(c *fiber.Ctx) error {
todo := new(Todo)
if err := c.BodyParser(todo); err != nil {
return err
}
if todo.Body == "" {
return c.Status(400).JSON(fiber.Map{"error": "body is required"})
}
insertResult, err := collection.InsertOne(context.Background(), todo)
if err != nil {
return err
}
todo.ID = insertResult.InsertedID.(primitive.ObjectID)
return c.Status(201).JSON(todo)
}
func updateTodos(c *fiber.Ctx) error {
id := c.Params("id")
objectId, err := primitive.ObjectIDFromHex(id)
if err != nil {
return c.Status(400).JSON(fiber.Map{"error": "invalid id"})
}
filter := bson.M{"_id": objectId}
var todo bson.M
err = collection.FindOne(context.Background(), filter).Decode(&todo)
if err != nil {
return c.Status(404).JSON(fiber.Map{"error": "todo not found"})
}
currentCompleted := todo["completed"].(bool)
update := bson.M{"$set": bson.M{"completed": !currentCompleted}}
_, err = collection.UpdateOne(context.Background(), filter, update)
if err != nil {
return err
}
return c.Status(200).JSON(fiber.Map{"success": true})
}
func deleteTodos(c *fiber.Ctx) error {
id := c.Params("id")
objectId, err := primitive.ObjectIDFromHex(id)
if err != nil {
return c.Status(400).JSON(fiber.Map{"error": "invalid id"})
}
filter := bson.M{"_id": objectId}
_, err = collection.DeleteOne(context.Background(), filter)
if err != nil {
return err
}
return c.Status(200).JSON(fiber.Map{"success": true})
}