rest

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2021 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultQPS            float32 = 5.0
	DefaultBurst          int     = 10
	DefaultTimeOut        int     = 10
	DefaultVersionApiPath string  = "/api/v2.0"
)

Variables

This section is empty.

Functions

func DefaultServerURL

func DefaultServerURL(host string) (*url.URL, 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 Kubernetes API.

func TransportFor

func TransportFor() *http.Transport

Types

type Config

type Config struct {
	// Host must be a host string, a host:port pair, or a URL to the base of the apiserver.
	// If a URL is given then the (optional) Path of that URL represents a prefix that must
	// be appended to all request URIs used to access the apiserver. This allows a frontend
	// proxy to easily relocate all of the apiserver endpoints.
	Host string
	// APIPath is a sub-path that points to an API root.
	APIPath string

	// ContentConfig contains settings that affect how objects are transformed when
	// sent to the server.
	ContentConfig

	// Server requires Basic authentication
	Username string
	Password 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

	// DisableCompression bypasses automatic GZip compression requests to the
	// server.
	DisableCompression bool

	// Transport may be used for custom HTTP behavior. This attribute may not
	// be specified with the TLS client certificate options. Use WrapTransport
	// to provide additional per-server middleware behavior.
	Transport http.RoundTripper

	// QPS indicates the maximum QPS to the master from this client.
	// If it's zero, the created RESTClient will use DefaultQPS: 5
	QPS float32

	// Maximum burst for throttle.
	// If it's zero, the created RESTClient will use DefaultBurst: 10.
	Burst int

	// Rate limiter for limiting connections to the master from this client. If present overwrites QPS/Burst
	RateLimiter flowcontrol2.RateLimiter

	// The maximum length of time to wait before giving up on a server request. A value of zero means no timeout.
	Timeout time.Duration

	// Dial specifies the dial function for creating unencrypted TCP connections.
	Dial func(ctx context.Context, network, address string) (net.Conn, error)
}

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

func NewDefaultConfig

func NewDefaultConfig(host string, username string, password string) *Config

type ContentConfig

type ContentConfig struct {
	// 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, and
	// as the default content type on any object sent to the server. If not set,
	// "application/json" is used.
	ContentType string
}

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is an interface for testing a request object.

type Interface

type Interface interface {
	Verb(verb string) *Request
	Post() *Request
	Put() *Request
	List() *Request
	Get() *Request
	Delete() *Request
}

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

type RESTClient

type RESTClient struct {
	Throttle flowcontrol2.RateLimiter

	// Set specific behavior of the client.  If not set http.DefaultClient will be used.
	Client *http.Client
	// contains filtered or unexported fields
}

RESTClient imposes common Kubernetes 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 Kubernetes API client.

func NewRESTClient

func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ContentConfig, headers map[string]string, maxQPS float32, maxBurst int, rateLimiter flowcontrol2.RateLimiter, client *http.Client) (*RESTClient, error)

NewRESTClient creates a new RESTClient. This client performs generic REST functions such as Get, Put, Post, and Delete on specified paths. Codec controls encoding and decoding of responses from the server.

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 Kubernetes conventions, but may not be the Kubernetes API.

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) List

func (c *RESTClient) List() *Request

func (*RESTClient) Post

func (c *RESTClient) Post() *Request

func (*RESTClient) Put

func (c *RESTClient) Put() *Request

func (*RESTClient) Verb

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

Verb begins a request with a verb (GET, POST, PUT, DELETE).

Example usage of RESTClient's request building interface: c, err := NewRESTClient(...) if err != nil { ... } resp, err := c.Verb("GET").

Path("pods").
SelectorParam("labels", "area=staging").
Timeout(10*time.Second).
Do()

if err != nil { ... } list, ok := resp.(*api.PodList)

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(client HTTPClient, verb string, baseURL *url.URL, headers map[string]string, versionedAPIPath string, content ContentConfig, throttle flowcontrol2.RateLimiter, timeout time.Duration) *Request

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

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. If obj is a string, try to read a file of that name. If obj is a []byte, send it directly. If obj is an io.Reader, use it directly. If obj is a runtime.Object, marshal it correctly, and set Content-Type header. If obj is a runtime.Object and nil, do nothing. Otherwise, set an error.

func (*Request) Do

func (r *Request) Do() Result

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

Error type:

  • If the request can't be constructed, or an error happened earlier while building its arguments: *RequestConstructionError
  • If the server responds with a status: *errors.StatusError or *errors.UnexpectedObjectError
  • http.Client.Do errors are returned directly.

func (*Request) DoRaw

func (r *Request) DoRaw() ([]byte, error)

DoRaw executes the request but does not process the response body.

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) Params

func (r *Request) Params(o interface{}) *Request

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) Project

func (r *Request) Project(project string) *Request

Project applies the namespace scope to a request (<resource>/[ns/<namespace>/]<name>)

func (*Request) Query

func (r *Request) Query(content interface{}) *Request

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

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.

type RequestConstructionError

type RequestConstructionError struct {
	Err error
}

RequestConstructionError is returned when there's an error assembling a request.

func (*RequestConstructionError) Error

func (r *RequestConstructionError) Error() string

Error returns a textual description of 'r'.

type ResponseWrapper

type ResponseWrapper interface {
	DoRaw() ([]byte, error)
	Stream() (io.ReadCloser, error)
}

ResponseWrapper is an interface for getting a response. The response may be either accessed as a raw data (the whole output is put into memory) or as a stream.

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

func (Result) Into

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

Into stores the result into obj, if possible. If obj is nil it is ignored. If the returned object is of type Status and has .Status != StatusSuccess, the additional information in Status will be used to enrich the error.

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 +k8s:deepcopy-gen=true

func (*TLSClientConfig) DeepCopy

func (in *TLSClientConfig) DeepCopy() *TLSClientConfig

DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSClientConfig.

func (*TLSClientConfig) DeepCopyInto

func (in *TLSClientConfig) DeepCopyInto(out *TLSClientConfig)

DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

Directories

Path Synopsis
util

Jump to

Keyboard shortcuts

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