-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
82 lines (71 loc) · 1.85 KB
/
main.go
File metadata and controls
82 lines (71 loc) · 1.85 KB
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
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/joho/godotenv"
"github.com/rithikjain/GistsBackend/api/handler"
"github.com/rithikjain/GistsBackend/pkg/gists"
"github.com/rithikjain/GistsBackend/pkg/user"
"log"
"net/http"
"os"
)
func dbConnect(host, port, user, dbname, password, sslmode string) (*gorm.DB, error) {
// In the case of heroku
if os.Getenv("DATABASE_URL") != "" {
return gorm.Open("postgres", os.Getenv("DATABASE_URL"))
}
db, err := gorm.Open(
"postgres",
fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=%s", host, port, user, dbname, password, sslmode),
)
return db, err
}
func GetPort() string {
var port = os.Getenv("PORT")
if port == "" {
fmt.Println("INFO: No PORT environment variable detected, defaulting to 3000")
return "localhost:3000"
}
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())
}
db.AutoMigrate(&user.User{})
defer db.Close()
fmt.Println("Connected to DB...")
db.LogMode(true)
// Setting up the router
r := http.NewServeMux()
gistsSvc := gists.NewService(db)
handler.MakeGistsHandler(r, gistsSvc)
userRepo := user.NewRepo(db)
userSvc := user.NewService(userRepo)
handler.MakeUserHandler(r, userSvc)
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("Hello There"))
return
})
fmt.Println("Serving...")
log.Fatal(http.ListenAndServe(GetPort(), r))
}