yarl

package module
v0.0.0-...-f39c695 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2019 License: MIT Imports: 20 Imported by: 0

README

yarl

GoDoc CircleCI

Yet Another http Request Library in golang. Because why not ?

Work In Progress. But apis in README should just work.

Install

go get -u -v github.com/inoc603/yarl

Usage

resp := yarl.Get("http://example.com").Do()

if resp.Error() == nil {
        fmt.Println(resp.StatusCode())
        // Get response body as a reader
        io.Copy(os.Stdout, resp.Body())
        // Get response as a string or bytes
        fmt.Println(resp.BodyString())
        fmt.Println(resp.BodyBytes())
}

// Marshal response body to a struct
var body struct {
        K string `json:"k"`
}

resp := yarl.Get("http://example.com").Do()

if resp.BodyMarshal(&body); err != nil {
        // Response body can still be used if marshalling failed
        fmt.Printf("error: %v; body: %s", err, resp.BodyString())
}
Setting headers
yarl.Get("http://github.com/inoc603").
        Header("k1", "v1").
        Headers(map[string]string{
                "k2": "v2",
        }).
        Headers(struct {
                K3 string `header:"k3"`
        }{"v3"})
Setting query
yarl.Get("http://github.com/inoc603").
        Query("k1", "v1").
        Queries(map[string]interface{}{
                "k2": "v2",
                "k3": 3,
        }).
        Queries(struct {
                K4 string `query:"k4"`
                K5 int    `query:"k5"`
        }{"v4", 5})
JSON body
// From any JSON-serializable variable
yarl.Post("http://github.com/inoc603").
        Body(&struct {
                K string `json:"k"`
        }{"value"})

yarl.Post("http://github.com/inoc603").
        Body(map[string]interface{}{
                "key": "value",
        })

yarl.Post("http://github.com/inoc603").
        Body([]int{1, 2, 3})

// From a string or bytes
yarl.Post("http://github.com/inoc603").
        Body(`{"key": { "nested": 1 }}`)

yarl.Post("http://github.com/inoc603").
        Body([]byte(`{"key": { "nested": 1 }}`))

// From a reader
f, _ := os.Open("req.json")
yarl.Post("http://github.com/inoc603").
        Body(f)


// Setting json field
yarl.Post("http://github.com/inoc603").
        Set("field_1", "a").
        Set("field_2", 1).
        Set("field_3", map[string]interface{}{
                "a": false,
        })
Multipart Body
yarl.Post("http://github.com/inoc603").
        Multipart().
        File("./file1.txt").
        File("./file2.txt", "field_name").
        FileFromReader(bytes.NewBuffer(content), "file3.txt", "field_name_2").
        Do()
Retry
yarl.Get("http://example.com").
        Retry(3, time.Second)
Redirect
// Set max redirect
yarl.Get("http://example.com").
        MaxRedirect(3)

// Custom redirec policy
yarl.Get("http://example.com").
        RedirectPolicy(func(req *http.Request, via []*http.Request) error {
                return http.ErrUseLastResponse
        })
Unix Socket
yarl.Get("http://whatever/v1.24/containers/json").
        UnixSocket("/var/run/docker.sock")
Proxy
yarl.Get("http://github.com/inoc603").
        Proxy("http://localhost:80").     // HTTP proxy
        Proxy("https://localhost:443").   // HTTPS proxy
        Proxy("socks5://localhost:1080")  // SOCKS5 proxy
Custom Transport
yarl.Get("http://github.com/inoc603").
        Transport(&http.Transport{})
Reuse Configurations

TODO: Make reusing reqeust thread-safe

v1 := yarl.New("http://example.com").
        BasePath("/api/v1")

// following calls will reuse v1
v1.Get("/example").Do()
v1.Post("/user/%d", 1).Body(body).Do()

// TODO

Documentation

Index

Constants

View Source
const (
	POST    = "POST"
	GET     = "GET"
	HEAD    = "HEAD"
	PUT     = "PUT"
	DELETE  = "DELETE"
	PATCH   = "PATCH"
	OPTIONS = "OPTIONS"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type RedirectPolicy

type RedirectPolicy func(req *http.Request, via []*http.Request) error

RedirectPolicy represents policy for handling redirections. It works like http.Client.CheckRedirect

type Request

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

func Delete

func Delete(url string) *Request

func Get

func Get(url string) *Request

func New

func New(url string) *Request

func Patch

func Patch(url string) *Request

func Post

func Post(url string) *Request

func Put

func Put(url string) *Request

func (*Request) BasePath

func (req *Request) BasePath(p string) *Request

BasePath sets a common base path for all requests from this instance

func (*Request) Body

func (req *Request) Body(v interface{}) *Request

Body sets the body to the given value. By default the body is in json.

func (*Request) ContentType

func (req *Request) ContentType(t string) *Request

func (*Request) Cookie

func (req *Request) Cookie(c *http.Cookie) *Request

func (*Request) Copy

func (req *Request) Copy() *Request

func (*Request) Delete

func (req *Request) Delete(url string, args ...interface{}) *Request

func (*Request) Do

func (req *Request) Do() *Response

Do makes the request and returns a reponse.

func (*Request) File

func (req *Request) File(path string, field ...string) *Request

File adds a file from the given path to multipart field, with optional custom filedname. Calling this will automatically sets the body type to multipart. It will be considered an error if the body is of another type and not empty.

func (*Request) FileFromReader

func (req *Request) FileFromReader(r io.Reader, name string, field string) *Request

FileFromReader adds a file to the multipart from the given reader. Its behavior is the same as File. TODO: Maybe an io.ReadCloser?

func (*Request) Get

func (req *Request) Get(url string, args ...interface{}) *Request

func (*Request) Header

func (req *Request) Header(k, v string) *Request

Header add the given key value pair to request header.

func (*Request) Headers

func (req *Request) Headers(v interface{}) *Request

Headers

func (*Request) Host

func (req *Request) Host(h string) *Request

Host sets a common host for all requests from this instance

func (*Request) JSON

func (req *Request) JSON() *Request

JSON explicitly sets the body type to json.

func (*Request) MaxCode

func (req *Request) MaxCode(code int) *Request

MaxCode tells the client the validate the request with the given max status code. If status code of a response is larger than it, the response is considered to be failed.

func (*Request) MaxRedirect

func (req *Request) MaxRedirect(max int) *Request

MaxRedirect sets the maxium redirects of the request

func (*Request) Method

func (req *Request) Method(method string) *Request

func (*Request) Multipart

func (req *Request) Multipart() *Request

Multipart explicitly sets the body type to multipart

func (*Request) Patch

func (req *Request) Patch(url string, args ...interface{}) *Request

func (*Request) Post

func (req *Request) Post(url string, args ...interface{}) *Request

func (*Request) Proxy

func (req *Request) Proxy(proxyURL string) *Request

Proxy sets the proxy used to perform the request. It supports http/https, and socks5 proxy.

func (*Request) Put

func (req *Request) Put(url string, args ...interface{}) *Request

func (*Request) Queries

func (req *Request) Queries(v interface{}) *Request

Queries add the given values to the query

func (*Request) Query

func (req *Request) Query(k, v string) *Request

Query sets a query item.

func (*Request) RedirectPolicy

func (req *Request) RedirectPolicy(p RedirectPolicy) *Request

RedirectPolicy adds a custom redirect policy to the request.

func (*Request) Retry

func (req *Request) Retry(attempts int, interval time.Duration) *Request

Retry sets the retry policy for the request

func (*Request) Set

func (req *Request) Set(k string, v interface{}) *Request

func (*Request) Timeout

func (req *Request) Timeout(t time.Duration) *Request

Timeout sets timeout on the the http client

func (*Request) Transport

func (req *Request) Transport(r http.RoundTripper) *Request

Transport sets a custom transport for the http client. If the transport is not a *http.Transport, no further customization can be done to the transport

func (*Request) URL

func (req *Request) URL(rawURL string) *Request

URL sets the request url.

func (*Request) UnixSocket

func (req *Request) UnixSocket(path string) *Request

UnixSocket sets the request to be sent to a unix socket.

func (*Request) Validator

func (req *Request) Validator(v ResponseValidator) *Request

Validator sets a custom response validator

func (*Request) WithContext

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

WithContext sets a context for the request. Context are valid through retries and redirects.

type Response

type Response struct {
	// Raw is the underlying http.Response
	Raw *http.Response

	// FailedAttempts keeps all previous failed attempts through retries
	FailedAttempts []*Response
	// contains filtered or unexported fields
}

func (*Response) Body

func (resp *Response) Body() io.Reader

Body returns the body as io.Reader

func (*Response) BodyBytes

func (resp *Response) BodyBytes() ([]byte, error)

BodyBytes returns the body as bytes

func (*Response) BodyJSON

func (resp *Response) BodyJSON(v interface{}) error

BodyJSON marshalls the body content to the given interface as JSON, regardless of the Content-Type header in the response.

func (*Response) BodyMarshal

func (resp *Response) BodyMarshal(v interface{}) error

BodyMarshal marshalls the body content to the given interface according to the content type.

func (*Response) BodyString

func (resp *Response) BodyString() (string, error)

BodyString returns the body as string

func (*Response) Error

func (resp *Response) Error() error

func (*Response) StatusCode

func (resp *Response) StatusCode() int

type ResponseValidator

type ResponseValidator func(*Response) bool

ResponseValidator tells whether the given response is valid.

Directories

Path Synopsis
internal
assert
package assert provides simple testig wrapper around testify/assert
package assert provides simple testig wrapper around testify/assert

Jump to

Keyboard shortcuts

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