-
Notifications
You must be signed in to change notification settings - Fork 2
/
collect.go
88 lines (77 loc) · 2.07 KB
/
collect.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
package main
import (
"fmt"
"net/http"
"os"
"github.com/go-pg/pg"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
// server is an object which implements the http.Handler interface (passes to
// router) and related connection objects hang off it (e.g. db conn)
type server struct {
router mux.Router
db *pg.DB
}
// envCheck is called upon startup to ensure the required environment variables
// are set
func envCheck() {
// ensure config vars set
reqd := []string{
"PGUSER",
"PGHOST",
"PGPORT",
"PGPASSWORD",
"PGDATABASE",
"JWT_SECRET_KEY",
"DASH_NETWORK",
"BIND_HOST",
"BIND_PORT",
}
missing := false
for _, env := range reqd {
val, ok := os.LookupEnv(env)
if !ok || (len(val) == 0) {
missing = true
fmt.Fprintf(os.Stderr, "error: required env var %s not set\n", env)
}
}
if missing {
os.Exit(1)
}
if val := os.Getenv("DASH_NETWORK"); val != "testnet" && val != "mainnet" {
fmt.Fprintf(os.Stderr, "error: unknown Dash network '%s'\n", val)
fmt.Fprintf(os.Stderr, "\texpected \"mainnet\" or \"testnet\"\n")
os.Exit(1)
}
}
func main() {
envCheck()
// create a PG database connection
db := pg.Connect(&pg.Options{
User: os.Getenv("PGUSER"),
Addr: os.Getenv("PGHOST") + ":" + os.Getenv("PGPORT"),
Password: os.Getenv("PGPASSWORD"),
Database: os.Getenv("PGDATABASE"),
})
defer db.Close()
// create the database tables if they don't exist
err := createSchema(db)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
// create a server object and add db connection
srv := server{
db: db,
}
srv.routes()
// allow CORS w/mux router
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
// serve the API
listenAt := os.Getenv("BIND_HOST") + ":" + os.Getenv("BIND_PORT")
fmt.Printf("%s listening at %s\n", os.Args[:1], listenAt)
http.ListenAndServe(listenAt, handlers.CORS(originsOk, headersOk, methodsOk)(srv))
}