forked from nickrobison-usds/demand-modeler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
172 lines (150 loc) · 4.11 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/nickrobison-usds/demand-modeling/api"
"github.com/nickrobison-usds/demand-modeling/cmd"
"github.com/nickrobison-usds/demand-modeling/dbbackend"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
)
func main() {
// Initialize logger
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
app := &cli.App{
Name: "Fearless Dreamer",
Commands: []*cli.Command{
cmd.USALoaderCMD(),
},
Action: runServer,
}
err := app.Run(os.Args)
if err != nil {
log.Fatal().Err(err).Send()
}
}
func runServer(c *cli.Context) error {
workDir, err := os.Getwd()
if err != nil {
log.Fatal().Err(err).Send()
}
filesDir := filepath.Join(workDir, "ui/build")
url := getDBURL()
// Do the migration
err = migrateDatabase(url, workDir)
// Load it up
ctx := c.Context
backend, err := dbbackend.NewBackend(ctx, url)
if err != nil {
log.Fatal().Err(err).Send()
}
defer backend.Shutdown()
go func() {
log.Info().Msg("Beginning background data load")
start := time.Now()
loader, err := cmd.NewLoader(ctx, url, filepath.Join(workDir, "data"))
if err != nil {
log.Fatal().Err(err).Send()
}
defer loader.Close()
err = loader.Load()
if err != nil {
log.Fatal().Err(err).Send()
}
end := time.Now()
duration := end.Sub(start)
log.Info().Dur("load_time", duration).Msg("Background data load completed")
}()
return serve(backend, filesDir)
}
func serve(backend api.DataBackend, filesDir string) error {
r := chi.NewRouter()
r.Use(api.BackendContext(backend))
// A good base middleware stack
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Setup CORS
// Basic CORS
// for more ideas, see: https://developer.github.com/v3/#cross-origin-resource-sharing
corsHandler := cors.New(cors.Options{
// AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
AllowedOrigins: []string{"*"},
// AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
r.Use(corsHandler.Handler)
// Get the port
var port string
portenv := os.Getenv("PORT")
if portenv == "" {
port = "8080"
} else {
port = portenv
}
r.Route("/api", api.MakeRouter)
FileServer(r, "", "/", http.Dir(filesDir))
log.Printf("Listening on %s", port)
return http.ListenAndServe(":"+port, r)
}
// FileServer conveniently sets up a http.FileServer handler to serve
// static files from a http.FileSystem.
func FileServer(r chi.Router, basePath string, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit URL parameters.")
}
fs := http.StripPrefix(basePath+path, http.FileServer(root))
path += "*"
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
})
}
func migrateDatabase(dbURL string, workDir string) error {
migrationDir := fmt.Sprintf("file://%s", filepath.Join(workDir, "db", "migrations"))
log.Printf("Connecting to %s from location: %s\n", dbURL, migrationDir)
m, err := migrate.New(
migrationDir,
dbURL)
if err != nil {
return err
}
err = m.Up()
if err != nil && err != migrate.ErrNoChange {
return err
}
return nil
}
func getDBURL() string {
//if cfenv.IsRunningOnCF() {
// app, err := cfenv.Current()
// if err != nil {
// log.Fatal(err)
// }
//
// serv, err := app.Services.WithName("fearless-dreamer-psql")
// if err != nil {
// log.Fatal(err)
// }
//
// url, _ := serv.CredentialString("uri")
// return url
//} else {
return os.Getenv("DATABASE_URL")
//}
}