package util import ( "context" "errors" "os" "time" "github.com/rs/zerolog" "github.com/spf13/cobra" "gitea.libretechconsulting.com/rmcguire/eia-api-go/pkg/eia" ) var ( DefRequestTimeout = 15 * time.Second DefAPILogLevel = zerolog.DebugLevel ) func RequestCtx(cmd *cobra.Command) (context.Context, context.CancelFunc) { return context.WithTimeout(cmd.Context(), GetRequestTmout(cmd)) } func GetRequestTmout(cmd *cobra.Command) time.Duration { tmout, ok := cmd.Context().Value(CTX_EIA_TMOUT).(time.Duration) if !ok || tmout == 0 { return DefRequestTimeout } return tmout } func SetRequestTmout(cmd *cobra.Command, tmout time.Duration) { cmd.SetContext(context.WithValue(cmd.Context(), CTX_EIA_TMOUT, tmout)) } func Client(cmd *cobra.Command) (*eia.Client, error) { client, ok := cmd.Context().Value(CTX_EIA_CLIENT).(*eia.Client) if !ok { return nil, errors.New("command context lacks api client") } return client, nil } func SetClient(cmd *cobra.Command, _ []string) { client, err := eia.NewClient(&eia.ClientOpts{ Context: cmd.Context(), APIKey: GetAPIKey(cmd), Logger: Logger(cmd), LogLevel: GetAPILogLevel(cmd), }) if err != nil { Logger(cmd).Fatal().Err(err).Send() } cmd.SetContext(context.WithValue(cmd.Context(), CTX_EIA_CLIENT, client)) } func GetAPIKey(cmd *cobra.Command) string { if key := os.Getenv(ENV_API); key != "" { return key } key, _ := cmd.Flags().GetString(FLAG_APIKEY) return key }