From 55f6086bd449b2b5ba1c759d92b20d473873eef2 Mon Sep 17 00:00:00 2001 From: Ryan McGuire Date: Tue, 19 Nov 2024 08:42:18 -0500 Subject: [PATCH] work on eia client --- cmd/eia-client/cmd/list/list_series.go | 9 +- cmd/eia-client/cmd/root.go | 8 +- cmd/eia-client/internal/util/util_logging.go | 89 +++++++++++--------- pkg/eia/eia.go | 23 +++-- 4 files changed, 74 insertions(+), 55 deletions(-) diff --git a/cmd/eia-client/cmd/list/list_series.go b/cmd/eia-client/cmd/list/list_series.go index 4738cee..b6fd1a8 100644 --- a/cmd/eia-client/cmd/list/list_series.go +++ b/cmd/eia-client/cmd/list/list_series.go @@ -3,6 +3,7 @@ package list import ( "github.com/spf13/cobra" + eiaapi "gitea.libretechconsulting.com/50W/eia-api-go/api" "gitea.libretechconsulting.com/50W/eia-api-go/cmd/eia-client/internal/util" ) @@ -16,6 +17,7 @@ var ListCmd = &cobra.Command{ func runListCmd(cmd *cobra.Command, _ []string) { logger := util.Logger(cmd) + client, err := util.Client(cmd) if err != nil { logger.Fatal().Err(err).Send() @@ -23,10 +25,11 @@ func runListCmd(cmd *cobra.Command, _ []string) { ctx, cncl := util.RequestCtx(cmd) defer cncl() - resp, err := client.GetV2(ctx) + resp, err := client.GetV2AeoRoute1DataWithResponse(ctx, "2023", &eiaapi.GetV2AeoRoute1DataParams{}) if err != nil { - logger.Err(err).Send() + logger.Error().Bytes("body", resp.Body) + logger.Fatal().Err(err).Send() } - logger.Debug().Any("resp", resp).Send() + logger.Info().Str("resp", string(resp.Body)).Send() } diff --git a/cmd/eia-client/cmd/root.go b/cmd/eia-client/cmd/root.go index e9b06c7..dd05dc9 100644 --- a/cmd/eia-client/cmd/root.go +++ b/cmd/eia-client/cmd/root.go @@ -51,6 +51,10 @@ func PreRun(cmd *cobra.Command, _ []string) { Timestamp().Logger().Level(*util.GetLogLevel(cmd)) util.SetLogger(cmd, &logger) + + util.Logger(cmd).Debug(). + Str("logLevel", util.Logger(cmd).GetLevel().String()). + Msg("logging configured") } // Execute adds all child commands to the root command and sets flags appropriately. @@ -70,10 +74,10 @@ func init() { cobra.EnableTraverseRunHooks = true // Handle command flags - rootCmd.PersistentFlags().StringP(util.FLAG_LOG_LEVEL, "l", util.DefaultLogLevel.String(), + rootCmd.PersistentFlags().StringP(util.FLAG_LOG_LEVEL, "l", "", "Log Level, or set "+util.ENV_LOG_LEVEL+" in environment") - rootCmd.PersistentFlags().StringP(util.FLAG_API_LOG_LEVEL, "L", util.DefAPILogLevel.String(), + rootCmd.PersistentFlags().StringP(util.FLAG_API_LOG_LEVEL, "L", "", "Log Level for EIA API Middleware, or set "+util.ENV_API_LOG_LEVEL+" in environment") rootCmd.PersistentFlags().StringP(util.FLAG_APIKEY, diff --git a/cmd/eia-client/internal/util/util_logging.go b/cmd/eia-client/internal/util/util_logging.go index ac2400a..e95845d 100644 --- a/cmd/eia-client/internal/util/util_logging.go +++ b/cmd/eia-client/internal/util/util_logging.go @@ -1,6 +1,7 @@ package util import ( + "fmt" "os" "github.com/rs/zerolog" @@ -18,57 +19,61 @@ func SetLogger(cmd *cobra.Command, logger *zerolog.Logger) { } func GetLogLevel(cmd *cobra.Command) *zerolog.Level { - var level zerolog.Level - var err error - if envLevel := os.Getenv(ENV_LOG_LEVEL); envLevel != "" { - level, err = zerolog.ParseLevel(envLevel) - if err != nil { - Logger(cmd).Err(err). - Str("envLogLevel", envLevel). - Str("envVar", ENV_LOG_LEVEL). - Str("defaultLevel", DefaultLogLevel.String()). - Msg("Invalid log level in environment, using default") - level = DefaultLogLevel - } + setLevel, err := GetStrFlagOrEnv(cmd, FLAG_LOG_LEVEL, ENV_LOG_LEVEL) + if err != nil || setLevel == "" { + Logger(cmd).Warn().Err(err). + Str("defaultLogLevel", DefAPILogLevel.String()). + Msg("no log level set, using default") + return &DefaultLogLevel } - if flagLevel, err := cmd.Flags().GetString(FLAG_LOG_LEVEL); err == nil { - level, err = zerolog.ParseLevel(flagLevel) - if err != nil { - Logger(cmd).Err(err). - Str("flagLogLevel", flagLevel). - Str("defaultLevel", DefaultLogLevel.String()). - Msg("Invalid log level in command flag, using default") - level = DefaultLogLevel - } + level, err := zerolog.ParseLevel(setLevel) + if err != nil { + Logger(cmd).Err(err). + Str("logLevel", setLevel). + Str("defaultLevel", DefaultLogLevel.String()). + Msg("Invalid log level, using default") + level = DefaultLogLevel } + return &level } func GetAPILogLevel(cmd *cobra.Command) *zerolog.Level { - var level zerolog.Level - var err error - if envLevel := os.Getenv(ENV_API_LOG_LEVEL); envLevel != "" { - level, err = zerolog.ParseLevel(envLevel) - if err != nil { - Logger(cmd).Err(err). - Str("envLogLevel", envLevel). - Str("envVar", ENV_API_LOG_LEVEL). - Str("defaultLevel", DefAPILogLevel.String()). - Msg("Invalid API log level in environment, using default") - level = DefAPILogLevel - } + setLevel, err := GetStrFlagOrEnv(cmd, FLAG_API_LOG_LEVEL, ENV_API_LOG_LEVEL) + if err != nil || setLevel == "" { + Logger(cmd).Warn().Err(err). + Str("defaultLogLevel", DefAPILogLevel.String()). + Msg("no API log level set, using default") + return &DefAPILogLevel } - if flagLevel, err := cmd.Flags().GetString(FLAG_API_LOG_LEVEL); err == nil { - level, err = zerolog.ParseLevel(flagLevel) - if err != nil { - Logger(cmd).Err(err). - Str("flagLogLevel", flagLevel). - Str("defaultLevel", DefAPILogLevel.String()). - Msg("Invalid API log level in command flag, using default") - level = DefAPILogLevel - } + level, err := zerolog.ParseLevel(setLevel) + if err != nil { + Logger(cmd).Err(err). + Str("logLevel", setLevel). + Str("defaultLevel", DefAPILogLevel.String()). + Msg("Invalid API log level, using default") + level = DefAPILogLevel } + return &level } + +// If set and not empty, returns the flag value +// Otherwise, returns the env value, empty or not +func GetStrFlagOrEnv(cmd *cobra.Command, flagName string, envName string) (string, error) { + flag, err := cmd.Flags().GetString(flagName) + if err != nil { + return "", err + } else if flag != "" { + return flag, nil + } + + envVal, set := os.LookupEnv(envName) + if !set { + return envVal, fmt.Errorf("environment variable %s not set", envName) + } + + return envVal, nil +} diff --git a/pkg/eia/eia.go b/pkg/eia/eia.go index 161734e..59df383 100644 --- a/pkg/eia/eia.go +++ b/pkg/eia/eia.go @@ -29,7 +29,7 @@ type Client struct { ctx context.Context apiKey string healthCheckTimeout time.Duration - *eiaapi.Client + *eiaapi.ClientWithResponses } type ClientOpts struct { @@ -56,11 +56,18 @@ func NewClient(opts *ClientOpts) (*Client, error) { // Injects Authorization: Bearer header into // outbound API calls - basicAuth, err := securityprovider.NewSecurityProviderBearerToken(opts.APIKey) + // basicAuth, err := securityprovider.NewSecurityProviderBearerToken(opts.APIKey) + // if err != nil { + // return nil, err + // } + // middlewares = append(middlewares, eiaapi.WithRequestEditorFn(basicAuth.Intercept)) + + // Injects API key as query parameter: ?api_key= + paramAuth, err := securityprovider.NewSecurityProviderApiKey("query", "api_key", opts.APIKey) if err != nil { return nil, err } - middlewares = append(middlewares, eiaapi.WithRequestEditorFn(basicAuth.Intercept)) + middlewares = append(middlewares, eiaapi.WithRequestEditorFn(paramAuth.Intercept)) // Logging middleware, if logger is given if opts.Logger != nil { @@ -73,15 +80,15 @@ func NewClient(opts *ClientOpts) (*Client, error) { eiaapi.WithRequestEditorFn(newLoggingMiddleware(opts.Logger, logLevel))) } - client, err := eiaapi.NewClient(baseURL, slices.Clip(middlewares)...) + client, err := eiaapi.NewClientWithResponses(baseURL, slices.Clip(middlewares)...) if err != nil { return nil, err } return &Client{ - apiKey: opts.APIKey, - ctx: opts.Context, - healthCheckTimeout: hcTimeout, - Client: client, + apiKey: opts.APIKey, + ctx: opts.Context, + healthCheckTimeout: hcTimeout, + ClientWithResponses: client, }, nil }