-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.go
54 lines (46 loc) · 1.32 KB
/
app.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
package main
import "fmt"
import "net/http"
import "os"
import "github.com/go-chi/chi"
import "github.com/jmoiron/sqlx"
import _ "github.com/go-sql-driver/mysql"
func main() {
mapper := func(name string) string {
value := os.Getenv(name)
switch name {
case "DB_HOST":
if value == "" {
value = "localhost"
}
case "DB_NAME", "DB_USER", "DB_PASSWORD":
if value == "" {
fmt.Fprintf(os.Stderr, "%s env variable is not set or empty\n", name)
os.Exit(1)
}
}
return value
}
dsn := os.Expand("${DB_USER}:${DB_PASSWORD}@tcp(${DB_HOST}:3306)/${DB_NAME}", mapper)
db, err := sqlx.Open("mysql", dsn)
if err != nil {
fmt.Fprintf(os.Stderr, "sqlx.Open failed: %v\n", err)
os.Exit(1)
}
defer db.Close()
if err = db.Ping(); err != nil {
fmt.Fprintf(os.Stderr, "Ping failed: could not connect to database: %v\n", err)
os.Exit(1)
}
r := chi.NewRouter()
registerRoutes(r, db)
registerCustomRoutes(r, db)
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
fmt.Println("Listen on " + port)
err = http.ListenAndServe(":"+port, r)
fmt.Fprintf(os.Stderr, "ListenAndServe failed: %v\n", err)
os.Exit(1)
}