99 lines
2.5 KiB
Go
99 lines
2.5 KiB
Go
package emapi
|
|
|
|
import (
|
|
"fmt"
|
|
"net/url"
|
|
|
|
"github.com/spf13/pflag"
|
|
"github.com/spf13/viper"
|
|
"go.infratographer.com/x/viperx"
|
|
)
|
|
|
|
// Config provides configuration for connecting to the Equinix Metal API provider.
|
|
type Config struct {
|
|
// BaseURL is the baseurl to use when connecting to the Equinix Metal API Provider.
|
|
BaseURL string
|
|
|
|
// AuthToken is the token to interact with the Equinix Metal API
|
|
AuthToken string
|
|
|
|
// ConsumerToken is the token to grant higher privileges in the Equinix Metal API
|
|
ConsumerToken string
|
|
}
|
|
|
|
// MustViperFlags registers command flags along with the viper bindings.
|
|
func MustViperFlags(v *viper.Viper, flags *pflag.FlagSet) {
|
|
flags.String("emapi-base-url", "", "Equinix Metal Rest API Base URL")
|
|
viperx.MustBindFlag(v, "equinixmetal.emapi.baseurl", flags.Lookup("emapi-base-url"))
|
|
|
|
flags.String("emapi-auth-token", "", "Equinix Metal Rest Auth Token")
|
|
viperx.MustBindFlag(v, "equinixmetal.emapi.authtoken", flags.Lookup("emapi-auth-token"))
|
|
|
|
flags.String("emapi-consumer-token", "", "Equinix Metal Rest Consumer Token")
|
|
viperx.MustBindFlag(v, "equinixmetal.emapi.consumertoken", flags.Lookup("emapi-consumer-token"))
|
|
}
|
|
|
|
// Populated checks if any field has been populated.
|
|
func (c Config) Populated() bool {
|
|
return c.AuthToken != "" || c.ConsumerToken != "" || c.BaseURL != ""
|
|
}
|
|
|
|
// WithConfig applies all configurations defined in the config.
|
|
func WithConfig(config Config) Option {
|
|
return func(c *Client) error {
|
|
var options []Option
|
|
|
|
if config.BaseURL != "" {
|
|
options = append(options, WithBaseURL(config.BaseURL))
|
|
}
|
|
|
|
if config.AuthToken != "" {
|
|
options = append(options, WithAuthToken(config.AuthToken))
|
|
}
|
|
|
|
if config.ConsumerToken != "" {
|
|
options = append(options, WithConsumerToken(config.ConsumerToken))
|
|
}
|
|
|
|
for _, opt := range options {
|
|
if err := opt(c); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithBaseURL updates the baseurl used by the client.
|
|
func WithBaseURL(baseURL string) Option {
|
|
return func(c *Client) error {
|
|
u, err := url.Parse(baseURL)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to parse emapi base url %s: %w", baseURL, err)
|
|
}
|
|
|
|
c.baseURL = u
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithAuthToken sets the auth token to authenticate the request with.
|
|
func WithAuthToken(token string) Option {
|
|
return func(c *Client) error {
|
|
c.authToken = token
|
|
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// WithConsumerToken sets the consumer token to elevate privileges for the request.
|
|
func WithConsumerToken(token string) Option {
|
|
return func(c *Client) error {
|
|
c.consumerToken = token
|
|
|
|
return nil
|
|
}
|
|
}
|