-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
60 lines (47 loc) · 1.42 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
package main
import (
"database/sql"
"fmt"
"net/http"
"os"
"github.com/belimawr/url-shortener/db"
"github.com/belimawr/url-shortener/handlers"
"github.com/belimawr/url-shortener/middleware"
"github.com/caarlos0/env/v6"
"github.com/go-chi/chi"
"github.com/google/uuid"
_ "github.com/lib/pq"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
)
type config struct {
Port int `env:"HTTP_PORT" envDefault:"3000"`
DBConnStr string `env:"DB_CONN_STR" envDefault:"host=localhost user=db_user dbname=url sslmode=disable"`
}
func main() {
cfg := config{}
if err := env.Parse(&cfg); err != nil {
panic(fmt.Sprintf("cannot parse configuration: %s", err.Error()))
}
logger := zerolog.New(os.Stdout).With().
Timestamp().
Logger()
logger = logger.Output(zerolog.NewConsoleWriter())
dbConn, err := sql.Open("postgres", cfg.DBConnStr)
if err != nil {
logger.Panic().Err(err).Msg("cannot connect to databse")
}
if err := dbConn.Ping(); err != nil {
logger.Panic().Err(err).Msg("cannot ping database")
}
h := handlers.New(db.NewPostgres(dbConn), uuid.NewString)
r := chi.NewRouter()
r.Use(hlog.NewHandler(logger))
r.Use(middleware.RequestID("req_id", "Request-Id"))
r.Use(middleware.RequestLogger)
r.Get("/", handlers.Hello)
r.Get("/save", h.SaveURL)
r.Get("/go", h.GetURL)
logger.Info().Msgf("starting HTTP server at port %d", cfg.Port)
panic(http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), r))
}