forked from sosedoff/pgweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
141 lines (111 loc) · 2.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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package main
import (
"fmt"
"os"
"os/exec"
"os/signal"
"github.com/gin-gonic/gin"
"github.com/sosedoff/pgweb/pkg/api"
"github.com/sosedoff/pgweb/pkg/client"
"github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/connection"
"github.com/sosedoff/pgweb/pkg/util"
)
var options command.Options
func exitWithMessage(message string) {
fmt.Println("Error:", message)
os.Exit(1)
}
func initClient() {
if connection.IsBlank(command.Opts) {
return
}
cl, err := client.New()
if err != nil {
exitWithMessage(err.Error())
}
if command.Opts.Debug {
fmt.Println("Server connection string:", cl.ConnectionString)
}
fmt.Println("Connecting to server...")
err = cl.Test()
if err != nil {
exitWithMessage(err.Error())
}
fmt.Println("Checking tables...")
_, err = cl.Tables()
if err != nil {
exitWithMessage(err.Error())
}
api.DbClient = cl
}
func initOptions() {
err := command.ParseOptions()
if err != nil {
os.Exit(1)
}
options = command.Opts
if options.Version {
printVersion()
os.Exit(0)
}
printVersion()
}
func printVersion() {
str := fmt.Sprintf("Pgweb v%s", command.VERSION)
if command.GitCommit != "" {
str += fmt.Sprintf(" (git: %s)", command.GitCommit)
}
fmt.Println(str)
}
func startServer() {
router := gin.Default()
// Enable HTTP basic authentication only if both user and password are set
if options.AuthUser != "" && options.AuthPass != "" {
auth := map[string]string{options.AuthUser: options.AuthPass}
router.Use(gin.BasicAuth(auth))
}
api.SetupRoutes(router)
fmt.Println("Starting server...")
go func() {
err := router.Run(fmt.Sprintf("%v:%v", options.HttpHost, options.HttpPort))
if err != nil {
fmt.Println("Cant start server:", err)
os.Exit(1)
}
}()
}
func handleSignals() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
<-c
}
func openPage() {
url := fmt.Sprintf("http://%v:%v", options.HttpHost, options.HttpPort)
fmt.Println("To view database open", url, "in browser")
if options.SkipOpen {
return
}
_, err := exec.Command("which", "open").Output()
if err != nil {
return
}
exec.Command("open", url).Output()
}
func main() {
initOptions()
initClient()
if api.DbClient != nil {
defer api.DbClient.Close()
}
if !options.Debug {
gin.SetMode("release")
}
// Print memory usage every 30 seconds with debug flag
if options.Debug {
util.StartProfiler()
}
startServer()
openPage()
handleSignals()
}