-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
106 lines (87 loc) · 2.22 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
package main
import (
"api-scorekeeper/server"
"database/sql"
"flag"
"fmt"
"os"
"github.com/bdharris08/scorekeeper"
"github.com/bdharris08/scorekeeper/score"
"github.com/bdharris08/scorekeeper/store"
_ "github.com/jackc/pgx/v4/stdlib"
)
var (
exampleDSN = "postgres://postgres:xxx@localhost:5432/postgres"
dsn = flag.String("dsn", exampleDSN, "dsn for postgres database")
routes = flag.Bool("routes", false, "Generate router documentation")
listenAddress = flag.String("listen", ":3000", "address to listen on")
)
// primitive config setup
// A production app might use a custom config package
// that enforces precedence between configuration sources
// which could be flags, env vars,
// or even remote sources like parameter store or secrets manager.
type config struct {
dsn string
listenAddress string
}
func getConfig() config {
conf := config{
listenAddress: ":3000",
}
flag.Parse()
switch {
case *dsn != exampleDSN:
conf.dsn = *dsn
case os.Getenv("DATABASE_URL") != "":
conf.dsn = os.Getenv("DATABASE_URL")
}
switch {
case *listenAddress != ":3000":
conf.listenAddress = *listenAddress
case os.Getenv("LISTEN") != "":
conf.listenAddress = os.Getenv("LISTEN")
}
return conf
}
func setupTrial(db *sql.DB) error {
stmt := `CREATE TABLE IF NOT EXISTS trial (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
value numeric NOT NULL
);`
_, err := db.Exec(stmt)
if err != nil {
return err
}
return nil
}
func main() {
conf := getConfig()
db, err := sql.Open("pgx", conf.dsn)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
defer db.Close()
if err = setupTrial(db); err != nil {
fmt.Fprintf(os.Stderr, "Unable to create trial db: %v\n", err)
os.Exit(1)
}
st, _ := store.NewSQLStore(db)
factory := score.ScoreFactory{
"trial": func() score.Score { return &score.Trial{} },
}
scoreKeeper, err := scorekeeper.New(st, factory)
if err != nil {
panic(fmt.Errorf("error creating scoreKeeper: %v", err))
}
scoreKeeper.Start()
defer scoreKeeper.Stop()
s := server.NewServer(scoreKeeper)
if *routes {
fmt.Println(s.Usage())
return
}
s.ListenAndServe(conf.listenAddress)
}