work on eia client

This commit is contained in:
Ryan McGuire 2024-11-19 08:42:18 -05:00
parent 9af155dbde
commit 55f6086bd4
4 changed files with 74 additions and 55 deletions

View File

@ -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()
}

View File

@ -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,

View File

@ -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
}

View File

@ -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 <APIKey> 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=<apiKey>
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
}