core

package
v5.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2021 License: Apache-2.0 Imports: 32 Imported by: 393

Documentation

Overview

Package core contains functionality used by Go SDK's generated by the IBM OpenAPI 3 SDK Generator (openapi-sdkgen). Authenticators

The go-sdk-core project supports the following types of authentication:

Basic Authentication
Bearer Token
Identity and Access Management (IAM)
Cloud Pak for Data
No Authentication

The authentication types that are appropriate for a particular service may vary from service to service. Each authentication type is implemented as an Authenticator for consumption by a service. To read more about authenticators and how to use them see here: https://github.com/IBM/go-sdk-core/blob/main/Authentication.md

Services

Services are the API clients generated by the IBM OpenAPI 3 SDK Generator. These services make use of the code within the core package BaseService instances to perform service operations.

Index

Constants

View Source
const (
	// IBM_CREDENTIAL_FILE_ENVVAR is the environment key used to find the path to
	// a credentials file.
	IBM_CREDENTIAL_FILE_ENVVAR = "IBM_CREDENTIALS_FILE"

	// DEFAULT_CREDENTIAL_FILE_NAME is the default filename for a credentials file.
	// It is used when "IBM_CREDENTIALS_FILE" is not specified. The filename will
	// be searched for within the program's working directory, and then the OS's
	// current user directory.
	DEFAULT_CREDENTIAL_FILE_NAME = "ibm-credentials.env"
)
View Source
const (
	// Supported authentication types.
	AUTHTYPE_BASIC        = "basic"
	AUTHTYPE_BEARER_TOKEN = "bearerToken"
	AUTHTYPE_NOAUTH       = "noAuth"
	AUTHTYPE_IAM          = "iam"
	AUTHTYPE_CP4D         = "cp4d"

	// Service client properties.
	PROPNAME_SVC_URL            = "URL"
	PROPNAME_SVC_DISABLE_SSL    = "DISABLE_SSL"
	PROPNAME_SVC_ENABLE_GZIP    = "ENABLE_GZIP"
	PROPNAME_SVC_ENABLE_RETRIES = "ENABLE_RETRIES"
	PROPNAME_SVC_MAX_RETRIES    = "MAX_RETRIES"
	PROPNAME_SVC_RETRY_INTERVAL = "RETRY_INTERVAL"

	// Authenticator properties.
	PROPNAME_AUTH_TYPE        = "AUTH_TYPE"
	PROPNAME_USERNAME         = "USERNAME"
	PROPNAME_PASSWORD         = "PASSWORD"
	PROPNAME_BEARER_TOKEN     = "BEARER_TOKEN"
	PROPNAME_AUTH_URL         = "AUTH_URL"
	PROPNAME_AUTH_DISABLE_SSL = "AUTH_DISABLE_SSL"
	PROPNAME_APIKEY           = "APIKEY"
	PROPNAME_CLIENT_ID        = "CLIENT_ID"
	PROPNAME_CLIENT_SECRET    = "CLIENT_SECRET"
	PROPNAME_SCOPE            = "SCOPE"

	// SSL error
	SSL_CERTIFICATION_ERROR = "x509: certificate"

	// Common error messages.
	ERRORMSG_PROP_MISSING            = "The %s property is required but was not specified."
	ERRORMSG_PROP_INVALID            = "The %s property is invalid. Please remove any surrounding {, }, or \" characters."
	ERRORMSG_EXCLUSIVE_PROPS_ERROR   = "Exactly one of %s or %s must be specified."
	ERRORMSG_NO_AUTHENTICATOR        = "Authentication information was not properly configured."
	ERRORMSG_AUTHTYPE_UNKNOWN        = "Unrecognized authentication type: %s"
	ERRORMSG_PROPS_MAP_NIL           = "The 'properties' map cannot be nil."
	ERRORMSG_SSL_VERIFICATION_FAILED = "The connection failed because the SSL certificate is not valid. To use a " +
		"self-signed certificate, disable verification of the server's SSL certificate " +
		"by invoking the DisableSSLVerification() function on your service instance " +
		"and/or use the DisableSSLVerification option of the authenticator."
	ERRORMSG_AUTHENTICATE_ERROR      = "An error occurred while performing the 'authenticate' step: %s"
	ERRORMSG_READ_RESPONSE_BODY      = "An error occurred while reading the response body: %s"
	ERRORMSG_UNEXPECTED_RESPONSE     = "The response contained unexpected content"
	ERRORMSG_UNMARSHAL_RESPONSE_BODY = "An error occurred while unmarshalling the response body: %s"
	ERRORMSG_NIL_SLICE               = "The 'slice' parameter cannot be nil"
	ERRORMSG_PARAM_NOT_SLICE         = "The 'slice' parameter must be a slice"
	ERRORMSG_MARSHAL_SLICE           = "An error occurred while marshalling the slice: %s"
	ERRORMSG_CONVERT_SLICE           = "An error occurred while converting 'slice' to string slice"
	ERRORMSG_CREATE_RETRYABLE_REQ    = "An error occurred while creating a retryable http Request: %s"
	ERRORMSG_UNEXPECTED_STATUS_CODE  = "Unexpected HTTP status code %d (%s)"
	ERRORMSG_UNMARSHAL_AUTH_RESPONSE = "error unmarshalling authentication response: %s"
)
View Source
const (
	DEFAULT_IAM_URL      = "https://iam.cloud.ibm.com"
	OPERATION_PATH       = "/identity/token"
	DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded"
	/* #nosec G101 */
	REQUEST_TOKEN_GRANT_TYPE    = "urn:ibm:params:oauth:grant-type:apikey"
	REQUEST_TOKEN_RESPONSE_TYPE = "cloud_iam"
)

IamAuthenticator-related constants.

View Source
const (
	POST   = http.MethodPost
	GET    = http.MethodGet
	DELETE = http.MethodDelete
	PUT    = http.MethodPut
	PATCH  = http.MethodPatch
	HEAD   = http.MethodHead
)

common HTTP methods

View Source
const (
	Accept                  = "Accept"
	APPLICATION_JSON        = "application/json"
	CONTENT_DISPOSITION     = "Content-Disposition"
	CONTENT_ENCODING        = "Content-Encoding"
	CONTENT_TYPE            = "Content-Type"
	FORM_URL_ENCODED_HEADER = "application/x-www-form-urlencoded"

	ERRORMSG_SERVICE_URL_MISSING = "service URL is empty"
	ERRORMSG_SERVICE_URL_INVALID = "error parsing service URL: %s"
	ERRORMSG_PATH_PARAM_EMPTY    = "path parameter '%s' is empty"
)

common headers

Variables

Validate is a shared validator instance used to perform validation of structs.

Functions

func BoolPtr

func BoolPtr(literal bool) *bool

BoolPtr returns a pointer to boolean literal.

func ConvertSlice

func ConvertSlice(slice interface{}) (s []string, err error)

ConvertSlice Marshals 'slice' to a json string, performs string manipulation on the resulting string, and converts the string to a '[]string'. If 'slice' is nil, not a 'slice' type, or an error occurred during conversion, an error will be returned

func DefaultHTTPClient

func DefaultHTTPClient() *http.Client

DefaultHTTPClient returns a non-retryable http client with default configuration.

func Float32Ptr

func Float32Ptr(literal float32) *float32

Float32Ptr returns a pointer to float32 literal.

func Float64Ptr

func Float64Ptr(literal float64) *float64

Float64Ptr returns a pointer to float64 literal.

func GetCurrentTime

func GetCurrentTime() int64

GetCurrentTime returns the current Unix time.

func GetQueryParam added in v5.2.0

func GetQueryParam(urlStr *string, param string) (*string, error)

return a pointer to the value of query parameter `param` from url, or nil when not found

func GetServiceProperties

func GetServiceProperties(serviceName string) (serviceProps map[string]string, err error)

GetServiceProperties returns a map containing configuration properties for the specified service that are retrieved from external configuration sources in the following precedence order: 1) credential file 2) environment variables 3) VCAP_SERVICES

'serviceName' is used as a filter against the property names. For example, if serviceName is passed in as "my_service", then configuration properties whose names begin with "MY_SERVICE_" will be returned in the map.

func HasBadFirstOrLastChar

func HasBadFirstOrLastChar(str string) bool

HasBadFirstOrLastChar checks if the string starts with `{` or `"` or ends with `}` or `"`.

func IBMCloudSDKBackoffPolicy

func IBMCloudSDKBackoffPolicy(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration

IBMCloudSDKBackoffPolicy provides a default implementation of the Backoff interface associated with a retryablehttp.Client. This function will return the wait time to be associated with the next retry attempt.

func IBMCloudSDKRetryPolicy

func IBMCloudSDKRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error)

IBMCloudSDKRetryPolicy provides a default implementation of the CheckRetry interface associated with a retryablehttp.Client. This function will return true if the specified request/response should be retried.

func Int64Ptr

func Int64Ptr(literal int64) *int64

Int64Ptr returns a pointer to int64 literal.

func IsJSONMimeType

func IsJSONMimeType(mimeType string) bool

IsJSONMimeType Returns true iff the specified mimeType value represents a "JSON" mimetype.

func IsJSONPatchMimeType

func IsJSONPatchMimeType(mimeType string) bool

IsJSONPatchMimeType returns true iff the specified mimeType value represents a "JSON Patch" mimetype.

func IsNil

func IsNil(object interface{}) bool

IsNil checks if the specified object is nil or not.

func NewGzipCompressionReader

func NewGzipCompressionReader(uncompressedReader io.Reader) (io.Reader, error)

NewGzipCompressionReader will return an io.Reader instance that will deliver the gzip-compressed version of the "uncompressedReader" argument. This function was inspired by this github gist:

https://gist.github.com/tomcatzh/cf8040820962e0f8c04700eb3b2f26be

func NewGzipDecompressionReader

func NewGzipDecompressionReader(compressedReader io.Reader) (io.Reader, error)

NewGzipDecompressionReader will return an io.Reader instance that will deliver the gzip-decompressed version of the "compressedReader" argument.

func NewRetryableHTTPClient

func NewRetryableHTTPClient() *retryablehttp.Client

NewRetryableHTTPClient returns a new instance of go-retryablehttp.Client with a default configuration that supports Go SDK usage.

func NormalizeDateTimeUTC

func NormalizeDateTimeUTC(t time.Time) time.Time

NormalizeDateTimeUTC normalizes t to reflect UTC timezone for marshaling

func ParseDate added in v5.1.0

func ParseDate(dateString string) (fmtDate strfmt.Date, err error)

ParseDate parses the specified RFC3339 full-date string (YYYY-MM-DD) and returns a strfmt.Date instance.

func ParseDateTime added in v5.1.0

func ParseDateTime(dateString string) (strfmt.DateTime, error)

ParseDateTime parses the specified date-time string and returns a strfmt.DateTime instance.

func PrettyPrint

func PrettyPrint(result interface{}, resultName string)

PrettyPrint print pretty.

func SetLogger

func SetLogger(logger Logger)

SetLogger sets the specified Logger instance as the logger to be used by the Go core library.

func SetLoggingLevel

func SetLoggingLevel(level LogLevel)

SetLoggingLevel will enable the specified logging level in the Go core library.

func SliceContains

func SliceContains(slice []string, contains string) bool

SliceContains returns true iff "contains" is an element of "slice"

func StringNilMapper

func StringNilMapper(s *string) string

StringNilMapper de-references the parameter 's' and returns the result, or "" if 's' is nil.

func StringPtr

func StringPtr(literal string) *string

StringPtr returns a pointer to string literal.

func SystemInfo

func SystemInfo() string

SystemInfo returns the system information.

func UUIDPtr added in v5.1.0

func UUIDPtr(literal strfmt.UUID) *strfmt.UUID

UUIDPtr returns a pointer to strfmt.UUID literal.

func UnmarshalModel

func UnmarshalModel(rawInput interface{}, propertyName string, result interface{}, unmarshaller ModelUnmarshaller) (err error)

UnmarshalModel unmarshals 'rawInput' into 'result' while using 'unmarshaller' to unmarshal model instances. This function is the single public interface to the various flavors of model-related unmarshal functions. The values passed in for the 'rawInput', 'propertyName' and 'result' fields will determine the function performed.

Parameters: rawInput: the unmarshal input source. The various types associated with this parameter are described below in "Usage Notes".

propertyName: an optional property name. If specified as "", then 'rawInput' is assumed to directly contain the input source to be used for the unmarshal operation. If propertyName is specified as a non-empty string, then 'rawInput' is assumed to be a map[string]json.RawMessage, and rawInput[propertyName] contains the input source to be unmarshalled.

result: the unmarshal destination. This should be passed in as one of the following types of values:

  • **<model> (a ptr to a ptr to a <model> instance)
  • *[]<model> (a ptr to a <model> slice)
  • *map[string]<model> (a ptr to a map of <model> instances)
  • *map[string][]<model> (a ptr to a map of <model> slices)

unmarshaller: the unmarshaller function to be used to unmarshal each model instance

Usage Notes: if 'result' is a: | and propertyName is: | then 'rawInput' should be: -------------------+--------------------------+------------------------------------------------------------------ **Foo | == "" | a map[string]json.RawMessage which directly

|                          | contains an instance of model Foo (i.e. each map entry represents
|                          | a property of Foo)
|                          |

**Foo | != "" (e.g. "prop") | a map[string]json.RawMessage and rawInput["prop"]

|                          | should contain an instance of Foo (i.e. it can itself be
|                          | unmarshalled into a map[string]json.RawMessage whose entries
|                          | represent the properties of Foo)

-------------------+--------------------------+------------------------------------------------------------------ *[]Foo | == "" | a []json.RawMessage where each slice element contains

|                          | an instance of Foo (i.e. the json.RawMessage can be unmarshalled
|                          | into a Foo instance)
|                          |

*[]Foo | != "" (e.g. "prop") | a map[string]json.RawMessage and rawInput["prop"]

|                          | contains a []Foo (slice of Foo instances)

-------------------+--------------------------+------------------------------------------------------------------ *map[string]Foo | == "" | a map[string]json.RawMessage which directly contains the

|                          | map[string]Foo (i.e. the value within each entry in 'rawInput'
|                          | contains an instance of Foo)
|                          |

*map[string]Foo | != "" (e.g. "prop") | a map[string]json.RawMessage and rawInput["prop"]

|                          | contains an instance of map[string]Foo

-------------------+--------------------------+------------------------------------------------------------------ *map[string][]Foo | == "" | a map[string]json.RawMessage which directly contains the

|                          | map[string][]Foo (i.e. the value within each entry in 'rawInput'
|                          | contains a []Foo)

*map[string][]Foo | != "" (e.g. "prop") | a map[string]json.RawMessage and rawInput["prop"]

|                          | contains an instance of map[string][]Foo

-------------------+--------------------------+------------------------------------------------------------------

func UnmarshalPrimitive

func UnmarshalPrimitive(rawInput map[string]json.RawMessage, propertyName string, result interface{}) (err error)

UnmarshalPrimitive retrieves the specified property from 'rawInput', then unmarshals the resulting value into 'result'.

This function will typically be invoked from within a model's generated "Unmarshal<model>()" method to unmarshal a struct field (model property) involving a primitive type (a scalar value, a slice, a map of the primitive, etc.). In this context, "primitive" refers to a type other than a user-defined model type within an OpenAPI definition. The 'rawInput' parameter is expected to be a map that contains an instance of a user-defined model type.

Parameters:

rawInput: the unmarshal input source in the form of a map[string]json.RawMessage The value 'rawInput[propertyName]' must be a json.RawMessage that contains an instance of the type inferred from the value passed in as 'result'.

propertyName: the name of the property (map entry) to retrieve from 'rawInput'. This entry's value will be used as the unmarshal input source.

result: a pointer to the unmarshal destination. This could be any of the following:

  • *<primitive-type>
  • **<primitive-type>
  • *[]<primitive-type>
  • *map[string]<primitive-type>
  • *map[string][]<primitive-type>
  • *[]map[string]<primitive-type>
  • *[]map[string][]<primitive-type>

Where <primitive-type> could be any of the following:

  • string, bool, []byte, int64, float32, float64, strfmt.Date, strfmt.DateTime, strfmt.UUID, interface{}, or map[string]interface{}.

Example:

type MyStruct struct {
    Field1 *string,
    Field2 map[string]int64
}

myStruct := new(MyStruct) jsonString := `{ "field1": "value1", "field2": {"foo": 44, "bar": 74}}` var rawMessageMap map[string]json.RawMessage var err error err = UnmarshalPrimitive(rawMessageMap, "field1", &myStruct.Field1) err = UnmarshalPrimitive(rawMessageMap, "field2", &myString.Field2)

func UserHomeDir

func UserHomeDir() string

UserHomeDir returns the user home directory.

func ValidateNotNil

func ValidateNotNil(object interface{}, errorMsg string) error

ValidateNotNil returns the specified error if 'object' is nil, nil otherwise.

func ValidateStruct

func ValidateStruct(param interface{}, paramName string) error

ValidateStruct validates 'param' (assumed to be a ptr to a struct) according to the annotations attached to its fields.

Types

type AuthenticationError

type AuthenticationError struct {
	Response *DetailedResponse
	Err      error
}

AuthenticationError describes the error returned when authentication fails

func NewAuthenticationError

func NewAuthenticationError(response *DetailedResponse, err error) *AuthenticationError

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type Authenticator

type Authenticator interface {
	AuthenticationType() string
	Authenticate(*http.Request) error
	Validate() error
}

Authenticator describes the set of methods implemented by each authenticator.

func GetAuthenticatorFromEnvironment

func GetAuthenticatorFromEnvironment(credentialKey string) (authenticator Authenticator, err error)

GetAuthenticatorFromEnvironment instantiates an Authenticator using service properties retrieved from external config sources.

type BaseService

type BaseService struct {

	// Configuration values for a service.
	Options *ServiceOptions

	// A set of "default" http headers to be included with each outbound request.
	DefaultHeaders http.Header

	// The HTTP Client used to send requests and receive responses.
	Client *http.Client

	// The value to be used for the "User-Agent" HTTP header that is added to each
	// outbound request. If this value is not set, then a default value will be
	// used for the header.
	UserAgent string
}

BaseService implements the common functionality shared by generated services to manage requests and responses, authenticate outbound requests, etc.

func NewBaseService

func NewBaseService(options *ServiceOptions) (*BaseService, error)

NewBaseService constructs a new instance of BaseService. Validation on input parameters and service options will be performed before instance creation.

func (*BaseService) Clone

func (service *BaseService) Clone() *BaseService

Clone will return a copy of "service" suitable for use by a generated service instance to process requests.

func (*BaseService) ConfigureService

func (service *BaseService) ConfigureService(serviceName string) error

ConfigureService updates the service with external configuration values.

func (*BaseService) DisableRetries

func (service *BaseService) DisableRetries()

DisableRetries will disable automatic retries by constructing a new default (non-retryable) HTTP Client instance and setting it on the service.

func (*BaseService) DisableSSLVerification

func (service *BaseService) DisableSSLVerification()

DisableSSLVerification skips SSL verification. This function sets a new http.Client instance on the service and configures it to bypass verification of server certificates and host names, making the client susceptible to "man-in-the-middle" attacks. This should be used only for testing.

func (*BaseService) EnableRetries

func (service *BaseService) EnableRetries(maxRetries int, maxRetryInterval time.Duration)

EnableRetries will construct a "retryable" HTTP Client with the specified configuration, and then set it on the service instance. If maxRetries and/or maxRetryInterval are specified as 0, then default values are used instead.

func (*BaseService) GetEnableGzipCompression

func (service *BaseService) GetEnableGzipCompression() bool

GetEnableGzipCompression returns the service's EnableGzipCompression field

func (*BaseService) GetServiceURL

func (service *BaseService) GetServiceURL() string

GetServiceURL returns the service URL.

func (*BaseService) IsSSLDisabled

func (service *BaseService) IsSSLDisabled() bool

IsSSLDisabled returns true if and only if the service's http.Client instance is configured to skip verification of server SSL certificates.

func (*BaseService) Request

func (service *BaseService) Request(req *http.Request, result interface{}) (detailedResponse *DetailedResponse, err error)

Request invokes the specified HTTP request and returns the response.

Parameters: req: the http.Request object that holds the request information

result: a pointer to the operation result. This should be one of:

  • *io.ReadCloser (for a byte-stream type response)
  • *<primitive>, *[]<primitive>, *map[string]<primitive>
  • *map[string]json.RawMessage, *[]json.RawMessage

Return values: detailedResponse: a DetailedResponse instance containing the status code, headers, etc.

err: a non-nil error object if an error occurred

func (*BaseService) SetDefaultHeaders

func (service *BaseService) SetDefaultHeaders(headers http.Header)

SetDefaultHeaders sets HTTP headers to be sent in every request.

func (*BaseService) SetEnableGzipCompression

func (service *BaseService) SetEnableGzipCompression(enableGzip bool)

SetEnableGzipCompression sets the service's EnableGzipCompression field

func (*BaseService) SetHTTPClient

func (service *BaseService) SetHTTPClient(client *http.Client)

SetHTTPClient updates the client handling the requests.

func (*BaseService) SetServiceURL

func (service *BaseService) SetServiceURL(url string) error

SetServiceURL sets the service URL.

func (*BaseService) SetURL deprecated

func (service *BaseService) SetURL(url string) error

SetURL sets the service URL.

Deprecated: use SetServiceURL instead.

func (*BaseService) SetUserAgent

func (service *BaseService) SetUserAgent(userAgentString string)

SetUserAgent sets the user agent value.

type BasicAuthenticator

type BasicAuthenticator struct {
	// Username is the user-supplied basic auth username [required].
	Username string
	// Password is the user-supplied basic auth password [required].
	Password string
}

BasicAuthenticator takes a user-supplied username and password, and adds them to requests via an Authorization header of the form:

Authorization: Basic <encoded username and password>

func NewBasicAuthenticator

func NewBasicAuthenticator(username string, password string) (*BasicAuthenticator, error)

NewBasicAuthenticator constructs a new BasicAuthenticator instance.

func (*BasicAuthenticator) Authenticate

func (this *BasicAuthenticator) Authenticate(request *http.Request) error

Authenticate adds basic authentication information to a request.

Basic Authorization will be added to the request's headers in the form:

Authorization: Basic <encoded username and password>

func (BasicAuthenticator) AuthenticationType

func (BasicAuthenticator) AuthenticationType() string

AuthenticationType returns the authentication type for this authenticator.

func (BasicAuthenticator) Validate

func (this BasicAuthenticator) Validate() error

Validate the authenticator's configuration.

Ensures the username and password are not Nil. Additionally, ensures they do not contain invalid characters.

type BearerTokenAuthenticator

type BearerTokenAuthenticator struct {

	// The bearer token value to be used to authenticate request [required].
	BearerToken string
}

BearerTokenAuthenticator will take a user-supplied bearer token and adds it to requests via an Authorization header of the form:

Authorization: Bearer <bearer-token>

func NewBearerTokenAuthenticator

func NewBearerTokenAuthenticator(bearerToken string) (*BearerTokenAuthenticator, error)

NewBearerTokenAuthenticator constructs a new BearerTokenAuthenticator instance.

func (*BearerTokenAuthenticator) Authenticate

func (this *BearerTokenAuthenticator) Authenticate(request *http.Request) error

Authenticate adds bearer authentication information to the request.

The bearer token will be added to the request's headers in the form:

Authorization: Bearer <bearer-token>

func (BearerTokenAuthenticator) AuthenticationType

func (BearerTokenAuthenticator) AuthenticationType() string

AuthenticationType returns the authentication type for this authenticator.

func (BearerTokenAuthenticator) Validate

func (this BearerTokenAuthenticator) Validate() error

Validate the authenticator's configuration.

Ensures the bearer token is not Nil.

type CloudPakForDataAuthenticator

type CloudPakForDataAuthenticator struct {
	// The URL representing the Cloud Pak for Data token service endpoint [required].
	URL string

	// The username used to obtain a bearer token [required].
	Username string

	// The password used to obtain a bearer token [required if APIKey not specified].
	// One of Password or APIKey must be specified.
	Password string

	// The apikey used to obtain a bearer token [required if Password not specified].
	// One of Password or APIKey must be specified.
	APIKey string

	// A flag that indicates whether verification of the server's SSL certificate
	// should be disabled; defaults to false [optional].
	DisableSSLVerification bool

	// Default headers to be sent with every CP4D token request [optional].
	Headers map[string]string

	// The http.Client object used to invoke token server requests [optional]. If
	// not specified, a suitable default Client will be constructed.
	Client *http.Client
	// contains filtered or unexported fields
}

CloudPakForDataAuthenticator uses either a username/password pair or a username/apikey pair to obtain a suitable bearer token from the CP4D authentication service, and adds the bearer token to requests via an Authorization header of the form:

Authorization: Bearer <bearer-token>

func NewCloudPakForDataAuthenticator

func NewCloudPakForDataAuthenticator(url string, username string, password string,
	disableSSLVerification bool, headers map[string]string) (*CloudPakForDataAuthenticator, error)

NewCloudPakForDataAuthenticator constructs a new CloudPakForDataAuthenticator instance from a username/password pair. This is the default way to create an authenticator and is a wrapper around the NewCloudPakForDataAuthenticatorUsingPassword() function

func NewCloudPakForDataAuthenticatorUsingAPIKey

func NewCloudPakForDataAuthenticatorUsingAPIKey(url string, username string, apikey string,
	disableSSLVerification bool, headers map[string]string) (*CloudPakForDataAuthenticator, error)

NewCloudPakForDataAuthenticatorUsingAPIKey constructs a new CloudPakForDataAuthenticator instance from a username/apikey pair.

func NewCloudPakForDataAuthenticatorUsingPassword

func NewCloudPakForDataAuthenticatorUsingPassword(url string, username string, password string,
	disableSSLVerification bool, headers map[string]string) (*CloudPakForDataAuthenticator, error)

NewCloudPakForDataAuthenticatorUsingPassword constructs a new CloudPakForDataAuthenticator instance from a username/password pair.

func (*CloudPakForDataAuthenticator) Authenticate

func (authenticator *CloudPakForDataAuthenticator) Authenticate(request *http.Request) error

Authenticate adds the bearer token (obtained from the token server) to the specified request.

The CP4D bearer token will be added to the request's headers in the form:

Authorization: Bearer <bearer-token>

func (CloudPakForDataAuthenticator) AuthenticationType

func (CloudPakForDataAuthenticator) AuthenticationType() string

AuthenticationType returns the authentication type for this authenticator.

func (CloudPakForDataAuthenticator) Validate

func (authenticator CloudPakForDataAuthenticator) Validate() error

Validate the authenticator's configuration.

Ensures the username, password, and url are not Nil. Additionally, ensures they do not contain invalid characters.

type DetailedResponse

type DetailedResponse struct {

	// The HTTP status code associated with the response.
	StatusCode int

	// The HTTP headers contained in the response.
	Headers http.Header

	// Result - this field will contain the result of the operation (obtained from the response body).
	//
	// If the operation was successful and the response body contains a JSON response, it is un-marshalled
	// into an object of the appropriate type (defined by the particular operation), and the Result field will contain
	// this response object.  If there was an error while un-marshalling the JSON response body, then the RawResult field
	// will be set to the byte array containing the response body.
	//
	// Alternatively, if the generated SDK code passes in a result object which is an io.ReadCloser instance,
	// the JSON un-marshalling step is bypassed and the response body is simply returned in the Result field.
	// This scenario would occur in a situation where the SDK would like to provide a streaming model for large JSON
	// objects.
	//
	// If the operation was successful and the response body contains a non-JSON response,
	// the Result field will be an instance of io.ReadCloser that can be used by generated SDK code
	// (or the application) to read the response data.
	//
	// If the operation was unsuccessful and the response body contains a JSON error response,
	// this field will contain an instance of map[string]interface{} which is the result of un-marshalling the
	// response body as a "generic" JSON object.
	// If the JSON response for an unsuccessful operation could not be properly un-marshalled, then the
	// RawResult field will contain the raw response body.
	Result interface{}

	// This field will contain the raw response body as a byte array under these conditions:
	// 1) there was a problem un-marshalling a JSON response body -
	// either for a successful or unsuccessful operation.
	// 2) the operation was unsuccessful, and the response body contains a non-JSON response.
	RawResult []byte
}

DetailedResponse holds the response information received from the server.

func (*DetailedResponse) GetHeaders

func (response *DetailedResponse) GetHeaders() http.Header

GetHeaders returns the headers

func (*DetailedResponse) GetRawResult

func (response *DetailedResponse) GetRawResult() []byte

GetRawResult returns the raw response body as a byte array.

func (*DetailedResponse) GetResult

func (response *DetailedResponse) GetResult() interface{}

GetResult returns the result from the service

func (*DetailedResponse) GetResultAsMap

func (response *DetailedResponse) GetResultAsMap() (map[string]interface{}, bool)

GetResultAsMap returns the result as a map (generic JSON object), if the DetailedResponse.Result field contains an instance of a map.

func (*DetailedResponse) GetStatusCode

func (response *DetailedResponse) GetStatusCode() int

GetStatusCode returns the HTTP status code

func (*DetailedResponse) String

func (response *DetailedResponse) String() string

type Error

type Error struct {
	Message string `json:"message,omitempty"`
}

Error is a struct used to represent a single error received in an operation response.

type Errors

type Errors struct {
	Errors []Error `json:"errors,omitempty"`
}

Errors is a struct used to hold an array of errors received in an operation response.

type FormData

type FormData struct {
	// contains filtered or unexported fields
}

FormData stores information for form data.

type IamAuthenticator

type IamAuthenticator struct {

	// The apikey used to fetch the bearer token from the IAM token server
	// [required].
	ApiKey string

	// The URL representing the IAM token server's endpoint; If not specified,
	// a suitable default value will be used [optional].
	URL string

	// If neither field is specified, then no Authorization header will be sent
	// with token server requests [optional]. These fields are optional, but must
	// be specified together.
	ClientId string

	// If neither field is specified, then no Authorization header will be sent
	// with token server requests [optional]. These fields are optional, but must
	// be specified together.
	ClientSecret string

	// A flag that indicates whether verification of the server's SSL certificate
	// should be disabled; defaults to false [optional].
	DisableSSLVerification bool

	// [Optional] The "scope" to use when fetching the bearer token from the
	// IAM token server.   This can be used to obtain an access token
	// with a specific scope.
	Scope string

	// [Optional] A set of key/value pairs that will be sent as HTTP headers in requests
	// made to the token server.
	Headers map[string]string

	// [Optional] The http.Client object used to invoke token server requests.
	// If not specified by the user, a suitable default Client will be constructed.
	Client *http.Client
	// contains filtered or unexported fields
}

IamAuthenticator uses an apikey to obtain a suitable bearer token value, and adds the bearer token to requests via an Authorization header of the form:

Authorization: Bearer <bearer-token>

func NewIamAuthenticator

func NewIamAuthenticator(apikey string, url string, clientId string, clientSecret string,
	disableSSLVerification bool, headers map[string]string) (*IamAuthenticator, error)

NewIamAuthenticator constructs a new IamAuthenticator instance.

func (*IamAuthenticator) Authenticate

func (authenticator *IamAuthenticator) Authenticate(request *http.Request) error

Authenticate adds IAM authentication information to the request.

The IAM bearer token will be added to the request's headers in the form:

Authorization: Bearer <bearer-token>

func (IamAuthenticator) AuthenticationType

func (IamAuthenticator) AuthenticationType() string

AuthenticationType returns the authentication type for this authenticator.

func (*IamAuthenticator) RequestToken

func (authenticator *IamAuthenticator) RequestToken() (*IamTokenServerResponse, error)

RequestToken fetches a new access token from the token server.

func (IamAuthenticator) Validate

func (this IamAuthenticator) Validate() error

Validate the authenticator's configuration.

Ensures the ApiKey is valid, and the ClientId and ClientSecret pair are mutually inclusive.

type IamTokenServerResponse

type IamTokenServerResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int64  `json:"expires_in"`
	Expiration   int64  `json:"expiration"`
}

IamTokenServerResponse : This struct models a response received from the token server.

type LogLevel

type LogLevel int

LogLevel defines a type for logging levels

const (
	LevelNone LogLevel = iota
	LevelError
	LevelWarn
	LevelInfo
	LevelDebug
)

Log level constants

type Logger

type Logger interface {
	Log(level LogLevel, format string, inserts ...interface{})
	Error(format string, inserts ...interface{})
	Warn(format string, inserts ...interface{})
	Info(format string, inserts ...interface{})
	Debug(format string, inserts ...interface{})

	SetLogLevel(level LogLevel)
	GetLogLevel() LogLevel
	IsLogLevelEnabled(level LogLevel) bool
}

Logger is the logging interface implemented and used by the Go core library. Users of the library can supply their own implementation by calling SetLogger().

func GetLogger

func GetLogger() Logger

GetLogger returns the Logger instance currently used by the Go core.

type ModelUnmarshaller

type ModelUnmarshaller func(rawInput map[string]json.RawMessage, result interface{}) error

ModelUnmarshaller defines the interface for a generated Unmarshal<model>() function, which is used by the various "UnmarshalModel" functions below to unmarshal an instance of the user-defined model type.

Parameters: rawInput: a map[string]json.RawMessage that is assumed to contain an instance of the model type.

result: the unmarshal destination. This should be a **<model> (i.e. a ptr to a ptr to a model instance). A new instance of the model is constructed by the unmarshaller function and is returned through the ptr passed in as 'result'.

type NoAuthAuthenticator

type NoAuthAuthenticator struct {
}

NoAuthAuthenticator is simply a placeholder implementation of the Authenticator interface that performs no authentication. This might be useful in testing/debugging situations.

func NewNoAuthAuthenticator

func NewNoAuthAuthenticator() (*NoAuthAuthenticator, error)

func (*NoAuthAuthenticator) Authenticate

func (this *NoAuthAuthenticator) Authenticate(request *http.Request) error

func (NoAuthAuthenticator) AuthenticationType

func (NoAuthAuthenticator) AuthenticationType() string

func (NoAuthAuthenticator) Validate

func (NoAuthAuthenticator) Validate() error

type RequestBuilder

type RequestBuilder struct {
	Method string
	URL    *url.URL
	Header http.Header
	Body   io.Reader
	Query  map[string][]string
	Form   map[string][]FormData

	// EnableGzipCompression indicates whether or not request bodies
	// should be gzip-compressed.
	// This field has no effect on response bodies.
	// If enabled, the Body field will be gzip-compressed and
	// the "Content-Encoding" header will be added to the request with the
	// value "gzip".
	EnableGzipCompression bool
	// contains filtered or unexported fields
}

RequestBuilder is used to build an HTTP Request instance.

func NewRequestBuilder

func NewRequestBuilder(method string) *RequestBuilder

NewRequestBuilder initiates a new request.

func (*RequestBuilder) AddFormData

func (requestBuilder *RequestBuilder) AddFormData(fieldName string, fileName string, contentType string,
	contents interface{}) *RequestBuilder

AddFormData adds a new mime part (constructed from the input parameters) to the request's multi-part form.

func (*RequestBuilder) AddHeader

func (requestBuilder *RequestBuilder) AddHeader(name string, value string) *RequestBuilder

AddHeader adds a header name and value to the request.

func (*RequestBuilder) AddQuery

func (requestBuilder *RequestBuilder) AddQuery(name string, value string) *RequestBuilder

AddQuery adds a query parameter name and value to the request.

func (*RequestBuilder) AddQuerySlice

func (requestBuilder *RequestBuilder) AddQuerySlice(param string, slice interface{}) (err error)

AddQuerySlice converts the passed in slice 'slice' by calling the ConverSlice method, and adds the converted slice to the request's query string. An error is returned when conversion fails.

func (*RequestBuilder) Build

func (requestBuilder *RequestBuilder) Build() (req *http.Request, err error)

Build builds an HTTP Request object from this RequestBuilder instance.

func (*RequestBuilder) ConstructHTTPURL

func (requestBuilder *RequestBuilder) ConstructHTTPURL(serviceURL string, pathSegments []string, pathParameters []string) (*RequestBuilder, error)

ConstructHTTPURL creates a properly-encoded URL with path parameters. This function returns an error if the serviceURL is "" or is an invalid URL string (e.g. ":<badscheme>").

func (*RequestBuilder) ResolveRequestURL

func (requestBuilder *RequestBuilder) ResolveRequestURL(serviceURL string, path string, pathParams map[string]string) (*RequestBuilder, error)

ResolveRequestURL creates a properly-encoded URL with path params. This function returns an error if the serviceURL is "" or is an invalid URL string (e.g. ":<badscheme>"). Parameters: serviceURL - the base URL associated with the service endpoint (e.g. "https://myservice.cloud.ibm.com") path - the unresolved path string (e.g. "/resource/{resource_id}/type/{type_id}") pathParams - a map containing the path params, keyed by the path param base name (e.g. {"type_id": "type-1", "resource_id": "res-123-456-789-abc"}) The resulting request URL: "https://myservice.cloud.ibm.com/resource/res-123-456-789-abc/type/type-1"

func (*RequestBuilder) SetBodyContent

func (requestBuilder *RequestBuilder) SetBodyContent(contentType string, jsonContent interface{}, jsonPatchContent interface{},
	nonJSONContent interface{}) (builder *RequestBuilder, err error)

SetBodyContent sets the body content from one of three different sources.

func (*RequestBuilder) SetBodyContentForMultipart

func (requestBuilder *RequestBuilder) SetBodyContentForMultipart(contentType string, content interface{}, writer io.Writer) error

SetBodyContentForMultipart sets the body content for a part in a multi-part form.

func (*RequestBuilder) SetBodyContentJSON

func (requestBuilder *RequestBuilder) SetBodyContentJSON(bodyContent interface{}) (*RequestBuilder, error)

SetBodyContentJSON sets the body content from a JSON structure.

func (*RequestBuilder) SetBodyContentStream

func (requestBuilder *RequestBuilder) SetBodyContentStream(bodyContent io.Reader) (*RequestBuilder, error)

SetBodyContentStream sets the body content from an io.Reader instance.

func (*RequestBuilder) SetBodyContentString

func (requestBuilder *RequestBuilder) SetBodyContentString(bodyContent string) (*RequestBuilder, error)

SetBodyContentString sets the body content from a string.

func (*RequestBuilder) WithContext

func (requestBuilder *RequestBuilder) WithContext(ctx context.Context) *RequestBuilder

WithContext sets "ctx" as the Context to be associated with the http.Request instance that will be constructed by the Build() method.

type SDKLoggerImpl

type SDKLoggerImpl struct {
	// contains filtered or unexported fields
}

SDKLoggerImpl is the Go core's implementation of the Logger interface. This logger contains two instances of Go's log.Logger interface which are used to perform message logging. "infoLogger" is used to log info/warn/debug messages. If specified as nil, then a default log.Logger instance that uses stdout will be created and used for "infoLogger". "errorLogger" is used to log error messages. If specified as nil, then a default log.Logger instance that uses stderr will be created and used for "errorLogger".

func NewLogger

func NewLogger(level LogLevel, infoLogger *log.Logger, errorLogger *log.Logger) *SDKLoggerImpl

NewLogger constructs an SDKLoggerImpl instance with the specified logging level enabled. The "infoLogger" parameter is the log.Logger instance to be used to log info/warn/debug messages. If specified as nil, then a default log.Logger instance that writes messages to "stdout" will be used. The "errorLogger" parameter is the log.Logger instance to be used to log error messages. If specified as nil, then a default log.Logger instance that writes messages to "stderr" will be used.

func (*SDKLoggerImpl) Debug

func (l *SDKLoggerImpl) Debug(format string, inserts ...interface{})

Debug logs a message at level "Debug"

func (*SDKLoggerImpl) Error

func (l *SDKLoggerImpl) Error(format string, inserts ...interface{})

Error logs a message at level "Error"

func (*SDKLoggerImpl) GetLogLevel

func (l *SDKLoggerImpl) GetLogLevel() LogLevel

GetLogLevel sets level to be the current logging level

func (*SDKLoggerImpl) Info

func (l *SDKLoggerImpl) Info(format string, inserts ...interface{})

Info logs a message at level "Info"

func (*SDKLoggerImpl) IsLogLevelEnabled

func (l *SDKLoggerImpl) IsLogLevelEnabled(level LogLevel) bool

IsLogLevelEnabled returns true iff the logger's current logging level indicates that 'level' is enabled.

func (*SDKLoggerImpl) Log

func (l *SDKLoggerImpl) Log(level LogLevel, format string, inserts ...interface{})

Log will log the specified message on the appropriate log.Logger instance if "level" is currently enabled.

func (*SDKLoggerImpl) SetLogLevel

func (l *SDKLoggerImpl) SetLogLevel(level LogLevel)

SetLogLevel sets level to be the current logging level

func (*SDKLoggerImpl) Warn

func (l *SDKLoggerImpl) Warn(format string, inserts ...interface{})

Warn logs a message at level "Warn"

type ServiceOptions

type ServiceOptions struct {
	// This is the base URL associated with the service instance. This value will
	// be combined with the paths for each operation to form the request URL
	// [required].
	URL string

	// Authenticator holds the authenticator implementation to be used by the
	// service instance to authenticate outbound requests, typically by adding the
	// HTTP "Authorization" header.
	Authenticator Authenticator

	// EnableGzipCompression indicates whether or not request bodies
	// should be gzip-compressed.
	// This field has no effect on response bodies.
	// If enabled, the Body field will be gzip-compressed and
	// the "Content-Encoding" header will be added to the request with the
	// value "gzip".
	EnableGzipCompression bool
}

ServiceOptions is a struct of configuration values for a service.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL