-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
80 lines (69 loc) · 1.44 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
package main
import (
"fmt"
"log"
"os"
"github.com/urfave/cli/v2"
"github.com/xo/dburl"
"go.uber.org/fx"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var (
GlobalFlagsInst = &GlobalFalgs{}
)
func main() {
app := &cli.App{
Name: "demo",
Action: run,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "database-url",
Usage: "Database URL",
EnvVars: []string{"DATABASE_URL"},
Required: true,
Destination: &GlobalFlagsInst.DatabaseURL,
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
type GlobalFalgs struct {
DatabaseURL string
}
func run(cCtx *cli.Context) error {
app := fx.New(
fx.Provide(connectDatabase),
fx.Invoke(
func(db *gorm.DB) {
// database migration
db.AutoMigrate(&User{})
// insert data
db.Create(&User{
Name: "John Doe",
})
},
),
)
return app.Start(cCtx.Context)
}
func connectDatabase() (*gorm.DB, error) {
dbUrl, err := dburl.Parse(GlobalFlagsInst.DatabaseURL)
if err != nil {
return nil, err
}
switch dbUrl.Driver {
case "sqlite", "sqlite3":
return gorm.Open(sqlite.Open(dbUrl.DSN), &gorm.Config{})
case "mysql", "mariadb":
return gorm.Open(mysql.Open(dbUrl.DSN), &gorm.Config{})
case "postgres", "postgresql", "pg":
return gorm.Open(postgres.Open(dbUrl.DSN), &gorm.Config{})
default:
return nil, fmt.Errorf("unsupported database type: %s", dbUrl.Driver)
}
}