-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
97 lines (75 loc) · 2.53 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/anGie44/theOffice-api/handlers"
"github.com/anGie44/theOffice-api/models"
"github.com/caarlos0/env/v9"
gohandlers "github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/go-openapi/runtime/middleware"
)
type config struct {
Port int `env:"PORT" envDefault:"8080"`
DBHost string `env:"MONGODB_HOST" envDefault:"localhost"`
DBDatabase string `env:"MONGODB_DATABASE" envDefault:"the-office"`
DBCollection string `env:"MONGODB_COLLECTION" envDefault:"quotes"`
DBUsername string `env:"MONGODB_USERNAME" envDefault:"boss"`
DBPassword string `env:"MONGODB_PASSWORD" envDefault:"password"`
}
func main() {
l := log.New(os.Stdout, "theOffice-api ", log.LstdFlags)
cfg := config{}
if err := env.Parse(&cfg); err != nil {
l.Printf("Error parsing environment config: %s\n", err)
os.Exit(1)
}
// Create MongoDB Client
dbOpts := models.NewQuotesDBOptions(cfg.DBHost, cfg.DBDatabase, cfg.DBUsername, cfg.DBPassword, cfg.DBCollection)
db := models.NewQuotesDB(dbOpts, l)
wh := handlers.NewWelcome(l)
qh := handlers.NewQuotes(l, db)
sm := mux.NewRouter()
getRouter := sm.Methods(http.MethodGet).Subrouter()
getRouter.HandleFunc("/", wh.Welcome)
// Deprecated handlers
getRouter.HandleFunc("/season/{season:[1-9]}/format/{format:quotes|connections}", qh.GetQuotesBySeasonWithFormat)
getRouter.HandleFunc("/season/{season:[1-9]}/episode/{episode:[1-9]|[1][0-9]|2[0-3]}", qh.GetQuotesBySeasonAndEpisode)
// V2 handlers to use request body for filtering data
getRouter.HandleFunc("/v2/quotes", qh.GetQuotes)
// handler for documentation
opts := middleware.RedocOpts{SpecURL: "/swagger.yaml"}
sh := middleware.Redoc(opts, nil)
getRouter.Handle("/docs", sh)
getRouter.Handle("/swagger.yaml", http.FileServer(http.Dir("./docs")))
// CORS
ch := gohandlers.CORS(gohandlers.AllowedOrigins([]string{"*"}))
s := http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: ch(sm),
ErrorLog: l,
ReadTimeout: 1 * time.Minute,
IdleTimeout: 2 * time.Minute,
}
go func() {
l.Printf("Starting server on port %d\n", cfg.Port)
err := s.ListenAndServe()
if err != nil {
l.Printf("Error starting server: %s\n", err)
os.Exit(1)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
// Block until a signal is received
sig := <-c
log.Println("Received signal:", sig)
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
s.Shutdown(ctx)
}