-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (77 loc) · 2.33 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
89
90
91
92
// Recipes API
//
// This is the Recipe API
//
// Schemes: http
// Host: localhost:8080
// BasePath: /
// Version: 1.0.0
// Contact: M Umer Masood <umermasood.dev@gmail.com> https://github.com/umermasood
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// swagger:meta
package main
import (
"context"
"github.com/gin-contrib/cors"
"godwagin/handlers"
"log"
"os"
"github.com/gin-contrib/sessions"
redisStore "github.com/gin-contrib/sessions/redis"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
var authHandler *handlers.AuthHandler
var recipesHandler *handlers.RecipesHandler
func init() {
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
if err != nil {
panic(err)
}
if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {
log.Fatal(err)
}
log.Println("Connected to MongoDB")
recipesCollection := client.Database(os.Getenv("MONGO_DATABASE")).Collection("recipes")
redisClient := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
status := redisClient.Ping(ctx)
log.Println(status)
recipesHandler = handlers.NewRecipesHandler(ctx, recipesCollection, redisClient)
usersCollection := client.Database(os.Getenv("MONGO_DATABASE")).Collection("users")
authHandler = handlers.NewAuthHandler(ctx, usersCollection)
}
func main() {
router := gin.Default()
router.Use(cors.Default())
store, _ := redisStore.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
router.Use(sessions.Sessions("recipes_api", store))
router.GET("/recipes", recipesHandler.ListRecipesHandler)
router.POST("/login", authHandler.LoginHandler)
router.POST("/refresh", authHandler.RefreshHandler)
router.POST("/logout", authHandler.LogoutHandler)
authorized := router.Group("/")
authorized.Use(authHandler.AuthMiddleware())
{
authorized.POST("/recipes", recipesHandler.NewRecipeHandler)
authorized.PUT("/recipes/:id", recipesHandler.UpdateRecipeHandler)
authorized.DELETE("/recipes/:id", recipesHandler.DeleteRecipeHandler)
authorized.GET("/recipes/:id", recipesHandler.GetOneRecipeHandler)
}
if err := router.Run(); err != nil {
return
}
}