request

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

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

Go to latest
Published: Nov 15, 2017 License: MIT Imports: 18 Imported by: 0

README

request

Build Status Coverage Status GoDoc License

A concise HTTP request client for Go. It provides elegant and chainalbe API to make you request with happiness.

Installation

go get -u github.com/DavidCai1993/request

Documentation

API documentation can be found here: https://godoc.org/github.com/DavidCai1993/request

Usage

Example:
json, err = request.
  Post("http://mysite.com").
  Timeout(30*time.Second).
  Send(map[string]string{"name": "David"}).
  Set("X-HEADER-KEY", "foo").
  Accept("application/json").
  JSON()
type MyResult struct {
  Code  int                    `json:"code"`
  Error string                 `json:"error"`
  Data  map[string]interface{} `json:"data"`
}

json, err = request.
  Get("http://mysite.com").
  JSON(new(MyResult))
GET:
res, err = request.
  Get("http://mysite.com").
  End()
text, err = request.
  Get("http://mysite.com/get").
  Cookie(&http.Cookie{Name: "name", Value: "David"}).
  Text()
Basic Authentication
json, err = request.
  Get("http://mysite.com/somebooks").
  Auth("name", "passwd").
  JSON()
Form with Attachments
json, err = request.
  Post("http://mysite.com/form").
  Field(url.Values{"key": []string{"value1"}}).
  Attach("test.md", "./README.md", "README.md").
  JSON()
Proxy
json, err = request.
  Get("http://mysite.com/somebooks").
  Proxy("http://myproxy.com:8080").
  JSON()
Convert to http.Request instance
req, err = request.
  Post("http://mysite.com/form").
  Auth("name", "passwd").
  Req()

Documentation

Overview

Example
package main

import (
	"time"

	"github.com/DavidCai1993/request"
)

var (
	err  error
	res  *request.Response
	json interface{}
)

func main() {
	res, err = request.
		Get("http://mysite.com").
		End()

	// json has the type *simplejson.Json
	json, err = request.
		Post("http://mysite.com").
		Timeout(30*time.Second).
		Send(map[string]string{"name": "David"}).
		Set("X-HEADER-KEY", "foo").
		Accept("application/json").
		JSON()
}
Output:

Index

Examples

Constants

View Source
const Version = "1.6.0"

Version is this package's version number.

Variables

View Source
var (
	ErrNotPOST        = errors.New("request: method is not POST when using form")
	ErrLackURL        = errors.New("request: request lacks URL")
	ErrLackMethod     = errors.New("request: request lacks method")
	ErrBodyAlreadySet = errors.New("request: request body has already been set")
	ErrStatusNotOk    = errors.New("request: status code is not ok (>= 400)")
)

Errors used by this package.

Functions

func GetIndex

func GetIndex(v interface{}, index int) interface{}

GetIndex searches value from []interface{} by index

func GetPath

func GetPath(v interface{}, branch ...string) interface{}

GetPath searches value from map[string]interface{} by path

Types

type Client

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

Client is a HTTP client which provides usable and chainable methods.

func Delete

func Delete(URL string) *Client

Delete equals New().Delete(URL) to let you start a DELETE request conveniently.

func Get

func Get(URL string) *Client

Get equals New().Get(URL) to let you start a GET request conveniently.

Example
package main

import (
	"github.com/DavidCai1993/request"
)

var (
	err error

	json interface{}
)

func main() {
	json, err = request.
		Get("http://mysite.com").
		JSON()
}
Output:

func New

func New() *Client

New returns a new instance of Client.

func Post

func Post(URL string) *Client

Post equals New().Post(URL) to let you start a POST request conveniently.

Example
package main

import (
	"github.com/DavidCai1993/request"
)

var (
	err error

	json interface{}
)

func main() {
	json, err = request.
		Post("http://mysite.com").
		Send(map[string]string{"name": "David"}).
		Set("X-HEADER-KEY", "foo").
		Accept("application/json").
		JSON()
}
Output:

func Put

func Put(URL string) *Client

Put equals New().Put(URL) to let you start a PUT request conveniently.

func (*Client) Accept

func (c *Client) Accept(t string) *Client

Accept sets the "Accept" request header to the given value. Some shorthands are supported:

"html": "text/html" "json": "application/json" "xml": "application/xml" "text": "text/plain" "urlencoded": "application/x-www-form-urlencoded" "form": "application/x-www-form-urlencoded" "form-data": "application/x-www-form-urlencoded" "multipart": "multipart/form-data"

So you can just call .Accept("json") to set the "Accept" header to "application/json".

func (*Client) Add

func (c *Client) Add(key, value string) *Client

Add adds the key, value pair to the request header.It appends to any existing values associated with key.

func (*Client) Attach

func (c *Client) Attach(fieldname, path, filename string) *Client

Attach adds the attachment file to the form. Once the attachment was set, the "Content-Type" will be set to "multipart/form-data; boundary=xxx" automatically.

Example
package main

import (
	"net/url"

	"github.com/DavidCai1993/request"
)

var (
	err error

	json interface{}
)

func main() {
	json, err = request.
		Post("http://mysite.com/readme").
		Field(url.Values{"key": []string{"value1"}}).
		Attach("test.md", "./README.md", "README.md").
		JSON()
}
Output:

func (*Client) Auth

func (c *Client) Auth(name, password string) *Client

Auth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

Example
package main

import (
	"github.com/DavidCai1993/request"
)

var (
	err error

	json interface{}
)

func main() {
	json, err = request.
		Get("http://mysite.com/somebooks").
		Auth("name", "passwd").
		JSON()
}
Output:

func (*Client) Cookie

func (c *Client) Cookie(cookie *http.Cookie) *Client

Cookie adds the cookie to the request.

Example
package main

import (
	"net/http"

	"github.com/DavidCai1993/request"
)

var (
	text string
	err  error
)

func main() {
	text, err = request.
		Get("http://mysite.com/get").
		Cookie(&http.Cookie{Name: "name", Value: "David"}).
		Text()
}
Output:

func (*Client) CookieJar

func (c *Client) CookieJar(jar http.CookieJar) *Client

CookieJar adds all cookies in the cookie jar to the request.

func (*Client) Delete

func (c *Client) Delete(URL string) *Client

Delete equals To("DELETE", URL) .

func (*Client) End

func (c *Client) End() (*Response, error)

End sends the HTTP request and returns the HTTP reponse.

An error is returned if caused by client policy (such as timeout), or failure to speak HTTP (such as a network connectivity problem), or generated by former chained methods. A non-2xx status code doesn't cause an error.

func (*Client) Field

func (c *Client) Field(vals url.Values) *Client

Field sets the field values like form fields in HTML. Once it was set, the "Content-Type" header of the request will be automatically set to "application/x-www-form-urlencoded".

func (*Client) Get

func (c *Client) Get(URL string) *Client

Get equals To("GET", URL) .

func (*Client) Header

func (c *Client) Header(h http.Header) *Client

Header sets all key, value pairs in h to the request header, it replaces any existing values associated with key.

func (*Client) JSON

func (c *Client) JSON(v ...interface{}) (interface{}, error)

JSON sends the HTTP request and returns the reponse body with JSON format.

func (*Client) Post

func (c *Client) Post(URL string) *Client

Post equals To("POST", URL) .

func (*Client) Proxy

func (c *Client) Proxy(addr string) *Client

Proxy sets the address of the proxy which used by the request.

Example
package main

import (
	"github.com/DavidCai1993/request"
)

var (
	err error

	json interface{}
)

func main() {
	json, err = request.
		Get("http://mysite.com/somebooks").
		Proxy("http://myproxy.com:8080").
		JSON()
}
Output:

func (*Client) Put

func (c *Client) Put(URL string) *Client

Put equals To("PUT", URL) .

func (*Client) Query

func (c *Client) Query(vals url.Values) *Client

Query adds the the given value to request's URL query-string.

func (*Client) Redirects

func (c *Client) Redirects(count int) *Client

Redirects sets the max redirects count for the request. If not set, request will use its default policy, which is to stop after 10 consecutive requests.

func (*Client) Req

func (c *Client) Req() (*http.Request, error)

Req returns the representing http.Request instance of this request. It is often used in wirting tests.

func (*Client) Send

func (c *Client) Send(body interface{}) *Client

Send sends the body in JSON format, body can be anything which can be Marshaled or just Marshaled JSON string.

func (*Client) Set

func (c *Client) Set(key, value string) *Client

Set sets the request header entries associated with key to the single element value. It replaces any existing values associated with key.

func (*Client) Text

func (c *Client) Text() (string, error)

Text sends the HTTP request and returns the reponse body with text format.

func (*Client) Timeout

func (c *Client) Timeout(timeout time.Duration) *Client

Timeout specifies a time limit for the request. The timeout includes connection time, any redirects, and reading the response body. The timer remains running after Get, Head, Post, or End return and will interrupt reading of the response body.

func (*Client) To

func (c *Client) To(method string, URL string) *Client

To defines the method and URL of the request.

func (*Client) Type

func (c *Client) Type(t string) *Client

Type sets the "Content-Type" request header to the given value. Some shorthands are supported:

"html": "text/html" "json": "application/json" "xml": "application/xml" "text": "text/plain" "urlencoded": "application/x-www-form-urlencoded" "form": "application/x-www-form-urlencoded" "form-data": "application/x-www-form-urlencoded" "multipart": "multipart/form-data"

So you can just call .Type("html") to set the "Content-Type" header to "text/html".

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

Response represents the response from a HTTP request.

func (*Response) Content

func (r *Response) Content() ([]byte, error)

Content returns the content of the response body, it will handle the compression.

func (*Response) JSON

func (r *Response) JSON(v ...interface{}) (interface{}, error)

JSON returns the reponse body with JSON format.

func (*Response) OK

func (r *Response) OK() bool

OK returns whether the reponse status code is less than 400.

func (*Response) Raw

func (r *Response) Raw() ([]byte, error)

Raw returns the raw bytes body of the response.

func (*Response) Reason

func (r *Response) Reason() string

Reason returns the status text of the response status code.

func (*Response) Text

func (r *Response) Text() (string, error)

Text returns the reponse body with text format.

func (*Response) URL

func (r *Response) URL() (*url.URL, error)

URL returns url of the final request.

Jump to

Keyboard shortcuts

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