package process import ( "context" "os" "os/signal" "time" "github.com/k0kubun/pp" "github.com/mattn/go-isatty" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/spf13/viper" ) // CLIEntry is the main entrypoint func CLIEntry(version, buildarch string) int { hp := new(HistoryPoster) hp.version = version hp.buildarch = buildarch hp.startup = time.Now() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) hp.configure() hp.setupLogging() ctx, cancel := context.WithCancel(context.Background()) go func() { // this sits and waits for an interrupt to be received sig := <-c log.Info().Msgf("signal received: %+v", sig) cancel() }() return hp.runForever(ctx) } type HistoryPoster struct { version string buildarch string startup time.Time } func (hp *HistoryPoster) configure() { viper.SetConfigName("historyposter") viper.SetConfigType("yaml") viper.AddConfigPath("/etc/historyposter") // path to look for the config file in viper.AddConfigPath("$HOME/.config/historyposter") // call multiple times to add many search paths viper.SetEnvPrefix("HISTORYPOSTER") viper.AutomaticEnv() viper.SetDefault("Debug", false) if err := viper.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { // Config file not found; ignore error if desired } else { // Config file was found but another error was produced log.Panic(). Err(err). Msg("cannot read config file") } } if viper.GetBool("debug") { pp.Print(viper.AllSettings()) } } func (hp *HistoryPoster) runForever(ctx context.Context) int { <-ctx.Done() log.Info().Msgf("shutting down") return 0 } func (hp *HistoryPoster) setupLogging() { log.Logger = log.With().Caller().Logger() tty := isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd()) if tty { out := zerolog.NewConsoleWriter( func(w *zerolog.ConsoleWriter) { // Customize time format w.TimeFormat = time.RFC3339 }, ) log.Logger = log.Output(out) } // always log in UTC zerolog.TimestampFunc = func() time.Time { return time.Now().UTC() } zerolog.SetGlobalLevel(zerolog.InfoLevel) if viper.GetBool("debug") { zerolog.SetGlobalLevel(zerolog.DebugLevel) } hp.identify() } func (hp *HistoryPoster) identify() { log.Info(). Str("version", hp.version). Str("buildarch", hp.buildarch). Msg("starting") }