-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (76 loc) · 2.02 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
package main
import (
"context"
"database/sql"
_ "embed"
"fmt"
"log"
"os"
"strings"
_ "github.com/mattn/go-sqlite3"
"github.com/peterbourgon/ff/v4"
"github.com/peterbourgon/ff/v4/ffhelp"
)
//go:embed schema.sql
var ddl string
func initDB(ctx context.Context) *sql.DB {
db, err := sql.Open("sqlite3", "golim.sqlite")
if err != nil {
log.Fatal(err)
}
// create tables
if _, err := db.ExecContext(ctx, ddl); err != nil && !strings.Contains(err.Error(), "already exists") {
log.Fatal(err)
}
return db
}
// everything start from main
func main() {
ctx := context.Background()
logger := initLogger()
db := initDB(ctx)
cache := initRedis()
limiter, err := initFlags(ctx, db, cache, logger)
if err != nil {
logger.errLog.Println(err.Error())
log.Fatalf("Error initializing limiter: %v", err)
}
data, err := limiter.ExecCMD(ctx)
if err != nil {
logger.errLog.Println(err.Error())
log.Fatalf("Error executing command: %v", err)
}
if data != nil {
makeTable(toSlice(data))
}
fmt.Println("DONE")
}
// initFlags get command and flags from std input to create a golim or role
func initFlags(ctx context.Context, db *sql.DB, cache *cache, logger *logger) (*golim, error) {
golim := newLimiter(db, cache, logger)
rootCmd := createRootCommand(golim)
if err := rootCmd.ParseAndRun(ctx, os.Args[1:]); err != nil {
return nil, fmt.Errorf("%s\n%s", ffhelp.Command(rootCmd), err)
}
return golim, nil
}
func createRootCommand(g *golim) *ff.Command {
rootFlags := ff.NewFlagSet("golim")
helpCMD := g.createHelpCMD()
initCMD := g.createInitCMD()
addCMD := g.createAddCMD()
removeCMD := g.createRemoveCMD()
getCMD := g.createGetRolesCMD()
removeLimiterCMD := g.addRemoveLimiterCMD()
runCMD := g.createRunCMD()
rootCmd := &ff.Command{
Name: "golim",
Usage: "golim [COMMANDS] <FLAGS>",
Flags: rootFlags,
Subcommands: []*ff.Command{helpCMD, initCMD, addCMD, removeCMD, getCMD, removeLimiterCMD, runCMD},
Exec: func(ctx context.Context, args []string) error {
return nil
},
}
return rootCmd
}