-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (66 loc) · 1.58 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
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
h "github.com/marcelluseasley/hex-ms-poc-1/api"
mr "github.com/marcelluseasley/hex-ms-poc-1/repository/mongodb"
rr "github.com/marcelluseasley/hex-ms-poc-1/repository/redis"
"github.com/marcelluseasley/hex-ms-poc-1/shortener"
)
func main() {
repo := chooseRepo()
service := shortener.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.Println("terminated", <-errs)
}
func httpPort() string {
port := "8000"
if os.Getenv("PORT") != "" {
port = os.Getenv("PORT")
}
return ":" + port
}
func chooseRepo() shortener.RedirectRepository {
switch os.Getenv("URL_DB") {
case "redis":
redisURL := os.Getenv("REDIS_URL")
repo, err := rr.NewRedisRepository(redisURL)
if err != nil {
panic(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 {
panic(err)
}
return repo
}
return nil
}