bouncer/internal/command/database/ping.go

49 lines
1.1 KiB
Go

package database
import (
"database/sql"
"forge.cadoles.com/cadoles/bouncer/internal/command/common"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"gitlab.com/wpetit/goweb/logger"
)
func PingCommand() *cli.Command {
return &cli.Command{
Name: "ping",
Usage: "Test database connectivity",
Action: func(ctx *cli.Context) error {
conf, err := common.LoadConfig(ctx)
if err != nil {
return errors.Wrap(err, "Could not load configuration")
}
logger.Info(ctx.Context, "connecting to database", logger.F("dsn", conf.Database.DSN))
driver := string(conf.Database.Driver)
dsn := string(conf.Database.DSN)
db, err := sql.Open(driver, dsn)
if err != nil {
return errors.WithStack(err)
}
defer func() {
if err := db.Close(); err != nil {
logger.Error(ctx.Context, "error while closing database connection", logger.E(errors.WithStack(err)))
}
}()
if err := db.PingContext(ctx.Context); err != nil {
return errors.WithStack(err)
}
logger.Info(ctx.Context, "connection succeeded", logger.F("dsn", conf.Database.DSN))
return nil
},
}
}