vrest

package module
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: May 16, 2024 License: Apache-2.0 Imports: 18 Imported by: 1

README

vrest

Simple REST client inspired by the great resty lib.

Why another rest lib?

We really like the API of resty, but there are a few reasons why we created our own lib:

  1. No dependencies: vrest has no dependencies.

  2. Efficient memory usage: We don't want a rest lib to copy body bytes. The lib user should be in control. vrest gives you access to the body bytes (if available).

  3. HTTP abstraction: We want to abstract the HTTP layer away, so there is only one error return value, no HTTP response handling required.

  4. Limited scope: This lib only covers default rest APIs with JSON and XML. We don't plan to add support for handling HTML related stuff like form data or multipart file uploads.

  5. Improved logging/tracing: Tracing requests was designed with Open Telemetry in mind. There is full access to all request/response data.

  6. No data hiding: We provide full access to all internal data in callbacks. You can break things, if you want, so please look at the examples how to perform advanced tasks like overwriting vrest functions.

  7. Configurability: Many configurable settings and replaceable functions. Most settings can be set in client (default for all requests) and each request to override client defaults.

  8. Easy testing: It is easy to replace functions in vrest. There are also some helper functions to mock responses.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrResponseNotUnmarshaled = errors.New("response was not unmarshaled")
)

Functions

func Do

func Do(req *Request) error

func DoHTTPRequest

func DoHTTPRequest(req *Request) (*http.Response, error)

func IsJSONContentType

func IsJSONContentType(contentType string) bool

func IsSuccess

func IsSuccess(req *Request) bool

func IsXMLContentType

func IsXMLContentType(contentType string) bool

func JSONMarshal

func JSONMarshal(req *Request, v interface{}) ([]byte, error)

func JSONUnmarshal

func JSONUnmarshal(req *Request, data []byte, v interface{}) error

func MustReadFile

func MustReadFile(t *testing.T, path string) []byte

func XMLMarshal

func XMLMarshal(req *Request, v interface{}) ([]byte, error)

func XMLUnmarshal

func XMLUnmarshal(req *Request, data []byte, v interface{}) error

Types

type Client

type Client struct {
	BaseURL string

	ResponseBodyLimit int64
	TraceBodies       bool

	ContentType   string
	Authorization string

	ErrorType reflect.Type

	Overridable Overridables
	// contains filtered or unexported fields
}

func New

func New() *Client

func NewWithClient

func NewWithClient(httpClient *http.Client) *Client

func NewWithTimeout

func NewWithTimeout(timeout time.Duration) *Client

func (*Client) NewRequest

func (c *Client) NewRequest() *Request

NewRequest is a shortcut for NewRequestWithContext(context.Background()).

func (*Client) NewRequestWithContext added in v0.0.11

func (c *Client) NewRequestWithContext(ctx context.Context) *Request

NewRequestWithContext creates a new Request instance and initializes its fields with default values. It also sets the Content-Type and Authorization headers of the request if they are provided in the Client struct.

func (*Client) SetAuthorization

func (c *Client) SetAuthorization(auth string) *Client

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string) *Client

func (*Client) SetBasicAuth

func (c *Client) SetBasicAuth(username, password string) *Client

func (*Client) SetBearerAuth

func (c *Client) SetBearerAuth(token string) *Client

func (*Client) SetContentType

func (c *Client) SetContentType(contentType string) *Client

func (*Client) SetContentTypeJSON

func (c *Client) SetContentTypeJSON() *Client

func (*Client) SetContentTypeXML

func (c *Client) SetContentTypeXML() *Client

func (*Client) SetErrorBodyType

func (c *Client) SetErrorBodyType(value error) *Client

func (*Client) SetLogger

func (c *Client) SetLogger(logger *slog.Logger) *Client

func (*Client) SetResponseBodyLimit

func (c *Client) SetResponseBodyLimit(limit int64) *Client

func (*Client) SetTraceBodies

func (c *Client) SetTraceBodies(value bool) *Client

func (*Client) SetTraceMaker

func (c *Client) SetTraceMaker(traceMaker TraceMaker) *Client

type Doer

type Doer func(req *Request) error

func MockDoer

func MockDoer(responseValue interface{}, err error) Doer

type HTTPDoer

type HTTPDoer func(req *Request) (*http.Response, error)

func MockHTTPDoer

func MockHTTPDoer(p *MockHTTPResponse, additionalHeaders ...string) HTTPDoer

type MockHTTPResponse

type MockHTTPResponse struct {
	StatusCode  int
	Body        []byte
	BodyString  string
	BodyReader  io.Reader
	ContentType string
	Error       error

	CapturedRequest *Request
}

func MockJSONResponse

func MockJSONResponse(statusCode int, body string) *MockHTTPResponse

func MockJSONResponseFromFile

func MockJSONResponseFromFile(t *testing.T, statusCode int, filePath string) *MockHTTPResponse

func MockXMLResponse

func MockXMLResponse(statusCode int, body string) *MockHTTPResponse

func MockXMLResponseFromFile

func MockXMLResponseFromFile(t *testing.T, statusCode int, filePath string) *MockHTTPResponse

type Overridables

type Overridables struct {
	Do Doer

	DoHTTPRequest HTTPDoer

	IsSuccess func(req *Request) bool

	JSONMarshal func(req *Request, v interface{}) ([]byte, error)

	JSONUnmarshal func(req *Request, data []byte, v interface{}) error

	XMLMarshal func(req *Request, v interface{}) ([]byte, error)

	XMLUnmarshal func(req *Request, data []byte, v interface{}) error
}

type Request

type Request struct {
	Client        *Client
	Context       context.Context
	Raw           *http.Request
	Method        string
	Path          string
	Header        http.Header
	Query         url.Values
	Body          interface{}
	BodyBytes     []byte
	ContentLength int64
	Response      Response
	Overridable   Overridables
	TraceBody     bool
}

func (*Request) ContentType

func (req *Request) ContentType() string

func (*Request) Do

func (req *Request) Do(method, pathFormat string, values ...any) error

func (*Request) DoConnect

func (req *Request) DoConnect(pathFormat string, values ...any) error

func (*Request) DoDelete

func (req *Request) DoDelete(pathFormat string, values ...any) error

func (*Request) DoGet

func (req *Request) DoGet(pathFormat string, values ...any) error

func (*Request) DoHead

func (req *Request) DoHead(pathFormat string, values ...any) error

func (*Request) DoOptions

func (req *Request) DoOptions(pathFormat string, values ...any) error

func (*Request) DoPatch

func (req *Request) DoPatch(pathFormat string, values ...any) error

func (*Request) DoPost

func (req *Request) DoPost(pathFormat string, values ...any) error

func (*Request) DoPut

func (req *Request) DoPut(pathFormat string, values ...any) error

func (*Request) DoTrace

func (req *Request) DoTrace(pathFormat string, values ...any) error

func (*Request) ForceResponseJSON

func (req *Request) ForceResponseJSON() *Request

func (*Request) ForceResponseXML

func (req *Request) ForceResponseXML() *Request

func (*Request) SetAuthorization

func (req *Request) SetAuthorization(authValue string) *Request

func (*Request) SetBasicAuth

func (req *Request) SetBasicAuth(username, password string) *Request

func (*Request) SetBearerAuth

func (req *Request) SetBearerAuth(token string) *Request

func (*Request) SetBody

func (req *Request) SetBody(body interface{}) *Request

func (*Request) SetContentLength added in v0.0.7

func (req *Request) SetContentLength(contentLength int64) *Request

func (*Request) SetContentType

func (req *Request) SetContentType(contentType string) *Request

func (*Request) SetContentTypeJSON

func (req *Request) SetContentTypeJSON() *Request

func (*Request) SetContentTypeXML

func (req *Request) SetContentTypeXML() *Request

func (*Request) SetContext

func (req *Request) SetContext(ctx context.Context) *Request

func (*Request) SetHeader

func (req *Request) SetHeader(key string, value string) *Request

func (*Request) SetHeaderIf

func (req *Request) SetHeaderIf(condition bool, key string, value string) *Request

func (*Request) SetQueryParam

func (req *Request) SetQueryParam(key string, values ...string) *Request

func (*Request) SetQueryParamIf

func (req *Request) SetQueryParamIf(condition bool, key string, values ...string) *Request

func (*Request) SetResponseBody

func (req *Request) SetResponseBody(value interface{}) *Request

func (*Request) SetResponseBodyLimit

func (req *Request) SetResponseBodyLimit(limit int64) *Request

func (*Request) SetResponseContentLengthPtr added in v0.0.6

func (req *Request) SetResponseContentLengthPtr(contentLengthPtr *int64) *Request

func (*Request) SetResponseErrorBody

func (req *Request) SetResponseErrorBody(value interface{}) *Request

func (*Request) SetSuccessStatusCode

func (req *Request) SetSuccessStatusCode(statusCodes ...int) *Request

func (*Request) SetTraceRequestBody

func (req *Request) SetTraceRequestBody(value bool) *Request

func (*Request) SetTraceResponseBody

func (req *Request) SetTraceResponseBody(value bool) *Request

type Response

type Response struct {
	Raw         *http.Response
	Error       error
	Body        interface{}
	ErrorBody   interface{}
	ForceJSON   bool
	ForceXML    bool
	BodyBytes   []byte
	BodyLimit   int64
	TraceBody   bool
	DoUnmarshal bool

	ContentLengthPtr *int64

	SuccessStatusCodes []int
}

func (*Response) ContentType

func (resp *Response) ContentType() string

func (*Response) HasEmptyBody

func (resp *Response) HasEmptyBody() bool

func (*Response) Header

func (resp *Response) Header() http.Header

func (*Response) StatusCode

func (resp *Response) StatusCode() int

func (*Response) WantsRawByteArray

func (resp *Response) WantsRawByteArray() bool

func (*Response) WantsReadCloser added in v0.0.4

func (resp *Response) WantsReadCloser() bool

type Trace

type Trace interface {
	// OnAfterRequest is called just after a request was executed.
	// It is called any time, even if the request/response was not
	// successful.
	OnAfterRequest(req *Request)

	// End is called with defer, just after the trace has been created.
	// It can be used to end/close a trace.
	End()
}

Trace is created for each new request.

type TraceMaker

type TraceMaker interface {
	// NewTrace is called just before a request is about to be executed
	// by the HTTP client. NewTrace is NOT called, if a request could not
	// be built, for example because the request body could be marshaled.
	NewTrace(req *Request) Trace
}

TraceMaker defines an interface for handling traces of HTTP requests. The interface is designed with Open Telemetry in mind. vrest creates a new trace for each request. A trace is only created, if the request could be built successfully.

A TraceMaker/Trace has full access to all Request data, but it should not modify anything. You can access the BodyBytes of the request and response if they are available. If the Request uses a Reader, BodyBytes will be nil.

Directories

Path Synopsis
examples module

Jump to

Keyboard shortcuts

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