-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (75 loc) · 1.79 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
h "github.com/praveen4g0/url-shortner/api"
lr "github.com/praveen4g0/url-shortner/repository/local"
mr "github.com/praveen4g0/url-shortner/repository/mongodb"
rr "github.com/praveen4g0/url-shortner/repository/redis"
"github.com/praveen4g0/url-shortner/shortner"
)
// repo <- service -> serializer -> http
func main() {
repo := chooseRepo()
service := shortner.NewRedirectService(repo)
handler := h.NewHandler(service)
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/{code}", handler.Get)
r.Post("/", handler.Post)
errs := make(chan error, 2)
go func() {
fmt.Println("Listening on port ", httpPort())
errs <- http.ListenAndServe(httpPort(), r)
}()
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
errs <- fmt.Errorf("%s", <-c)
}()
fmt.Printf("Terminated %s", <-errs)
os.Exit(0)
}
func httpPort() string {
port := "8000"
if os.Getenv("PORT") != "" {
port = os.Getenv("PORT")
}
return fmt.Sprintf(":%s", port)
}
func chooseRepo() shortner.RedirectRepository {
switch os.Getenv("DB") {
case "redis":
redisURL := os.Getenv("REDIS_URL")
repo, err := rr.NewRedisRepository(redisURL)
if err != nil {
log.Fatal(err)
}
return repo
case "mongo":
mongoURL := os.Getenv("MONGO_URL")
mongodb := os.Getenv("MONGO_DB")
mongoTimeout, _ := strconv.Atoi(os.Getenv("MONGO_TIMEOUT"))
repo, err := mr.NewMongoRepository(mongoURL, mongodb, mongoTimeout)
if err != nil {
log.Fatal(err)
}
return repo
default:
repo, err := lr.NewLocalRepository()
if err != nil {
log.Fatal(err)
}
return repo
}
}