snorlax

package module
v0.0.0-...-516ef26 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2020 License: MIT Imports: 13 Imported by: 2

README

Snorlax

Simple HTTP and REST client library written in Go

Build Status Go Report Card GoDoc License

Installation

To install snorlax, use go get:

go get github.com/nickcorin/snorlax

Import the snorlax package into your code:

package main

import "github.com/nickcorin/snorlax"

func main() {
	client := snorlax.DefaultClient
}

Usage

Using the DefaultClient.
// You can construct a DefaultClient.
client := snorlax.DefaultClient

// ...or you can use it without allocating a new Client.
res, err := snorlax.Get(context.Background(), "/example", nil)
if err != nil {
	log.Fatal(err)
}
Configuring the client.
// You can configure some attibutes when constructing the client by using `ClientOption`s.
client := snorlax.NewClient(snorlax.ClientOptions{
	BaseURL: "https://example.com",
})

// You can also configure the client after construction.
client.AddRequestHook(snorlax.WithHeader("X-Powered-By", "Snorlax"))

// You can also chain configuration functions.
client.SetProxyURL("https://proxy.example.com").SetHeader("X-Powered-By", "Snorlax")
Performing a simple request.
// Using the DefaultClient.
res, err := snorlax.Get(context.Background(), "/example", nil)
if err != nil {
	log.Fatal(err)
}

// Using a custom Client.
res, err := client.Get(context.Background(), "/example", nil)
if err != nil {
	log.Fatal(err)
}
Performing a request with query parameters.
params := make(url.Values)
params.Set("name", "Snorlax")
params.Set("number", 143")

res, err := client.Get(context.Background(), "/example", params)
if err != nil {
	log.Fatal(err)
}
Performing a request with a body.
payload := []byte("{\"name\": \"Snorlax\", \"number\": 143}")

res, err := client.Post(context.Background(), "/example", nil, bytes.NewBuffer(payload))
if err != nil {
	log.Fatal(err)
}
Performing a request with RequestHooks.
// You can set RequestHooks which run on every request.
client.AddRequestHook(snorlax.WithHeader("Content-Type", "application/json"))

// You can also set RequestHooks to run for single requests.
username, password := "testuser", "testpassword"

res, err := client.Get(context.Background(), "/example", nil, snorlax.WithBasicAuth(username, password))
if err != nil {
	log.Fatal(err)
}

// You can even define your own hooks!
func MyLoggerHook(c snorlax.Client, r *http.Request) {
	log.Printf("snorlax is sending a request to %s!\n", r.URL.Path)
}

client.AddRequestHook(MyLoggerHook)
Extracting JSON out of a response.
type Pokemon struct {
	Name 	string `json:"name"`
	Number 	int    `json:"number"`
}

res, err := client.Get(context.Background(), "/example", nil)
if err != nil {
	log.Fatal(err)
}

var pokemon Pokemon
if err = res.JSON(&pokemon); err != nil {
	log.Fatal(err)
}

Contributing

Please feel free to submit issues, fork the repositoy and send pull requests!

License

This project is licensed under the terms of the MIT license.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultClient = &client{
	opts: Defaults(),
}

DefaultClient is a Snorlax client configured with all of the default options.

Functions

This section is empty.

Types

type Client

type Client interface {
	// AddHeader appends a header value to the client to be sent in every
	// request. To replace the current existing header use SetHeader.
	AddHeader(key, value string) Client

	// AddRequestHook appends a RequestHook to the list of hooks which are to be
	// run just before the client sends a request. RequestHooks are executed in
	// the order they are added.
	AddRequestHook(hook RequestHook) Client

	// AddRequestHooks is a convenience function which calls AddRequestHook
	// multiple times.
	AddRequestHooks(hooks ...RequestHook) Client

	// Get performs a Get request. You can optionally configure the request
	// using RequestHooks, or by configuring the client if you need to configure
	// all requests.
	Delete(ctx context.Context, target string, query url.Values, body io.Reader,
		hooks ...RequestHook) (*Response, error)

	// Get performs a Get request. You can optionally configure the request
	// using RequestHooks, or by configuring the client if you need to configure
	// all requests.
	Get(ctx context.Context, target string, query url.Values,
		hooks ...RequestHook) (*Response, error)

	// Head performs a Head request. You can optionally configure the request
	// using RequestHooks, or by configuring the client if you need to configure
	// all requests.
	Head(ctx context.Context, target string, query url.Values,
		hooks ...RequestHook) (*Response, error)

	// Logger returns the client's internal logger.
	Logger() *logrus.Logger

	// Options performs a Options request. You can optionally configure the
	// request using RequestHooks, or by configuring the client if you need to
	// configure  all requests.
	Options(ctx context.Context, target string, query url.Values,
		hooks ...RequestHook) (*Response, error)

	// Post performs a Post request. You can optionally configure the request
	// using RequestHooks, or by configuring the client if you need to configure
	// all requests.
	Post(ctx context.Context, target string, query url.Values, body io.Reader,
		hooks ...RequestHook) (*Response, error)

	// Put performs a Put request. You can optionally configure the request
	// using RequestHooks, or by configuring the client if you need to configure
	// all requests.
	Put(ctx context.Context, target string, query url.Values, body io.Reader,
		hooks ...RequestHook) (*Response, error)

	// RemoveProxy removes any currently set proxy URL in the Client's
	// transport.
	RemoveProxy() Client

	// SetBaseURL sets a host URL inside the client which is prepended to all
	// request URLs performed by the Client.
	SetBaseURL(url string) Client

	// SetHeader sets a header value in the client to be sent in every request.
	// This will overwrite any exiting headers present associated with the same
	// key. To add headers to the key instead of replacing them use AddHeader.
	SetHeader(key, value string) Client

	// SetHTTPClient replaces the internal http.Client that Snorlax uses to
	// perform requests. Use this if you need finer control over the client's
	// internals.
	SetHTTPClient(c *http.Client) Client

	// SetLogLevel sets the amount of logs the client will produce. The lower
	// the level, the less logs will be written. By default, Snorlax uses the
	// lowest possible level - PanicLevel.
	SetLogLevel(level logrus.Level) Client

	// SetProxy sets the proxy URL in the clent's transport. If the URL fails
	// to parse, nothing is set. This function fails silently. If you need more
	// of a guarantee rather create your own http.Client with your proxy set and
	// use SetHTTPClient.
	SetProxy(url string) Client
}

Client defines a wrapper around an http.Client making it easier to send requests to RESTful APIs.

func NewClient

func NewClient(opts *ClientOptions) Client

NewClient constructs a new Client configured with the provided ClientOptions.

type ClientOptions

type ClientOptions struct {
	BaseURL     string
	WithMetrics bool
	// contains filtered or unexported fields
}

ClientOptions contains the configuration options for a Snorlax client.

func Defaults

func Defaults() *ClientOptions

Defaults returns a set of default ClientOptions.

type RequestHook

type RequestHook func(Client, *http.Request) error

RequestHook is a middleware function that can be applied to an HTTP request before it's sent.

func WithBasicAuth

func WithBasicAuth(username, password string) RequestHook

WithBasicAuth sets basic authentication on the request.

func WithHeader

func WithHeader(key, value string) RequestHook

WithHeader adds a the header key value pair to the request.

type Response

type Response struct {
	http.Response
}

Response is a type alias for http.Response.

func Delete

func Delete(ctx context.Context, target string, query url.Values,
	body io.Reader, hooks ...RequestHook) (*Response, error)

Delete performs a delete request using the DefaultClient. You can optionally configure the request using RequestHooks. If you need to configure every request then consider not using the DefaultClient.

func Get

func Get(ctx context.Context, target string, query url.Values,
	opts ...RequestHook) (*Response, error)

Get performs a get request using the DefaultClient. You can optionally configure the request using RequestHooks. If you need to configure every request then consider not using the DefaultClient.

func Head(ctx context.Context, target string, query url.Values,
	opts ...RequestHook) (*Response, error)

Head performs a head request using the DefaultClient. You can optionally configure the request using RequestHooks. If you need to configure every request then consider not using the DefaultClient.

func Options

func Options(ctx context.Context, target string, query url.Values,
	opts ...RequestHook) (*Response, error)

Options performs an options request using the DefaultClient. You can optionally configure the request using RequestHooks. If you need to configure every request then consider not using the DefaultClient.

func Post

func Post(ctx context.Context, target string, query url.Values,
	body io.Reader, opts ...RequestHook) (*Response, error)

Post performs a post request using the DefaultClient. You can optionally configure the request using RequestHooks. If you need to configure every request then consider not using the DefaultClient.

func Put

func Put(ctx context.Context, target string, query url.Values,
	body io.Reader, opts ...RequestHook) (*Response, error)

Post performs a post request using the DefaultClient. You can optionally configure the request using RequestHooks. If you need to configure every request then consider not using the DefaultClient.

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns whether the response code is within the 2XX range.

func (*Response) JSON

func (r *Response) JSON(out interface{}) error

JSON reads and unmarshals the response body into out.

func (*Response) RawBody

func (r *Response) RawBody() (io.Reader, error)

RawBody returns an io.Reader containing the data returned in the response body.

Jump to

Keyboard shortcuts

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