got a JSON response from the database
This commit is contained in:
@@ -1,11 +1,39 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
"log"
|
||||
|
||||
"github.com/captbrogers/MagicStreamServer/database"
|
||||
"github.com/captbrogers/MagicStreamServer/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
)
|
||||
|
||||
var movieCollection *mongo.Collection = database.OpenCollection("movies")
|
||||
|
||||
func GetMovies() gin.HandlerFunc {
|
||||
return func(ginContext *gin.Context) {
|
||||
ginContext.JSON(200, gin.H{"message": "list of movies"})
|
||||
return func(ginCtx *gin.Context) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var movies []models.Movie
|
||||
|
||||
cursor, err := movieCollection.Find(ctx, bson.M{})
|
||||
if err != nil {
|
||||
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch movies"})
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
if err = cursor.All(ctx, &movies); err != nil {
|
||||
log.Fatalf("Failed to decode: %v", err)
|
||||
ginCtx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to decode movies"})
|
||||
}
|
||||
|
||||
ginCtx.JSON(http.StatusOK, movies)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user