yahc

package module
v0.0.0-...-8b704a3 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2018 License: MIT Imports: 9 Imported by: 0

README

Yet another HTTP client (yahc)

yach is a very simple opinionated http client, that takes most of the decisions out of the hands of the developer, and tries to figure out what is actually supposed to be going on.

yach comes with build in support for interfacing with REST endpoints, but can very easily be extended. In fact the standard json support is an extension build into the library.

Installation

go get github.com/zlepper/yahc

Godoc: https://godoc.org/github.com/zlepper/yahc

Examples

Here are some basic examples of how this library can be used.

Getting a resource
package main

import "github.com/zlepper/yahc"

type Post struct {
	UserID int    `json:"userId"`
	ID     int    `json:"id"`
	Title  string `json:"title"`
	Body   string `json:"body"`
}

func main() {
	out := make([]Post, 0)
	err := yahc.Get("https://jsonplaceholder.typicode.com/posts", yahc.NoOptions, &out)
	// Response is now in 'out' if the request didn't fail
}
Posting a resource
package main

import "github.com/zlepper/yahc"

type Post struct {
	UserID int    `json:"userId"`
	ID     int    `json:"id"`
	Title  string `json:"title"`
	Body   string `json:"body"`
}

func main() {
	newPost := Post{UserID:1,Title:"foo",Body:"The cake is a lie"}
	out := Post{}
	err := yahc.Post("https://jsonplaceholder.typicode.com/posts", yahc.NoOptions, newPost, &out)
	// Response is now in 'out' if the request didn't fail
}

Same pattern follows for PUT and DELETE

Advanced usage

Advanced usage is for when you are not just working with json, or might require a custom client

Custom client

A new client can be created by doing yahc.NewClient(&http.Client{}). Example use case for this adding a cookie-jar to the client to work with stateful apis

package main

import (
    "net/http"
    "net/http/cookiejar"
    "github.com/zlepper/yahc"
)

func main() {
    cookieJar, _ := cookiejar.New(nil)
    
    httpClient := &http.Client{
        Jar: cookieJar,
    }
    
    client := yahc.NewClient(httpClient)
}
Custom parses

yahc attempts to automatically parse your request and response into something that can be send to servers. All these parses can be changed, and additional ones registered to allow for working with more types of content. By default only a JSON parser is provided.

To register a custom parser, implement the

// A request parser will take to the request body struct, and turn it into
// a byte array that can be passed along to the actual request
type RequestParser interface {
	// Should convert the given argument into a byte array
	Convert(v interface{}) ([]byte, error)
}

or

// A ResponseParser should convert a response body into an object
type ResponseParser interface {
	// Should convert the r into v
	// Closing the reader is handled by yahc
	Convert(r io.Reader, v interface{}) error
}

depending on your use-case, and register them with RegisterRequestParser or RegisterResponseParser. A parser can be registered for multiple content types.

For an example, check the json-parser.go file, which is what handles the build in json parser.

Documentation

Index

Constants

View Source
const ApplicationJsonContentType = "application/json"
View Source
const ContentType = "Content-Type"

Variables

View Source
var (
	// A precreated client. Uses the http.Default client
	// All direct yahc.Get/Post/Put/Delete/Patch methods uses this
	// client.
	//
	// If another client should be used instead, request a custom
	// client instead using yahc.NewClient
	DefaultClient = NewClient(http.DefaultClient)

	// A default set of options
	// Will treat everything as json
	NoOptions = RequestOptions{
		Headers: HeadersFromMap(map[string]string{ContentType: ApplicationJsonContentType}),
	}
)

Functions

func ConvertRequestBody

func ConvertRequestBody(contentType string, body interface{}) (data []byte, err error)

Convert the body into bytes Will attempt to convert into the requested content type If no matching parser is registered, will return an error

func Delete

func Delete(url string, options RequestOptions, v interface{}) error

Does a delete request using the default client

func Get

func Get(url string, options RequestOptions, v interface{}) error

Does a GET request using the default client

func ParseResponse

func ParseResponse(contentType string, body io.Reader, v interface{}) error

Parses the response body into the v object v should be a pointer

func Post

func Post(url string, options RequestOptions, body, v interface{}) error

Does a POST request using the default client

func Put

func Put(url string, options RequestOptions, body, v interface{}) error

Does a PUT request using the default client

func RegisterRequestParser

func RegisterRequestParser(contentType string, parser RequestParser)

Registers a new parser for the given contentType If a parser is already registered, it's overwritten

func RegisterResponseParser

func RegisterResponseParser(contentType string, parser ResponseParser)

Registers a new parser for the given content type If a parser is already registered for the content type, it is overwritten

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

A client that can interact with external services

func NewClient

func NewClient(inner *http.Client) *Client

Gets a new client, based on the given client use this if you want provide e.g. a cookie jar for interacting with stateful services

func (*Client) Delete

func (c *Client) Delete(url string, options RequestOptions, v interface{}) error

Does a delete to the given resource

func (*Client) Get

func (c *Client) Get(url string, options RequestOptions, v interface{}) error

Does a get request to the given resource v should be a pointer to a struct that should be filled with values

func (*Client) Post

func (c *Client) Post(url string, options RequestOptions, body interface{}, v interface{}) error

Does a post request to the given resource Body of the struct that should be send to the resource v if a pointer to an output, in case a response is expected

func (*Client) Put

func (c *Client) Put(url string, options RequestOptions, body interface{}, v interface{}) error

Does a put request to the given resource

type Header map[string][]string

Headers to be passed along to the http request

func HeadersFromMap

func HeadersFromMap(m map[string]string) Header

Creates a new header object based on the given map

func (Header) Add

func (h Header) Add(key, value string)

Adds a new header

func (Header) Del

func (h Header) Del(key string)

Removes the given key from the headers

func (Header) Get

func (h Header) Get(key string) string

Gets the given header

func (Header) Set

func (h Header) Set(key, value string)

Overwrites the given header, and sets it to the provided value

type JsonRequestParser

type JsonRequestParser struct {
}

func (JsonRequestParser) Convert

func (JsonRequestParser) Convert(v interface{}) ([]byte, error)

type JsonResponseParser

type JsonResponseParser struct {
}

func (JsonResponseParser) Convert

func (JsonResponseParser) Convert(r io.Reader, v interface{}) error

type QueryParam

type QueryParam map[string][]string

Query params to send a long with requests These will be added to the query params given in the url string

func (QueryParam) Add

func (p QueryParam) Add(key, value string)

Adds a value to the given parameter

func (QueryParam) Del

func (p QueryParam) Del(key string)

Removes the given parameter

func (QueryParam) Set

func (p QueryParam) Set(key, value string)

Overwrites the given parameter

type RequestOptions

type RequestOptions struct {
	// Headers to attach to the request
	Headers Header
	// Query parameters to add to the request
	QueryParams QueryParam
}

Headers and query parameters for the request

type RequestParser

type RequestParser interface {
	// Should convert the given argument into a byte array
	Convert(v interface{}) ([]byte, error)
}

A request parser will take to the request body struct, and turn it into a byte array that can be passed along to the actual request

type ResponseParser

type ResponseParser interface {
	// Should convert the r into v
	// Closing the reader is handled by yahc
	Convert(r io.Reader, v interface{}) error
}

A ResponseParser should convert a response body into an object

Jump to

Keyboard shortcuts

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