forked from Taker-Academy/KeDuBak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (66 loc) · 1.46 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
package main
import (
"containerized-go-app/router"
"context"
"errors"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"os"
"time"
)
func connectToDB() (*mongo.Database, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
uri := os.Getenv("MONGO_URI")
if uri == "" {
return nil, errors.New("MONGO_URI is not set")
}
dbName := os.Getenv("DB_NAME")
if dbName == "" {
return nil, errors.New("DB_NAME is not set")
}
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
return nil, err
}
db := client.Database(dbName)
return db, err
}
func main() {
err := run()
if err != nil {
panic(err)
}
}
func run() error {
// load env variables
err := godotenv.Load()
if err != nil {
return err
}
//init database
db, err := connectToDB()
if err != nil {
log.Fatal(err)
}
//defer disconnect
defer db.Client().Disconnect(context.Background())
app := fiber.New()
app.Use(logger.New())
app.Use(recover.New())
app.Use(cors.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
router.AuthRoutes(app, db)
router.UserRoutes(app, db)
router.PostRoutes(app, db)
app.Listen(":8080")
return nil
}