-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
88 lines (69 loc) · 1.77 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
package main
import (
"context"
"log"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type CAGR struct {
OneYear float64 `json:"1_year" bson:"1_year"`
ThreeYear float64 `json:"3_year" bson:"3_year"`
FiveYear float64 `json:"5_year" bson:"5_year"`
}
type Fund struct {
Name string `json:"name" bson:"name"`
Category string `json:"category" bson:"category"`
CAGR []CAGR `json:"cagr" bson:"cagr"`
Rating int `json:"rating" bson:"rating"`
}
var collection *mongo.Collection
func main() {
router := gin.Default()
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
collection = client.Database("mutual_funds").Collection("funds")
router.GET("/getAllFunds", getAllFunds)
router.POST("/addFund", addFund)
router.Run()
}
func addFund(c *gin.Context) {
var fund Fund
if err := c.ShouldBindJSON(&fund); err != nil {
c.JSON(400, gin.H{
"error": err.Error()})
return
}
_, err := collection.InsertOne(context.TODO(), fund)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"result": "success"})
}
func getAllFunds(c *gin.Context) {
cursor, err := collection.Find(context.TODO(), bson.M{})
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
defer cursor.Close(context.TODO())
var funds []Fund
for cursor.Next(context.TODO()) {
var fund Fund
if err := cursor.Decode(&fund); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
funds = append(funds, fund)
}
c.JSON(200, funds)
}