-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (81 loc) · 2.03 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
93
94
95
96
97
98
99
package main
import (
"fmt"
"log"
"os"
"os/signal"
"strconv"
"syscall"
fiber "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/requestid"
h "github.com/lrweck/shawty/api"
mdb "github.com/lrweck/shawty/repository/mongodb"
pg "github.com/lrweck/shawty/repository/postgresql"
red "github.com/lrweck/shawty/repository/redis"
"github.com/lrweck/shawty/shortener"
)
func main() {
repo := chooseRepo()
service := shortener.NewRedirectService(repo)
hand := h.NewHandler(service)
app := fiber.New()
app.Use(requestid.New())
app.Use(logger.New())
app.Use(recover.New())
app.Get("/:code", hand.Get)
app.Post("/", hand.Post)
errs := make(chan error, 2)
go func() {
fmt.Println("Listening on port", httpPort())
errs <- app.Listen(httpPort())
}()
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
errs <- fmt.Errorf("%s", <-c)
}()
fmt.Printf("Terminated: %s", <-errs)
}
func httpPort() string {
port := "8000"
if os.Getenv("PORT") != "" {
port = os.Getenv("PORT")
}
return fmt.Sprintf(":%s", port)
}
func chooseRepo() shortener.RedirectRepository {
fmt.Println("choose db")
switch os.Getenv("URL_DB") {
case "pg":
pgURL := os.Getenv("PG_URL")
pgTimeout, _ := strconv.Atoi(os.Getenv("PG_TIMEOUT"))
repo, err := pg.NewPGRepo(pgURL, pgTimeout)
if err != nil {
log.Fatal(err)
}
return repo
case "redis":
redisURL := os.Getenv("REDIS_URL")
repo, err := red.NewRedisRepository(redisURL)
if err != nil {
log.Fatal(err)
}
fmt.Println("choose REDIS")
return repo
case "mongo":
mongoURL := os.Getenv("MONGO_URL")
mongoDB := os.Getenv("MONGO_DB")
mongoTimeout, _ := strconv.Atoi(os.Getenv("MONGO_TIMEOUT"))
fmt.Println("choose MONGO")
repo, err := mdb.NewMongoRepo(mongoURL, mongoDB, mongoTimeout)
// fmt.Printf("Mongo URL: %s \n", mongoURL)
if err != nil {
log.Fatal(err)
}
return repo
}
fmt.Println("choose NOTHING")
// return nil
}