-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (92 loc) · 2.46 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
// This program performs administrative tasks for the url-shortener service.
package main
import (
"errors"
"fmt"
"os"
"github.com/ardanlabs/conf/v3"
"go.uber.org/zap"
"github.com/illyasch/url-shortener/cmd/tooling/admin/commands"
"github.com/illyasch/url-shortener/pkg/data/database"
"github.com/illyasch/url-shortener/pkg/sys/logger"
)
// build is the git version of this program. It is set using build flags in the makefile.
var build = "develop"
func main() {
log, err := logger.New("ADMIN")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer log.Sync()
// Perform the startup and shutdown sequence.
if err := run(log); err != nil {
if !errors.Is(err, commands.ErrHelp) {
log.Errorw("startup", "ERROR", err)
}
log.Sync()
os.Exit(1)
}
}
func run(log *zap.SugaredLogger) error {
// Configuration
cfg := struct {
conf.Version
Args conf.Args
DB struct {
User string `conf:"default:postgres"`
Password string `conf:"default:postgres,mask"`
Host string `conf:"default:localhost"`
Name string `conf:"default:postgres"`
DisableTLS bool `conf:"default:true"`
}
}{
Version: conf.Version{
Build: build,
Desc: "copyright information here",
},
}
const prefix = "SHORTENER"
help, err := conf.Parse(prefix, &cfg)
if err != nil {
if errors.Is(err, conf.ErrHelpWanted) {
fmt.Println(help)
return nil
}
return fmt.Errorf("parsing config: %w", err)
}
out, err := conf.String(&cfg)
if err != nil {
return fmt.Errorf("generating config for output: %w", err)
}
log.Infow("startup", "config", out)
// Commands
dbConfig := database.Config{
User: cfg.DB.User,
Password: cfg.DB.Password,
Host: cfg.DB.Host,
Name: cfg.DB.Name,
DisableTLS: cfg.DB.DisableTLS,
}
return processCommands(cfg.Args, log, dbConfig)
}
// processCommands handles the execution of the commands specified on
// the command line.
func processCommands(args conf.Args, log *zap.SugaredLogger, dbConfig database.Config) error {
switch args.Num(0) {
case "migrate":
if err := commands.Migrate(dbConfig); err != nil {
return fmt.Errorf("migrating database: %w", err)
}
case "seed":
if err := commands.Seed(dbConfig); err != nil {
return fmt.Errorf("seeding database: %w", err)
}
default:
fmt.Println("migrate: create the schema in the database")
fmt.Println("seed: add data to the database")
fmt.Println("provide a command to get more help.")
return commands.ErrHelp
}
return nil
}