rclient

package module
v0.0.0-...-00dfcee Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2019 License: MIT Imports: 5 Imported by: 12

README

RClient

MIT License Go Report Card Go Doc

Getting Started

Checkout the Examples folder for some working examples. The following snippet shows RClient interacting with Github's API:

package main

import (
        "github.com/zpatrick/rclient"
        "log"
)

type Repository struct {
        Name        string `json:"name"`
}

func main() {
        client := rclient.NewRestClient("https://api.github.com")

        var repos []Repository
        if err := client.Get("/users/zpatrick/repos", &repos); err != nil {
                log.Fatal(err)
        }

        log.Println(repos)
}

Request Options

Requests can be configured using a Request Option. A RequestOption is simply a function that manipulates an http.Request. You can create request options like so:

setProto := func(req *http.Request) error {
    req.Proto = "HTTP/1.0"
    return nil
}

client.Get("/path", &v, setProto)

The built-in request options are described below.

Header / Headers

The Header() and Headers() options add header(s) to a *http.Request.

// add a single header
client.Get("/path", &v, rclient.Header("name", "val"))

// add multiple headers
client.Get("/path", &v, rclient.Header("name1", "val1"), rclient.Header("name2", "val2"))
client.Get("/path", &v, rclient.Headers(map[string]string{"name1": "val1", "name2":"val2"}))
Basic Auth

The BasicAuth() option adds basic auth to a *http.Request.

client.Get("/path", &v, rclient.BasicAuth("user", "pass"))
Query

The Query() options adds a query to a *http.Request.

query := url.Values{}
query.Add("name", "John")
query.Add("age", "35")

client.Get("/path", &v, rclient.Query(query))

NOTE: This can also be accomplished by adding the raw query to the path argument

client.Get("/path?name=John&age=35", &v)

Client Configuration

The RestClient can be configured using the Client Options described below.

Doer

The Doer() option sets the RequestDoer field on the RestClient. This is the http.DefaultClient by default, and it can be set to anything that satisfies the RequestDoer interface.

client, err := rclient.NewRestClient("https://api.github.com", rclient.Doer(&http.Client{}))
Request Options

The RequestOptions() option sets the RequestOptions field on the RestClient. This will manipulate each request made by the RestClient. This can be any of the options described in the Request Options section. A typical use-case would be adding headers for each request.

options := []rclient.RequestOption{
    rclient.Header("name", "John Doe").
    rclient.Header("token", "abc123"),
}

client, err := rclient.NewRestClient("https://api.github.com", rclient.RequestOptions(options...))
Builder

The Builder() option sets the RequestBuilder field on the RestClient. This field is responsible for building *http.Request objects. This is the BuildJSONRequest function by default, and it can be set to any RequestBuilder function.

builder := func(method, url string, body interface{}, options ...RequestOption) (*http.Request, error){
    req, _ := http.NewRequest(method, url, nil)
    for _, option := range options {
		if err := option(req); err != nil {
			return nil, err
		}
	}
	
    return nil, errors.New("I forgot to add a body to the request!")
}

client, err := rclient.NewRestClient("https://api.github.com", rclient.Builder(builder))
Reader

The Reader() option sets the ResponseReader field on the RestClient. This field is responsible for reading *http.Response objects. This is the ReadJSONResponse function by default, and it can be set to any ResponseReader function.

reader := func(resp *http.Response, v interface{}) error{
    defer resp.Body.Close()
    return json.NewDecoder(resp.Body).Decode(v)
}

client, err := rclient.NewRestClient("https://api.github.com", rclient.Reader(reader))

License

This work is published under the MIT license.

Please see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildJSONRequest

func BuildJSONRequest(method, url string, body interface{}, options ...RequestOption) (*http.Request, error)

BuildJSONRequest creates a new *http.Request with the specified method, url and body in JSON format.

func ReadJSONResponse

func ReadJSONResponse(resp *http.Response, v interface{}) error

ReadJSONResponse attempts to marshal the response body into v if and only if the response StatusCode is in the 200 range. Otherwise, an error is thrown. It assumes the response body is in JSON format.

Types

type ClientOption

type ClientOption func(client *RestClient)

A ClientOption configures a *RestClient.

func Builder

func Builder(builder RequestBuilder) ClientOption

Builder sets the RequestBuilder field of a RestClient.

func Doer

func Doer(doer RequestDoer) ClientOption

Doer sets the RequestDoer field of a RestClient.

func Reader

func Reader(reader ResponseReader) ClientOption

Reader sets the ResponseReader field of a RestClient.

func RequestOptions

func RequestOptions(options ...RequestOption) ClientOption

RequestOptions sets the RequestOptions field of a RestClient.

type RequestBuilder

type RequestBuilder func(method, url string, body interface{}, options ...RequestOption) (*http.Request, error)

A RequestBuilder creates a *http.Request from the given parameters. It is important that each option gets added to the generated request:

req, _ := http.NewRequest(...)
for _, option := range options
    if err := option(req); err != nil {
        return nil, err
    }
}

type RequestDoer

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

A RequestDoer sends a *http.Request and returns a *http.Response.

type RequestDoerFunc

type RequestDoerFunc func(*http.Request) (*http.Response, error)

A RequestDoerFunc is a function that implements the RequestDoer interface.

func (RequestDoerFunc) Do

func (d RequestDoerFunc) Do(req *http.Request) (*http.Response, error)

Do executes the RequestDoerFunc.

type RequestOption

type RequestOption func(req *http.Request) error

A RequestOption configures a *http.Request.

func BasicAuth

func BasicAuth(user, pass string) RequestOption

BasicAuth adds the specified username and password as basic auth to a request.

func Header(name, val string) RequestOption

Header adds the specified name and value as a header to a request.

func Headers

func Headers(headers map[string]string) RequestOption

Headers adds the specified names and values as headers to a request

func Query

func Query(query url.Values) RequestOption

Query adds the specified query to a request.

type ResponseError

type ResponseError struct {
	Response *http.Response
	Message  string
}

func NewResponseError

func NewResponseError(resp *http.Response, message string) *ResponseError

func NewResponseErrorf

func NewResponseErrorf(resp *http.Response, format string, tokens ...interface{}) *ResponseError

func (*ResponseError) Error

func (e *ResponseError) Error() string

type ResponseReader

type ResponseReader func(resp *http.Response, v interface{}) error

A ResponseReader attempts to read a *http.Response into v.

type RestClient

type RestClient struct {
	Host           string
	RequestBuilder RequestBuilder
	RequestDoer    RequestDoer
	ResponseReader ResponseReader
	RequestOptions []RequestOption
}

RestClient builds, executes, and reads http requests/responses.

func NewRestClient

func NewRestClient(host string, options ...ClientOption) *RestClient

NewRestClient returns a new RestClient with all of the default fields. Any of the default fields can be changed with the options param.

func (*RestClient) Delete

func (r *RestClient) Delete(path string, body, v interface{}, options ...RequestOption) error

Delete passes its params to RestClient.Do() with the "DELETE" method.

func (*RestClient) Do

func (r *RestClient) Do(method, path string, body, v interface{}, options ...RequestOption) error

Do orchestrates building, performing, and reading http requests and responses.

func (*RestClient) Get

func (r *RestClient) Get(path string, v interface{}, options ...RequestOption) error

Get passes its params to RestClient.Do() with the "GET" method.

func (*RestClient) Patch

func (r *RestClient) Patch(path string, body, v interface{}, options ...RequestOption) error

Patch passes its params to RestClient.Do() with the "PATCH" method.

func (*RestClient) Post

func (r *RestClient) Post(path string, body, v interface{}, options ...RequestOption) error

Post passes its params to RestClient.Do() with the "POST" method.

func (*RestClient) Put

func (r *RestClient) Put(path string, body, v interface{}, options ...RequestOption) error

Put passes its params to RestClient.Do() with the "PUT" method.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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