-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
65 lines (55 loc) · 1.31 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
h "github.com/a-Osama/urlshortner/api"
re "github.com/a-Osama/urlshortner/repository/mongodb"
shortner "github.com/a-Osama/urlshortner/shortner"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func httpPort() string {
port := "8000"
if os.Getenv("PORT") != "" {
port = os.Getenv("PORT")
}
return fmt.Sprintf(":%s", port)
}
func mongoConf() shortner.RedirectRepository {
mongoURL := os.Getenv("MONGO_URL")
mongodb := os.Getenv("MONGO_DB")
mongoTimeout, _ := strconv.Atoi(os.Getenv("MONGO_TIMEOUT"))
repo, err := re.NewMongoRepository(mongoURL, mongodb, mongoTimeout)
if err != nil {
log.Fatal(err)
}
return repo
}
func main() {
repo := mongoConf()
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 :8000")
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)
}