-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
125 lines (97 loc) · 2.34 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
package main
import (
"context"
"encoding/json"
"github.com/gofiber/fiber"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
const dbName = "personsdb"
const collectionName = "person"
const port = 8000
func getPerson(c *fiber.Ctx) {
collection, err := getMongoDbCollection(dbName, collectionName)
if err != nil {
c.Status(500).Send(err)
return
}
var filter bson.M = bson.M{}
if c.Params("id") != "" {
id := c.Params("id")
objID, _ := primitive.ObjectIDFromHex(id)
filter = bson.M{"_id": objID}
}
var results []bson.M
cur, err := collection.Find(context.Background(), filter)
defer cur.Close(context.Background())
if err != nil {
c.Status(500).Send(err)
return
}
cur.All(context.Background(), &results)
if results == nil {
c.SendStatus(404)
return
}
json, _ := json.Marshal(results)
c.Send(json)
}
func createPerson(c *fiber.Ctx) {
collection, err := getMongoDbCollection(dbName, collectionName)
if err != nil {
c.Status(500).Send(err)
return
}
var person Person
json.Unmarshal([]byte(c.Body()), &person)
res, err := collection.InsertOne(context.Background(), person)
if err != nil {
c.Status(500).Send(err)
return
}
response, _ := json.Marshal(res)
c.Send(response)
}
func updatePerson(c *fiber.Ctx) {
collection, err := getMongoDbCollection(dbName, collectionName)
if err != nil {
c.Status(500).Send(err)
return
}
var person Person
json.Unmarshal([]byte(c.Body()), &person)
update := bson.M{
"$set": person,
}
objID, _ := primitive.ObjectIDFromHex(c.Params("id"))
res, err := collection.UpdateOne(context.Background(), bson.M{"_id": objID}, update)
if err != nil {
c.Status(500).Send(err)
return
}
response, _ := json.Marshal(res)
c.Send(response)
}
func deletePerson(c *fiber.Ctx) {
collection, err := getMongoDbCollection(dbName, collectionName)
if err != nil {
c.Status(500).Send(err)
return
}
objID, _ := primitive.ObjectIDFromHex(c.Params("id"))
res, err := collection.DeleteOne(context.Background(), bson.M{"_id": objID})
if err != nil {
c.Status(500).Send(err)
return
}
jsonResponse, _ := json.Marshal(res)
c.Send(jsonResponse)
}
func main() {
app := fiber.New()
app.Get("/person/:id?", getPerson)
app.Post("/person", createPerson)
app.Put("/person/:id", updatePerson)
app.Delete("/person/:id", deletePerson)
app.Listen(port)
}