-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (58 loc) · 1.85 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
package main
import (
"context"
"go-api/handlers"
"log"
"os"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func getMongoUri() string {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
return os.Getenv("MONGO_URI")
}
var recipesHandler *handlers.RecipesHandler
func init() {
// recipes = make([]Recipe, 0)
// file, _ := ioutil.ReadFile("recipes.json")
// _ = json.Unmarshal([]byte(file), &recipes)
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(getMongoUri()))
if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {
log.Fatal(err)
}
collection := client.Database("recipesdb").Collection("recipes")
log.Println("Conntected to MongoDB")
redisClient := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 0,
})
recipesHandler = handlers.NewRecipesHandler(ctx, collection, redisClient)
// var listOfRecipes []interface{}
// for _, recipe := range recipes {
// recipe.ID = primitive.NewObjectID()
// listOfRecipes = append(listOfRecipes, recipe)
// }
// collection := client.Database("recipesdb").Collection("recipes")
// insertManyResult, err := collection.InsertMany(ctx, listOfRecipes)
// if err != nil {
// log.Fatal(err)
// }
// log.Println("Inserted recipes: ", len(insertManyResult.InsertedIDs))
}
func main() {
router := gin.Default()
router.GET("/recipes", recipesHandler.GetRecipesHandler)
router.GET("/recipes/:id", recipesHandler.GetRecipeByIdHandler)
router.POST("/recipes", recipesHandler.CreateRecipeHandler)
router.PUT("/recipes/:id", recipesHandler.UpdateRecipeHandler)
router.DELETE("/recipes/:id", recipesHandler.DeleteRecipeHandler)
router.Run()
}