bouncer/internal/command/main.go

112 lines
2.4 KiB
Go
Raw Permalink Normal View History

2023-04-24 20:52:12 +02:00
package command
import (
"context"
"fmt"
"os"
"sort"
"time"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"gitlab.com/wpetit/goweb/logger"
2023-04-24 20:52:12 +02:00
)
func Main(buildDate, projectVersion, gitRef, defaultConfigPath string, commands ...*cli.Command) {
ctx := context.Background()
compiled, err := time.Parse(time.RFC3339, buildDate)
if err != nil {
panic(errors.Wrapf(err, "could not parse build date '%s'", buildDate))
}
app := &cli.App{
Version: fmt.Sprintf("%s (%s, %s)", projectVersion, gitRef, buildDate),
Compiled: compiled,
Name: "bouncer",
Usage: "reverse proxy server with dynamic queuing management",
Commands: commands,
Before: func(ctx *cli.Context) error {
workdir := ctx.String("workdir")
// Switch to new working directory if defined
if workdir != "" {
logger.Info(ctx.Context, "changing working directory", logger.F("workdir", workdir))
2023-04-24 20:52:12 +02:00
if err := os.Chdir(workdir); err != nil {
return errors.Wrap(err, "could not change working directory")
}
}
if err := ctx.Set("projectVersion", projectVersion); err != nil {
return errors.WithStack(err)
}
if err := ctx.Set("gitRef", gitRef); err != nil {
return errors.WithStack(err)
}
if err := ctx.Set("buildDate", buildDate); err != nil {
return errors.WithStack(err)
}
return nil
},
Flags: []cli.Flag{
&cli.StringFlag{
2023-06-30 04:13:56 +02:00
Name: "workdir",
Value: "",
EnvVars: []string{"BOUNCER_WORKDIR"},
Usage: "The working directory",
2023-04-24 20:52:12 +02:00
},
&cli.StringFlag{
Name: "projectVersion",
Value: "",
Hidden: true,
},
&cli.StringFlag{
Name: "gitRef",
Value: "",
Hidden: true,
},
&cli.StringFlag{
Name: "buildDate",
Value: "",
Hidden: true,
},
&cli.BoolFlag{
Name: "debug",
EnvVars: []string{"BOUNCER_DEBUG"},
Value: false,
},
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
EnvVars: []string{"BOUNCER_CONFIG"},
Value: defaultConfigPath,
TakesFile: true,
},
},
}
app.ExitErrHandler = func(ctx *cli.Context, err error) {
if err == nil {
return
}
debug := ctx.Bool("debug")
if !debug {
fmt.Printf("[ERROR] %v\n", err)
} else {
fmt.Printf("%+v", err)
}
}
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))
if err := app.RunContext(ctx, os.Args); err != nil {
os.Exit(1)
}
}