/
main.go
92 lines (80 loc) · 2.13 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
package main
import (
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/joho/godotenv"
"github.com/rithikjain/motorq-task-backend/api/handler"
"github.com/rithikjain/motorq-task-backend/pkg/class"
"github.com/rithikjain/motorq-task-backend/pkg/models"
"github.com/rithikjain/motorq-task-backend/pkg/student"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
"os"
)
func dbConnect(host, port, user, dbname, password, sslmode string) (*gorm.DB, error) {
// In the case of heroku
if os.Getenv("onServer") == "True" {
return gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{})
}
db, err := gorm.Open(
postgres.Open(fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=%s", host, port, user, dbname, password, sslmode)),
&gorm.Config{},
)
return db, err
}
func GetPort() string {
var port = os.Getenv("PORT")
if port == "" {
fmt.Println("INFO: No PORT environment variable detected, defaulting to 4000")
return "localhost:4000"
}
return ":" + port
}
func main() {
if os.Getenv("onServer") != "True" {
// Loading the .env file
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
// Setting up DB
db, err := dbConnect(
os.Getenv("dbHost"),
os.Getenv("dbPort"),
os.Getenv("dbUser"),
os.Getenv("dbName"),
os.Getenv("dbPass"),
os.Getenv("sslmode"),
)
if err != nil {
log.Fatalf("Error connecting to the database: %s", err.Error())
}
// Migrating tables
err = db.AutoMigrate(
&models.Student{},
&models.Building{},
&models.Course{},
&models.Class{},
)
if err != nil {
log.Fatal(err.Error())
}
app := fiber.New(fiber.Config{CaseSensitive: true})
app.Use(logger.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hey there looks like its working 🔥")
})
// Student
studentRepo := student.NewRepo(db)
studentSvc := student.NewService(studentRepo)
handler.MakeStudentHandler(app, studentSvc)
// Class
classRepo := class.NewRepo(db)
classSvc := class.NewService(classRepo)
handler.MakeClassHandler(app, classSvc)
fmt.Println("Serving...")
log.Fatal(app.Listen(GetPort()))
}