-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello.go
99 lines (90 loc) · 2.45 KB
/
hello.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
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/gofiber/fiber/v2"
"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 Body struct {
Name string `json:"name"`
Marks int `json:"marks"`
}
func main() {
app := fiber.New()
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
panic(err)
}
coll := client.Database("health_cube").Collection("patients")
app.Get("/", func(c *fiber.Ctx) error {
fmt.Println("Endpoint hit")
return c.SendString("Hello, World 👋!")
})
app.Get("/:id", func(c *fiber.Ctx) error {
id, error := primitive.ObjectIDFromHex(c.Params("id"))
if error != nil {
return c.Status(400).SendString("wrong id format")
}
res := coll.FindOne(context.TODO(), bson.M{
"_id": id,
})
body := new(Body)
if res.Decode(body) != nil {
return c.Status(404).SendString("not found")
}
bodyJson, _ := json.Marshal(body)
return c.SendString(string(bodyJson))
})
app.Post("/", func(c *fiber.Ctx) error {
body := new(Body)
if error := c.BodyParser(&body); error != nil {
return c.Status(400).SendString(error.Error())
}
if res, error := coll.InsertOne(context.TODO(), body); err != nil {
return c.Status(400).SendString(error.Error())
} else {
fmt.Println(res.InsertedID)
return c.SendString(fmt.Sprintln(res.InsertedID))
}
})
app.Delete("/:id", func(c *fiber.Ctx) error {
requestId := c.Params("id")
parsedId, error := primitive.ObjectIDFromHex(requestId)
if error != nil {
return c.Status(400).SendString("wrong id format")
}
_, error = coll.DeleteOne(context.TODO(), bson.M{
"_id": parsedId,
})
if error != nil {
return c.Status(404).SendString("not found")
}
return c.SendString("ok")
})
app.Put("/:id", func(c *fiber.Ctx) error {
requestId := c.Params("id")
parsedId, error := primitive.ObjectIDFromHex(requestId)
if error != nil {
return c.Status(400).SendString("wrong id format")
}
body := new(Body)
c.BodyParser(&body)
_, err := coll.UpdateOne(
context.TODO(),
bson.M{"_id": parsedId},
bson.D{
{Key: "$set", Value: bson.D{{Key: "name", Value: body.Name}}},
{Key: "$set", Value: bson.D{{Key: "marks", Value: body.Marks}}},
},
)
if err != nil {
return c.Status(404).SendString("not found")
}
return c.SendString("ok")
})
app.Listen(":3000")
}