jape

package
v0.0.0-...-d727afa Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2023 License: MIT Imports: 10 Imported by: 3

Documentation

Overview

Package jape implements a client for a JSON-based HTTP API.

Usage outline

cli := &jape.Client{
   BaseURL:   "https://api.whatevs.com/v2",
   Authorize: jape.BearerTokenAuthorizer(token),
}

ctx := context.Background()
headers, body, err := cli.Call(ctx, &jape.Request{
   Method: "service/method",
   Params: jape.Params{
      "ids": {"a", "b", "c"},
   },
   Data:        []byte("fly you fools"),
   ContentType: "text/plain",
})
if err != nil {
   log.Fatalf("Request failed: %v", err)
}
process(headers, body)

Index

Constants

View Source
const (
	// DefaultContentType is the default content-type reported for a request body.
	DefaultContentType = "application/json"
)

Variables

View Source
var ErrStopStreaming = errors.New("stop streaming")

ErrStopStreaming is a sentinel error that a stream callback can use to signal it does not want any further results.

Functions

This section is empty.

Types

type Authorizer

type Authorizer func(*http.Request) error

An Authorizer attaches authorization metadata to an outbound request after it has been populated with the caller's query but before it is sent to the API. The function modifies the request in-place as needed.

func BearerTokenAuthorizer

func BearerTokenAuthorizer(token string) Authorizer

BearerTokenAuthorizer returns an authorizer that injects the specified bearer token into the Authorization header of each request.

type Callback

type Callback func([]byte) error

A Callback function is invoked for each reply received in a stream. If the callback reports a non-nil error, the stream is terminated. If the error is anything other than ErrStopStreaming, it is reported to the caller.

type Client

type Client struct {
	// The HTTP client used to issue requests to the API.
	// If nil, use http.DefaultClient.
	HTTPClient *http.Client

	// If set, this is called prior to issuing the request to the API.  If it
	// reports an error, the request is aborted and the error is returned to the
	// caller.
	Authorize func(*http.Request) error

	// Defines the base URL for requests to the API.
	BaseURL string

	// If set, this function is called to log interesting events during the
	// transaction.
	Log LogFunc

	// If non-zero, only log tags in this mask are sent to the log function.
	LogMask LogTag
}

A Client serves as a client for an JSON-based HTTP API.

func (*Client) Call

func (c *Client) Call(ctx context.Context, req *Request) (http.Header, []byte, error)

Call issues the specified API request and returns the HTTP response headers and response body without decoding. Errors from Call have type *jape.Error.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, req *Request, f Callback) error

Stream issues the specified API request and streams results to the given callback. Errors from Stream have concrete type *jape.Error.

type Error

type Error struct {
	Message string // a description of the error
	Status  int    // an HTTP status code, if known
	Err     error  // the underlying error, if any
	Data    []byte // the response data from the server, if any
}

Error is the concrete type of errors returned by a Call.

func (*Error) Error

func (e *Error) Error() string

Error satisfies the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap satisfies the wrapping interface for the errors package.

type LogFunc

type LogFunc func(tag LogTag, message string)

A LogFunc receives log messages from the client.

type LogTag

type LogTag int

LogTag identifies the kind of log message being written to a logger.

const (
	// The request URL sent to the server
	LogRequestURL LogTag = 1 << iota
	// The contents of the HTTP Authorization header
	LogAuthorization
	// The HTTP status string (e.g., "200 OK")
	LogHTTPStatus
	// The body of the response sent by the server
	LogResponseBody
	// The body of a stream response from the server
	LogStreamBody
)

Constants for LogTag. These may be combined as a bitmask to filter a log function.

func (LogTag) String

func (t LogTag) String() string

type Params

type Params map[string][]string

Params carries additional request parameters sent in the query URL.

func (Params) Add

func (p Params) Add(name string, values ...string)

Add the given values for the specified parameter, in addition to any previously-defined values for that name.

func (Params) Encode

func (p Params) Encode() string

Encode encodes p as a query string. If len(p) == 0, Encode returns "".

func (Params) Reset

func (p Params) Reset(name string)

Reset removes any existing values for the specified parameter.

func (Params) Set

func (p Params) Set(name, value string)

Set sets the value of the specified parameter name, removing any previously-defined values for that name.

type Request

type Request struct {
	// The fully-expanded method path for the API to call, including parameters.
	// For example: "service/method/12345".
	Method string

	// Additional request parameters, including optional fields and expansions.
	Params Params

	// The HTTP method to use for the request; if unset the default is "GET".
	HTTPMethod string

	// If non-empty, send these data as the body of the request.
	Data []byte

	// If set, use this as the content-type for the request body.
	// If unset, the value defaults to DefaultContentType (JSON).
	// A content-type is only set if Data is non-empty.
	ContentType string
}

A Request is the generic format for a request.

func (*Request) Body

func (r *Request) Body() (data io.Reader, size int64, ctype string)

Body returns the size and putative content-type of the request body, along with a reader that will deliver its contents.

If no data are set on the request, Body returns nil, 0, "".

func (*Request) SetBodyToParams

func (r *Request) SetBodyToParams()

SetBodyToParams encodes r.Params in the request body. This replaces the Data and ContentType fields, and leaves r.Params set to nil.

func (*Request) URL

func (r *Request) URL(base string) (string, error)

URL returns the complete request URL for r, using base as the base URL.

Directories

Path Synopsis
Package auth supports OAuth 1.0a request signing.
Package auth supports OAuth 1.0a request signing.

Jump to

Keyboard shortcuts

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