70 lines
2.2 KiB
Go
70 lines
2.2 KiB
Go
package shared
|
|
|
|
import (
|
|
"context"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"git.maronato.dev/maronato/goshort/internal/config"
|
|
"git.maronato.dev/maronato/goshort/internal/storage"
|
|
memorystorage "git.maronato.dev/maronato/goshort/internal/storage/memory"
|
|
sqlitestorage "git.maronato.dev/maronato/goshort/internal/storage/sqlite"
|
|
"github.com/peterbourgon/ff/v3"
|
|
)
|
|
|
|
type Command struct {
|
|
// cfg is the command config populated by Parse.
|
|
cfg *config.Config
|
|
// exec is the command execution function.
|
|
exec func(context.Context, *config.Config) error
|
|
}
|
|
|
|
func NewCommand(cfg *config.Config, exec func(context.Context, *config.Config) error) *Command {
|
|
return &Command{
|
|
cfg: cfg,
|
|
exec: exec,
|
|
}
|
|
}
|
|
|
|
func (c *Command) Exec(ctx context.Context, _ []string) error {
|
|
return c.exec(ctx, c.cfg)
|
|
}
|
|
|
|
func NewSharedCmdOptions() []ff.Option {
|
|
return []ff.Option{
|
|
ff.WithEnvVarPrefix("GOSHORT"),
|
|
}
|
|
}
|
|
|
|
func RegisterBaseFlags(fs *flag.FlagSet, cfg *config.Config) {
|
|
fs.BoolVar(&cfg.Debug, "debug", config.DefaultDebug, "enable debug mode")
|
|
var defaultHost = config.DefaultHost
|
|
if os.Getenv("ENV_DOCKER") == "true" {
|
|
defaultHost = "0.0.0.0"
|
|
}
|
|
fs.StringVar(&cfg.Host, "host", defaultHost, "host to listen on")
|
|
fs.StringVar(&cfg.Port, "port", config.DefaultPort, "port to listen on")
|
|
}
|
|
|
|
func RegisterServerFlags(fs *flag.FlagSet, cfg *config.Config) {
|
|
fs.BoolVar(&cfg.DisableRegistration, "disable-registration", config.DefaultDisableRegistration, "wether or not registration is disabled")
|
|
dbTypeString := fmt.Sprintf("type of database to use [%s]", strings.Join(config.DBTypes[:], ", "))
|
|
fs.StringVar(&cfg.DBType, "db-type", config.DefaultDBType, dbTypeString)
|
|
fs.StringVar(&cfg.DBURL, "db", config.DefaultDBURL, "database connection string or sqlite db path")
|
|
fs.DurationVar(&cfg.SessionDuration, "session-duration", config.DefaultSessionDuration, "session duration")
|
|
}
|
|
|
|
// InitStorage initializes the storage depending on the config
|
|
func InitStorage(cfg *config.Config) storage.Storage {
|
|
switch cfg.DBType {
|
|
case config.DBTypeMemory:
|
|
return memorystorage.NewMemoryStorage()
|
|
case config.DBTypeSQLite:
|
|
return sqlitestorage.NewSQLiteStorage(cfg)
|
|
default:
|
|
panic("database type not implemented!")
|
|
}
|
|
}
|