-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (52 loc) · 1.26 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
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/xpero39/simple-books-api/controllers"
"github.com/xpero39/simple-books-api/db"
)
func main() {
addr := ":8080"
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("Error occurred: %s", err.Error())
}
dbUser, dbPassword, dbName :=
os.Getenv("POSTGRES_USER"),
os.Getenv("POSTGRES_PASSWORD"),
os.Getenv("POSTGRES_DB")
database, err := db.Initialize(dbUser, dbPassword, dbName)
if err != nil {
log.Fatalf("Could not set up database: %v", err)
}
defer database.Conn.Close()
httpHandler := controllers.NewController(database)
server := &http.Server{
Handler: httpHandler,
}
go func() {
server.Serve(listener)
}()
defer Stop(server)
log.Printf("Started server on %s", addr)
// listen for ctrl+c signal from terminal
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
log.Println(fmt.Sprint(<-ch))
log.Println("Stopping API server.")
}
func Stop(server *http.Server) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Printf("Could not shut down server correctly: %v\n", err)
os.Exit(1)
}
}