-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
126 lines (107 loc) · 2.21 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
package main
import (
"flag"
"log"
"net/http"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"github.com/rs/cors"
)
type Config struct {
HTTP struct {
Listen string
}
Postgres struct {
User string
Password string
DBName string
Host string
Port int
}
LevelDB struct {
Dir string
}
}
func (config *Config) PostgresDSN() string {
dsn := []string{}
include := func(name, value string) {
if value != "" {
dsn = append(dsn, name+"="+value)
}
}
p := &config.Postgres
include("user", p.User)
include("password", p.Password)
include("dbname", p.DBName)
include("host", p.Host)
if p.Port == 0 {
include("port", "5432")
} else {
include("port", strconv.Itoa(p.Port))
}
return strings.Join(dsn, " ")
}
var (
configFile = flag.String("config", "config.toml", "configuration file")
)
func main() {
flag.Parse()
var config Config
meta, err := toml.DecodeFile(*configFile, &config)
if err != nil {
log.Fatal(err)
}
if len(meta.Undecoded()) > 0 {
log.Printf("unused keys: %v\n", meta.Undecoded())
}
if config.HTTP.Listen == "" {
config.HTTP.Listen = ":8000"
}
if config.LevelDB.Dir == "" {
config.LevelDB.Dir = "data"
}
if flag.Arg(0) == "migrate" {
log.Println("Migrating")
log.Println("LevelDB: ", config.LevelDB.Dir)
ldb, err := NewLevelDB(config.LevelDB.Dir)
if err != nil {
log.Fatal(err)
}
defer ldb.Close()
dsn := config.PostgresDSN()
log.Println("Postgres: ", dsn)
pgdb, err := NewPostgresDB(dsn)
if err != nil {
log.Fatal(err)
}
defer pgdb.Close()
count, err := pgdb.MigrateFrom(ldb)
if err != nil {
log.Fatal(err)
}
log.Println("Migration complete", count)
return
}
var store Store
if dsn := config.PostgresDSN(); dsn != "" {
log.Println("Postgres: ", dsn)
pgdb, err := NewPostgresDB(dsn)
if err != nil {
log.Fatal(err)
}
defer pgdb.Close()
store = pgdb
} else {
log.Println("LevelDB: ", config.LevelDB.Dir)
ldb, err := NewLevelDB(config.LevelDB.Dir)
if err != nil {
log.Fatal(err)
}
defer ldb.Close()
store = ldb
}
server := NewServer(store)
log.Printf("Starting server on %s\n", config.HTTP.Listen)
log.Fatal(http.ListenAndServe(config.HTTP.Listen, cors.Default().Handler(server)))
}