-
Notifications
You must be signed in to change notification settings - Fork 0
/
api1.go
71 lines (64 loc) · 1.75 KB
/
api1.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
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"net/http"
"time"
)
type Movies struct {
ID string `json:"id" bson:"_id, omitempty"`
Name string `json:"name" bson:"name"`
Release int `json:"date" bson: "Date"`
Collection string `json:"money" bson: "collection"`
}
var moviesCollection *mongo.Collection
//connect to mongodb
func connectToMongo() (*mongo.Client, error) {
clientoptions := options.Client().ApplyURI("mongodb://localhost:27017/")
client, err := mongo.NewClient(clientoptions)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
return nil, err
}
err = client.Ping(ctx, readpref.Primary())
if err != nil {
return nil, err
}
fmt.Println("Connected to MongoDB!")
return client, nil
}
func GetMovies(c *gin.Context) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cursor, err := moviesCollection.Find(ctx, bson.M{})
if err != nil {
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "cannot retrive movies"})
return
}
var movies []Movies
if err = cursor.All(ctx, &movies); err != nil {
c.IndentedJSON(http.StatusInternalServerError, gin.H{"message": "could not decode movies"})
return
}
c.IndentedJSON(http.StatusOK, movies)
}
func main() {
router := gin.Default()
client, err := connectToMongo()
if err != nil {
panic(err)
}
moviesCollection = client.Database("Films").Collection("Movies")
router.GET("/", GetMovies)
router.Run("localhost:8081")
}