chttp

package
v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2020 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package chttp provides a minimal HTTP driver backend for communicating with CouchDB servers.

Index

Constants

View Source
const (
	UserAgent = "Kivik chttp"
	Version   = "2.0.0-prerelease"
)

The default UserAgent values

View Source
const (
	HeaderDestination    = "Destination"
	HeaderIdempotencyKey = "X-Idempotency-Key"
)

Standard headers used by CouchDB.

View Source
const (
	// Exited with an unknown failure.
	ExitUnknownFailure = 1
	// Failed to initialize.
	ExitFailedToInitialize = 2
	// URL malformed. The syntax was not correct.
	ExitStatusURLMalformed = 3
	// The given remote host was not resolved.
	ExitHostNotResolved = 6
	// Failed to connect to host.
	ExitFailedToConnect = 7
	// Weird server reply. The server sent data kouch couldn't parse.
	ExitWeirdReply = 8
	// The requested url was not found or returned another error with the HTTP error code being 400 or above.
	ExitNotRetrieved = 22
	// Write error. Kouch couldn't write data to a local filesystem or similar.
	ExitWriteError = 23
	// Read error. Various reading problems.
	ExitReadError = 26
	// The specified time-out period was reached according to the conditions.
	ExitOperationTimeout = 28
	// Internal post request generation error.
	ExitPostError = 34
	// When following redirects, curl hit the maximum amount.
	ExitTooManyRedirects = 47
)

Exit statuses, borrowed from Curl. Not all Curl statuses are represented here.

Variables

This section is empty.

Functions

func BodyEncoder

func BodyEncoder(i interface{}) func() (io.ReadCloser, error)

BodyEncoder returns a function which returns the encoded body. It is meant to be used as a http.Request.GetBody value.

func DecodeJSON

func DecodeJSON(r *http.Response, i interface{}) error

DecodeJSON unmarshals the response body into i. This method consumes and closes the response body.

func ETag

func ETag(resp *http.Response) (string, bool)

ETag returns the unquoted ETag value, and a bool indicating whether it was found.

func EncodeBody

func EncodeBody(i interface{}) io.ReadCloser

EncodeBody JSON encodes i to an io.ReadCloser. If an encoding error occurs, it will be returned on the next read.

func EncodeDocID

func EncodeDocID(docID string) string

EncodeDocID encodes a document ID according to CouchDB's path encoding rules.

In particular: - '_design/' and '_local/' prefixes are unaltered. - The rest of the docID is Query-URL encoded (despite being part of the path)

func ExitStatus

func ExitStatus(err error) int

ExitStatus returns the curl exit status embedded in the error, or 1 (unknown error), if there was no specified exit status. If err is nil, ExitStatus returns 0.

func GetRev

func GetRev(resp *http.Response) (rev string, err error)

GetRev extracts the revision from the response's Etag header

func ResponseError

func ResponseError(resp *http.Response) error

ResponseError returns an error from an *http.Response.

func WithClientTrace

func WithClientTrace(ctx context.Context, trace *ClientTrace) context.Context

WithClientTrace returns a new context based on the provided parent ctx. HTTP client requests made with the returned context will use the provided trace hooks, in addition to any previous hooks registered with ctx. Any hooks defined in the provided trace will be called first.

Types

type Authenticator

type Authenticator interface {
	Authenticate(*Client) error
}

Authenticator is an interface that provides authentication to a server.

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
	// contains filtered or unexported fields
}

BasicAuth provides HTTP Basic Auth for a client.

func (*BasicAuth) Authenticate

func (a *BasicAuth) Authenticate(c *Client) error

Authenticate sets HTTP Basic Auth headers for the client.

func (*BasicAuth) RoundTrip

func (a *BasicAuth) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip fulfills the http.RoundTripper interface. It sets HTTP Basic Auth on outbound requests.

type Client

type Client struct {
	// UserAgents is appended to set the User-Agent header. Typically it should
	// contain pairs of product name and version.
	UserAgents []string

	*http.Client
	// contains filtered or unexported fields
}

Client represents a client connection. It embeds an *http.Client

func New

func New(dsn string) (*Client, error)

New returns a connection to a remote CouchDB server. If credentials are included in the URL, requests will be authenticated using Cookie Auth. To use HTTP BasicAuth or some other authentication mechanism, do not specify credentials in the URL, and instead call the Auth() method later.

func NewWithClient

func NewWithClient(client *http.Client, dsn string) (*Client, error)

NewWithClient works the same as New(), but allows providing a custom *http.Client for all network connections.

func (*Client) Auth

func (c *Client) Auth(a Authenticator) error

Auth authenticates using the provided Authenticator.

func (*Client) DSN

func (c *Client) DSN() string

DSN returns the unparsed DSN used to connect.

func (*Client) DoError

func (c *Client) DoError(ctx context.Context, method, path string, opts *Options) (*http.Response, error)

DoError is the same as DoReq(), followed by checking the response error. This method is meant for cases where the only information you need from the response is the status code. It unconditionally closes the response body.

func (*Client) DoJSON

func (c *Client) DoJSON(ctx context.Context, method, path string, opts *Options, i interface{}) (*http.Response, error)

DoJSON combines DoReq() and, ResponseError(), and (*Response).DecodeJSON(), and closes the response body.

func (*Client) DoReq

func (c *Client) DoReq(ctx context.Context, method, path string, opts *Options) (*http.Response, error)

DoReq does an HTTP request. An error is returned only if there was an error processing the request. In particular, an error status code, such as 400 or 500, does _not_ cause an error to be returned.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error)

NewRequest returns a new *http.Request to the CouchDB server, and the specified path. The host, schema, etc, of the specified path are ignored.

type ClientTrace

type ClientTrace struct {
	// HTTPResponse returns a cloe of the *http.Response received from the
	// server, with the body set to nil. If you need the body, use the more
	// expensive HTTPResponseBody.
	HTTPResponse func(*http.Response)

	// HTTPResponseBody returns a clone of the *http.Response received from the
	// server, with the body cloned. This can be expensive for responses
	// with large bodies.
	HTTPResponseBody func(*http.Response)

	// HTTPRequest returns a clone of the *http.Request sent to the server, with
	// the body set to nil. If you need the body, use the more expensive
	// HTTPRequestBody.
	HTTPRequest func(*http.Request)

	// HTTPRequestBody returns a clone of the *http.Request sent to the server,
	// with the body cloned, if it is set. This can be expensive for requests
	// with large bodies.
	HTTPRequestBody func(*http.Request)
}

ClientTrace is a set of hooks to run at various stages of an outgoing HTTP request. Any particular hook may be nil. Functions may be called concurrently from different goroutines and some may be called after the request has completed or failed.

func ContextClientTrace

func ContextClientTrace(ctx context.Context) *ClientTrace

ContextClientTrace returns the ClientTrace associated with the provided context. If none, it returns nil.

type CookieAuth

type CookieAuth struct {
	Username string `json:"name"`
	Password string `json:"password"`
	// contains filtered or unexported fields
}

CookieAuth provides CouchDB Cookie auth services as described at http://docs.couchdb.org/en/2.0.0/api/server/authn.html#cookie-authentication

CookieAuth stores authentication state after use, so should not be re-used.

func (*CookieAuth) Authenticate

func (a *CookieAuth) Authenticate(c *Client) error

Authenticate initiates a session with the CouchDB server.

func (*CookieAuth) Cookie added in v1.0.7

func (a *CookieAuth) Cookie() *http.Cookie

Cookie returns the current session cookie if found, or nil if not.

func (*CookieAuth) RoundTrip

func (a *CookieAuth) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip fulfills the http.RoundTripper interface. It sets (re-)authenticates when the cookie has expired or is not yet set.

type HTTPError

type HTTPError struct {
	// Response is the HTTP response received by the client.  Typically the
	// response body has already been consumed, but the response and request
	// headers and other metadata will typically be in tact for debugging
	// purposes.
	Response *http.Response `json:"-"`

	// Reason is the server-supplied error reason.
	Reason string `json:"reason"`
	// contains filtered or unexported fields
}

HTTPError is an error that represents an HTTP transport error.

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) ExitStatus

func (e *HTTPError) ExitStatus() int

ExitStatus returns the embedded exit status.

func (*HTTPError) Format

func (e *HTTPError) Format(f fmt.State, c rune)

Format implements fmt.Formatter

func (*HTTPError) FormatError

func (e *HTTPError) FormatError(p printer) error

FormatError satisfies the Go 1.13 errors.Formatter interface (golang.org/x/xerrors.Formatter for older versions of Go).

func (*HTTPError) StatusCode

func (e *HTTPError) StatusCode() int

StatusCode returns the embedded status code.

type Options

type Options struct {
	// Accept sets the request's Accept header. Defaults to "application/json".
	// To specify any, use "*/*".
	Accept string

	// ContentType sets the requests's Content-Type header. Defaults to "application/json".
	ContentType string

	// ContentLength, if set, sets the ContentLength of the request
	ContentLength int64

	// Body sets the body of the request.
	Body io.ReadCloser

	// GetBody is a function to set the body, and can be used on retries. If
	// set, Body is ignored.
	GetBody func() (io.ReadCloser, error)

	// JSON is an arbitrary data type which is marshaled to the request's body.
	// It an error to set both Body and JSON on the same request. When this is
	// set, ContentType is unconditionally set to 'application/json'. Note that
	// for large JSON payloads, it can be beneficial to do your own JSON stream
	// encoding, so that the request can be live on the wire during JSON
	// encoding.
	JSON interface{}

	// FullCommit adds the X-Couch-Full-Commit: true header to requests
	FullCommit bool

	// IfNoneMatch adds the If-None-Match header. The value will be quoted if
	// it is not already.
	IfNoneMatch string

	// Query is appended to the exiting url, if present. If the passed url
	// already contains query parameters, the values in Query are appended.
	// No merging takes place.
	Query url.Values

	// Header is a list of default headers to be set on the request.
	Header http.Header
}

Options are optional parameters which may be sent with a request.

type ProxyAuth

type ProxyAuth struct {
	Username string
	Secret   string
	Roles    []string
	Headers  http.Header
	// contains filtered or unexported fields
}

func (*ProxyAuth) Authenticate

func (a *ProxyAuth) Authenticate(c *Client) error

func (*ProxyAuth) RoundTrip

func (a *ProxyAuth) RoundTrip(req *http.Request) (*http.Response, error)

type Response

type Response struct {
	*http.Response

	// ContentType is the base content type, parsed from the response headers.
	ContentType string
}

Response represents a response from a CouchDB server.

Jump to

Keyboard shortcuts

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