rest

package
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2021 License: Apache-2.0, BSD-2-Clause, BSD-3-Clause, + 1 more Imports: 21 Imported by: 8

Documentation

Overview

Package rest can used to deal with restful request. Use gorequest as the http engine.

Index

Constants

This section is empty.

Variables

View Source
var NameMayNotBe = []string{".", ".."}

NameMayNotBe specifies strings that cannot be used as names specified as path segments (like the REST API or etcd store).

View Source
var NameMayNotContain = []string{"/", "%"}

NameMayNotContain specifies substrings that cannot be used in names specified as path segments (like the REST API or etcd store).

Functions

func DefaultServerURL

func DefaultServerURL(host, apiPath string, groupVersion scheme.GroupVersion,
	defaultTLS bool) (*url.URL, string, error)

DefaultServerURL converts a host, host:port, or URL string to the default base server API path to use with a Client at a given API version following the standard conventions for a IAM API.

func DefaultUserAgent

func DefaultUserAgent() string

DefaultUserAgent returns a User-Agent string built from static global vars.

func DefaultVersionedAPIPath

func DefaultVersionedAPIPath(apiPath string, groupVersion scheme.GroupVersion) string

DefaultVersionedAPIPath constructs the default path for the given group version, assuming the given API path, following the standard conventions of the IAM API.

func IsValidPathSegmentName

func IsValidPathSegmentName(name string) []string

IsValidPathSegmentName validates the name can be safely encoded as a path segment.

func IsValidPathSegmentPrefix

func IsValidPathSegmentPrefix(name string) []string

IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment. It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid.

func LoadTLSFiles

func LoadTLSFiles(c *Config) error

LoadTLSFiles copies the data from the CertFile, KeyFile, and CAFile fields into the CertData, KeyData, and CAFile fields, or returns an error. If no error is returned, all three fields are either populated or were empty to start.

func SetIAMDefaults

func SetIAMDefaults(config *Config) error

SetIAMDefaults sets default values on the provided client config for accessing the IAM API or returns an error if any of the defaults are impossible or invalid.

func TLSConfigFor

func TLSConfigFor(c *Config) (*tls.Config, error)

TLSConfigFor returns a tls.Config that will provide the transport level security defined by the provided Config. Will return nil if no transport level security is requested.

func ValidatePathSegmentName

func ValidatePathSegmentName(name string, prefix bool) []string

ValidatePathSegmentName validates the name can be safely encoded as a path segment.

Types

type ClientContentConfig

type ClientContentConfig struct {
	Username string
	Password string

	SecretID  string
	SecretKey string
	// Server requires Bearer authentication. This client will not attempt to use
	// refresh tokens for an OAuth2 flow.
	// TODO: demonstrate an OAuth2 compatible client.
	BearerToken string

	// Path to a file containing a BearerToken.
	// If set, the contents are periodically read.
	// The last successfully read value takes precedence over BearerToken.
	BearerTokenFile string
	TLSClientConfig

	// AcceptContentTypes specifies the types the client will accept and is optional.
	// If not set, ContentType will be used to define the Accept header
	AcceptContentTypes string
	// ContentType specifies the wire format used to communicate with the server.
	// This value will be set as the Accept header on requests made to the server if
	// AcceptContentTypes is not set, and as the default content type on any object
	// sent to the server. If not set, "application/json" is used.
	ContentType  string
	GroupVersion scheme.GroupVersion
	Negotiator   runtime.ClientNegotiator
}

ClientContentConfig controls how RESTClient communicates with the server.

func (*ClientContentConfig) HasBasicAuth

func (c *ClientContentConfig) HasBasicAuth() bool

HasBasicAuth returns whether the configuration has basic authentication or not.

func (*ClientContentConfig) HasKeyAuth

func (c *ClientContentConfig) HasKeyAuth() bool

HasKeyAuth returns whether the configuration has secretId/secretKey authentication or not.

func (*ClientContentConfig) HasTokenAuth

func (c *ClientContentConfig) HasTokenAuth() bool

HasTokenAuth returns whether the configuration has token authentication or not.

type Config

type Config struct {
	Host    string
	APIPath string
	ContentConfig

	// Server requires Basic authentication
	Username string
	Password string

	SecretID  string
	SecretKey string

	// Server requires Bearer authentication. This client will not attempt to use
	// refresh tokens for an OAuth2 flow.
	// TODO: demonstrate an OAuth2 compatible client.
	BearerToken string

	// Path to a file containing a BearerToken.
	// If set, the contents are periodically read.
	// The last successfully read value takes precedence over BearerToken.
	BearerTokenFile string

	// TLSClientConfig contains settings to enable transport layer security
	TLSClientConfig

	// UserAgent is an optional field that specifies the caller of this request.
	UserAgent string
	// The maximum length of time to wait before giving up on a server request. A value of zero means no timeout.
	Timeout       time.Duration
	MaxRetries    int
	RetryInterval time.Duration
}

Config holds the common attributes that can be passed to a IAM client on initialization.

func AddUserAgent

func AddUserAgent(config *Config, userAgent string) *Config

AddUserAgent add a http User-Agent header.

func CopyConfig

func CopyConfig(config *Config) *Config

CopyConfig returns a copy of the given config.

func (*Config) GoString

func (c *Config) GoString() string

GoString implements fmt.GoStringer and sanitizes sensitive fields of Config to prevent accidental leaking via logs.

func (*Config) String

func (c *Config) String() string

String implements fmt.Stringer and sanitizes sensitive fields of Config to prevent accidental leaking via logs.

type ContentConfig

type ContentConfig struct {
	ServiceName        string
	AcceptContentTypes string
	ContentType        string
	GroupVersion       *scheme.GroupVersion
	Negotiator         runtime.ClientNegotiator
}

ContentConfig defines config for content.

type Interface

type Interface interface {
	Verb(verb string) *Request
	Post() *Request
	Put() *Request
	// Patch(pt types.PatchType) *Request
	Get() *Request
	Delete() *Request
	APIVersion() scheme.GroupVersion
}

Interface captures the set of operations for generically interacting with IAM REST apis.

type RESTClient

type RESTClient struct {
	Client *gorequest.SuperAgent
	// contains filtered or unexported fields
}

RESTClient imposes common IAM API conventions on a set of resource paths. The baseURL is expected to point to an HTTP or HTTPS path that is the parent of one or more resources. The server should return a decodable API resource object, or an api.Status object which contains information about the reason for any failure.

Most consumers should use client.New() to get a IAM API client.

func NewRESTClient

func NewRESTClient(baseURL *url.URL, versionedAPIPath string,
	config ClientContentConfig, client *gorequest.SuperAgent) (*RESTClient, error)

NewRESTClient creates a new RESTClient. This client performs generic REST functions such as Get, Put, Post, and Delete on specified paths.

func RESTClientFor

func RESTClientFor(config *Config) (*RESTClient, error)

RESTClientFor returns a RESTClient that satisfies the requested attributes on a client Config object. Note that a RESTClient may require fields that are optional when initializing a Client. A RESTClient created by this method is generic - it expects to operate on an API that follows the IAM conventions, but may not be the IAM API.

func (*RESTClient) APIVersion

func (c *RESTClient) APIVersion() scheme.GroupVersion

APIVersion returns the APIVersion this RESTClient is expected to use.

func (*RESTClient) Delete

func (c *RESTClient) Delete() *Request

Delete begins a DELETE request. Short for c.Verb("DELETE").

func (*RESTClient) Get

func (c *RESTClient) Get() *Request

Get begins a GET request. Short for c.Verb("GET").

func (*RESTClient) Post

func (c *RESTClient) Post() *Request

Post begins a POST request. Short for c.Verb("POST").

func (*RESTClient) Put

func (c *RESTClient) Put() *Request

Put begins a PUT request. Short for c.Verb("PUT").

func (*RESTClient) Verb

func (c *RESTClient) Verb(verb string) *Request

Verb begins a Verb request.

type Request

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

Request allows for building up a request to a server in a chained fashion. Any errors are stored until the end of your call, so you only have to check once.

func NewRequest

func NewRequest(c *RESTClient) *Request

NewRequest creates a new request helper object for accessing runtime.Objects on a server.

func NewRequestWithClient

func NewRequestWithClient(base *url.URL, versionedAPIPath string,
	content ClientContentConfig, client *gorequest.SuperAgent) *Request

NewRequestWithClient creates a Request with an embedded RESTClient for use in test scenarios.

func (*Request) AbsPath

func (r *Request) AbsPath(segments ...string) *Request

AbsPath overwrites an existing path with the segments provided. Trailing slashes are preserved when a single segment is passed.

func (*Request) Body

func (r *Request) Body(obj interface{}) *Request

Body makes the request use obj as the body. Optional.

func (*Request) Do

func (r *Request) Do(ctx context.Context) Result

Do formats and executes the request. Returns a Result object for easy response processing.

func (*Request) Name

func (r *Request) Name(resourceName string) *Request

Name sets the name of a resource to access (<resource>/[ns/<namespace>/]<name>).

func (*Request) Param

func (r *Request) Param(paramName, s string) *Request

Param creates a query parameter with the given string value.

func (*Request) Prefix

func (r *Request) Prefix(segments ...string) *Request

Prefix adds segments to the relative beginning to the request path. These items will be placed before the optional Namespace, Resource, or Name sections. Setting AbsPath will clear any previously set Prefix segments.

func (*Request) RequestURI

func (r *Request) RequestURI(uri string) *Request

RequestURI overwrites existing path and parameters with the value of the provided server relative URI.

func (*Request) Resource

func (r *Request) Resource(resource string) *Request

Resource sets the resource to access (<resource>/[ns/<namespace>/]<name>).

func (*Request) SetHeader

func (r *Request) SetHeader(key string, values ...string) *Request

SetHeader set header for a http request.

func (*Request) SubResource

func (r *Request) SubResource(subresources ...string) *Request

SubResource sets a sub-resource path which can be multiple segments after the resource name but before the suffix.

func (*Request) Suffix

func (r *Request) Suffix(segments ...string) *Request

Suffix appends segments to the end of the path. These items will be placed after the prefix and optional Namespace, Resource, or Name sections.

func (*Request) Timeout

func (r *Request) Timeout(d time.Duration) *Request

Timeout makes the request use the given duration as an overall timeout for the request. Additionally, if set passes the value as "timeout" parameter in URL.

func (*Request) URL

func (r *Request) URL() *url.URL

URL returns the current working URL.

func (*Request) Verb

func (r *Request) Verb(verb string) *Request

Verb sets the verb this request will use.

func (*Request) VersionedParams

func (r *Request) VersionedParams(v interface{}) *Request

VersionedParams will take the provided object, serialize it to a map[string][]string using the implicit RESTClient API version and the default parameter codec, and then add those as parameters to the request. Use this to provide versioned query parameters from client libraries. VersionedParams will not write query parameters that have omitempty set and are empty. If a parameter has already been set it is appended to (Params and VersionedParams are additive).

type Result

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

Result contains the result of calling Request.Do().

func (Result) Error

func (r Result) Error() error

Error implements the error interface.

func (Result) Into

func (r Result) Into(v interface{}) error

Into stores the result into obj, if possible. If obj is nil it is ignored.

func (Result) Raw

func (r Result) Raw() ([]byte, error)

Raw returns the raw result.

type TLSClientConfig

type TLSClientConfig struct {
	// Server should be accessed without verifying the TLS certificate. For testing only.
	Insecure bool
	// ServerName is passed to the server for SNI and is used in the client to check server
	// ceritificates against. If ServerName is empty, the hostname used to contact the
	// server is used.
	ServerName string

	// Server requires TLS client certificate authentication
	CertFile string
	// Server requires TLS client certificate authentication
	KeyFile string
	// Trusted root certificates for server
	CAFile string

	// CertData holds PEM-encoded bytes (typically read from a client certificate file).
	// CertData takes precedence over CertFile
	CertData []byte
	// KeyData holds PEM-encoded bytes (typically read from a client certificate key file).
	// KeyData takes precedence over KeyFile
	KeyData []byte
	// CAData holds PEM-encoded bytes (typically read from a root certificates bundle).
	// CAData takes precedence over CAFile
	CAData []byte

	// NextProtos is a list of supported application level protocols, in order of preference.
	// Used to populate tls.Config.NextProtos.
	// To indicate to the server http/1.1 is preferred over http/2, set to ["http/1.1", "h2"] (though the server is free
	// to ignore that preference).
	// To use only http/1.1, set to ["http/1.1"].
	NextProtos []string
}

TLSClientConfig contains settings to enable transport layer security.

func (TLSClientConfig) GoString

func (c TLSClientConfig) GoString() string

GoString implements fmt.GoStringer and sanitizes sensitive fields of TLSClientConfig to prevent accidental leaking via logs.

func (TLSClientConfig) HasCA

func (c TLSClientConfig) HasCA() bool

HasCA returns whether the configuration has a certificate authority or not.

func (TLSClientConfig) HasCertAuth

func (c TLSClientConfig) HasCertAuth() bool

HasCertAuth returns whether the configuration has certificate authentication or not.

func (TLSClientConfig) String

func (c TLSClientConfig) String() string

String implements fmt.Stringer and sanitizes sensitive fields of TLSClientConfig to prevent accidental leaking via logs.

type TLSConfig

type TLSConfig struct {
	CAFile         string // Path of the PEM-encoded server trusted root certificates.
	CertFile       string // Path of the PEM-encoded client certificate.
	KeyFile        string // Path of the PEM-encoded client key.
	ReloadTLSFiles bool   // Set to indicate that the original config provided files, and that they should be reloaded

	Insecure   bool   // Server should be accessed without verifying the certificate. For testing only.
	ServerName string // Override for the server name passed to the server for SNI and used to verify certificates.

	CAData   []byte // Bytes of the PEM-encoded server trusted root certificates. Supercedes CAFile.
	CertData []byte // Bytes of the PEM-encoded client certificate. Supercedes CertFile.
	KeyData  []byte // Bytes of the PEM-encoded client key. Supercedes KeyFile.
}

TLSConfig holds the information needed to set up a TLS transport.

Jump to

Keyboard shortcuts

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