/
main.go
86 lines (76 loc) · 2.44 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
// Recipes API
//
// This is a sample recipes API. You can find out more about the API at https://github.com/PacktPublishing/Building-Distributed-Applications-in-Gin.
//
// Schemes: http
// Host: localhost:8080
// BasePath: /
// Version: 1.0.0
// Contact: Mohamed Labouardy <mohamed@labouardy.com> https://labouardy.com
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
// swagger:meta
package main
import (
"context"
"log"
"os"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis"
handlers "github.com/mlabouardy/recipes-api/handlers"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
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(os.Getenv("MONGO_URI")))
if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {
log.Fatal(err)
}
log.Println("Connected to MongoDB")
var listOfRecipes []interface{}
for _, recipe := range recipes {
listOfRecipes = append(listOfRecipes, recipe)
}
collection := client.Database(os.Getenv("MONGO_DATABASE")).Collection("recipes")
insertManyResult, err := collection.InsertMany(ctx, listOfRecipes)
if err != nil {
log.Fatal(err)
}
log.Println("Inserted recipes: ", len(insertManyResult.InsertedIDs))*/
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {
log.Fatal(err)
}
log.Println("Connected to MongoDB")
collection := client.Database(os.Getenv("MONGO_DATABASE")).Collection("recipes")
redisClient := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
status := redisClient.Ping()
log.Println(status)
recipesHandler = handlers.NewRecipesHandler(ctx, collection, redisClient)
}
func main() {
router := gin.Default()
router.POST("/recipes", recipesHandler.NewRecipeHandler)
router.GET("/recipes", recipesHandler.ListRecipesHandler)
router.PUT("/recipes/:id", recipesHandler.UpdateRecipeHandler)
router.DELETE("/recipes/:id", recipesHandler.DeleteRecipeHandler)
router.GET("/recipes/:id", recipesHandler.GetOneRecipeHandler)
/*
router.GET("/recipes/search", SearchRecipesHandler)*/
router.Run()
}