-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
112 lines (104 loc) · 2.43 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"context"
"database/sql"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"dv4all/goauth2/pgdb"
"dv4all/goauth2/routes"
"dv4all/goauth2/utils"
)
// AppName holds application name
var AppName string
// connection to postgres
func oauth2DB() *sql.DB {
// get connection props from environment
pgHost := utils.GetEnv("PG_HOST", "localhost")
pgPort, _ := strconv.Atoi(utils.GetEnv("PG_PORT", "5432"))
pgUser := utils.GetEnv("PG_USER", "postgres")
pgPass := utils.GetEnv("PG_PASS", "changeme")
pgDb := utils.GetEnv("PG_DB", "oauth_db")
// connect to postgres database
cnnStr := pgdb.ConnectionStr(pgdb.Settings{
Host: pgHost,
Port: pgPort,
User: pgUser,
Password: pgPass,
Dbname: pgDb,
})
// println(cnnStr)
db := pgdb.Connect(cnnStr)
//close connection at the end
return db
}
// start http server
func oauth2HTTP() *http.Server {
// get host url and port
apiHost := utils.GetEnv("OAUTH2_HOST", ":8080")
// create new router
mux := routes.Register()
// create https server
srv := &http.Server{
Addr: apiHost,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 20 * time.Second,
}
log.Printf("%v...starting on...%v", AppName, apiHost)
return srv
}
// shutdown http server
func shutdownServer(db *sql.DB, api *http.Server) {
if db != nil {
log.Println("sqlDB...closing...")
edb := db.Close()
if edb != nil {
log.Printf("sqlDB.Close() failed: %v", edb)
}
}
if api != nil {
log.Println("http...closing...")
err := api.Shutdown(context.Background())
if err != nil {
log.Printf("http closing failed: %v", err)
}
}
log.Printf("%v...stopped", AppName)
}
// Listen for system close events
func onCloseAPI(close chan bool) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// wait for sigs
log.Printf("os.Signal...%v", <-sigs)
// os signal send notify others now
close <- true
}
func main() {
// load AppName
AppName = utils.GetEnv("OAUTH2_NAME", "go-oauth2-api")
// create close channel
close := make(chan bool, 1)
//connect to database
db := oauth2DB()
//start api on http
api := oauth2HTTP()
//run api in separate routine
go func(api *http.Server) {
err := api.ListenAndServe()
if err != nil {
log.Fatalf("%v server failed: %v", AppName, err)
}
}(api)
//listen for close events
go onCloseAPI(close)
//wait for close event
<-close
//close DB and api
shutdownServer(db, api)
}