request: github.com/mozillazg/request Index | Examples | Files

package request

import "github.com/mozillazg/request"

Package request is a developer-friendly HTTP request library for Gopher.

GET Request:

c := &http.Client{}
req := request.NewRequest(c)
resp, err := req.Get("http://httpbin.org/get")
defer resp.Body.Close()  // **Don't forget close the response body**
j, err := resp.Json()

POST Request:

req = request.NewRequest(c)
req.Data = map[string]string{
	"key": "value",
	"a":   "123",
}
resp, err := req.Post("http://httpbin.org/post")

Custom Cookies:

req = request.NewRequest(c)
req.Cookies = map[string]string{
	"key": "value",
	"a":   "123",
}
resp, err := req.Get("http://httpbin.org/cookies")

Custom Headers:

req = request.NewRequest(c)
req.Headers = map[string]string{
	"Accept-Encoding": "gzip,deflate,sdch",
	"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
}
resp, err := req.Get("http://httpbin.org/get")

Upload Files:

req = request.NewRequest(c)
f, err := os.Open("test.txt")
req.Files = []request.FileField{
	request.FileField{"file", "test.txt", f},
}
resp, err := req.Post("http://httpbin.org/post")

Json Body:

req = request.NewRequest(c)
req.Json = map[string]string{
	"a": "A",
	"b": "B",
}
resp, err := req.Post("http://httpbin.org/post")
req.Json = []int{1, 2, 3}
resp, err = req.Post("http://httpbin.org/post")

others body:

req = request.NewRequest(c)
// not set Content-Type
req.Body = strings.NewReader("<xml><a>abc</a></xml")
resp, err := req.Post("http://httpbin.org/post")

// form
req = request.NewRequest(c)
req.Body = strings.NewReader("a=1&b=2")
req.Headers = map[string]string{
	"Content-Type": request.DefaultContentType,
}
resp, err = req.Post("http://httpbin.org/post")

Proxy:

req = request.NewRequest(c)
req.Proxy = "http://127.0.0.1:8080"
// req.Proxy = "https://127.0.0.1:8080"
// req.Proxy = "socks5://127.0.0.1:57341"
resp, err := req.Get("http://httpbin.org/get")

HTTP Basic Authentication:

req = request.NewRequest(c)
req.BasicAuth = request.BasicAuth{"user", "passwd"}
resp, err := req.Get("http://httpbin.org/basic-auth/user/passwd")

Need more control?

You can setup req.Client(you know, it's an &http.Client), for example: set timeout

timeout := time.Duration(1 * time.Second)
req.Client.Timeout = timeout
req.Get("http://httpbin.org/get")

Index

Examples

Package Files

cookies.go doc.go form.go headers.go hook.go proxy_go12.go redirect.go request.go response.go

Constants

const Version = "0.8.0"

Version export version

Variables

var DefaultClient = new(http.Client)

DefaultClient for NewArgs and NewRequest

var DefaultContentType = "application/x-www-form-urlencoded; charset=utf-8"

DefaultContentType define default Content-Type Header for form body

var DefaultHeaders = map[string]string{
    "Connection":      "keep-alive",
    "Accept-Encoding": "gzip, deflate",
    "Accept":          "*/*",
    "User-Agent":      DefaultUserAgent,
}

DefaultHeaders define default headers

var DefaultJsonType = "application/json; charset=utf-8"

DefaultJsonType define default Content-Type Header for json body

var DefaultRedirectLimit = 10

DefaultRedirectLimit define max redirect counts

var DefaultUserAgent = "go-request/" + Version

DefaultUserAgent define default User-Agent header

var ErrMaxRedirect = errors.New("Exceeded max redirects")

ErrMaxRedirect when redirect times great than DefaultRedirectLimit will return this error

type Args Uses

type Args struct {
    Client    *http.Client
    Headers   map[string]string
    Cookies   map[string]string
    Data      map[string]string
    Params    map[string]string
    Files     []FileField
    Json      interface{}
    Proxy     string
    BasicAuth BasicAuth
    Body      io.Reader
    Hooks     []Hook
}

Args for request args

func NewArgs Uses

func NewArgs(c *http.Client) *Args

NewArgs return a *Args

type BasicAuth Uses

type BasicAuth struct {
    Username string
    Password string
}

BasicAuth struct for http basic auth

type FileField Uses

type FileField struct {
    FieldName string
    FileName  string
    File      io.Reader
}

FileField struct for upload file

type Hook Uses

type Hook interface {
    // call BeforeRequest before send http request,
    // if resp != nil or err != nil
    // use this resp and err, no longer send http request.
    BeforeRequest(req *http.Request) (resp *http.Response, err error)
    // call AfterRequest after got response
    // if newResp != nil or newErr != nil
    // use the new NewResp instead of origin response.
    AfterRequest(req *http.Request, resp *http.Response, err error) (newResp *http.Response, newErr error)
}

Hook ...

type Request Uses

type Request struct {
    *Args
}

Request is alias Args

func NewRequest Uses

func NewRequest(c *http.Client) *Request

NewRequest return a *Request

func (*Request) Delete Uses

func (req *Request) Delete(url interface{}) (resp *Response, err error)

Delete issues a DELETE to the specified URL.

url can be string or *url.URL or ur.URL

func (*Request) Get Uses

func (req *Request) Get(url interface{}) (resp *Response, err error)

Get issues a GET to the specified URL.

url can be string or *url.URL or ur.URL

Code:

c := new(http.Client)
req := request.NewRequest(c)
url := "http://httpbin.org/get"
resp, _ := req.Get(url)
d, _ := resp.Json()
defer resp.Body.Close()
fmt.Println(resp.Ok())
fmt.Println(d.Get("url").MustString())

Output:

true
http://httpbin.org/get

Code:

c := new(http.Client)
req := request.NewRequest(c)
req.Cookies = map[string]string{
    "name": "value",
    "foo":  "bar",
}
url := "http://httpbin.org/cookies"
resp, _ := req.Get(url)
defer resp.Body.Close()

Code:

c := new(http.Client)
req := request.NewRequest(c)
req.Headers = map[string]string{
    "X-Abc":      "abc",
    "User-Agent": "go-request-test",
}
url := "http://httpbin.org/get"
resp, _ := req.Get(url)
d, _ := resp.Json()
defer resp.Body.Close()
fmt.Println(d.Get("headers").Get("User-Agent").MustString())
fmt.Println(d.Get("headers").Get("X-Abc").MustString())

Output:

go-request-test
abc

Code:

c := new(http.Client)
req := request.NewRequest(c)
req.Params = map[string]string{
    "a": "1",
    "b": "2",
}
url := "http://httpbin.org/get"
resp, _ := req.Get(url)
d, _ := resp.Json()
defer resp.Body.Close()
fmt.Println(d.Get("url").MustString())

Output:

http://httpbin.org/get?a=1&b=2

func (*Request) Head Uses

func (req *Request) Head(url interface{}) (resp *Response, err error)

Head issues a HEAD to the specified URL.

url can be string or *url.URL or ur.URL

func (*Request) Options Uses

func (req *Request) Options(url interface{}) (resp *Response, err error)

Options issues a OPTIONS to the specified URL.

url can be string or *url.URL or ur.URL

func (*Request) Patch Uses

func (req *Request) Patch(url interface{}) (resp *Response, err error)

Patch issues a PATCH to the specified URL.

url can be string or *url.URL or ur.URL

func (*Request) Post Uses

func (req *Request) Post(url interface{}) (resp *Response, err error)

Post issues a POST to the specified URL.

url can be string or *url.URL or ur.URL

Code:

c := new(http.Client)
req := request.NewRequest(c)
req.Data = map[string]string{
    "a": "1",
    "b": "2",
}
url := "http://httpbin.org/post"
resp, _ := req.Post(url)
defer resp.Body.Close()

Code:

c := new(http.Client)
req := request.NewRequest(c)
f, _ := os.Open("test.txt")
defer f.Close()
req.Files = []request.FileField{
    {FieldName: "abc", FileName: "abc.txt", File: f},
}
url := "http://httpbin.org/post"
resp, _ := req.Post(url)
defer resp.Body.Close()

Code:

c := new(http.Client)
req := request.NewRequest(c)
req.Body = strings.NewReader("a=1&b=2&foo=bar")
req.Headers = map[string]string{
    "Content-Type": request.DefaultContentType,
}
url := "http://httpbin.org/post"
resp, _ := req.Post(url)
defer resp.Body.Close()

func (*Request) PostForm Uses

func (req *Request) PostForm(url interface{}, data interface{}) (resp *Response, err error)

PostForm send post form request.

url can be string or *url.URL or ur.URL

data can be map[string]string or map[string][]string or string or io.Reader

data := map[string]string{
	"a": "1",
	"b": "2",
}

data := map[string][]string{
	"a": []string{"1", "2"},
	"b": []string{"2", "3"},
}

data : = "a=1&b=2"

data : = strings.NewReader("a=1&b=2")

func (*Request) Put Uses

func (req *Request) Put(url interface{}) (resp *Response, err error)

Put issues a PUT to the specified URL.

url can be string or *url.URL or ur.URL

func (*Request) Reset Uses

func (req *Request) Reset()

Reset all fields to default values

type Response Uses

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

Response ...

func Delete Uses

func Delete(url string, a *Args) (resp *Response, err error)

Delete issues a DELETE to the specified URL.

Caller should close resp.Body when done reading from it.

func Get Uses

func Get(url string, a *Args) (resp *Response, err error)

Get issues a GET to the specified URL.

Caller should close resp.Body when done reading from it.

Code:

c := new(http.Client)
args := request.NewArgs(c)
url := "http://httpbin.org/get"
resp, _ := request.Get(url, args)
d, _ := resp.Json()
defer resp.Body.Close()
fmt.Println(resp.Ok())
fmt.Println(d.Get("url").MustString())

Output:

true
http://httpbin.org/get
func Head(url string, a *Args) (resp *Response, err error)

Head issues a HEAD to the specified URL.

Caller should close resp.Body when done reading from it.

func Options Uses

func Options(url string, a *Args) (resp *Response, err error)

Options issues a OPTIONS to the specified URL.

Caller should close resp.Body when done reading from it.

func Patch Uses

func Patch(url string, a *Args) (resp *Response, err error)

Patch issues a PATCH to the specified URL.

Caller should close resp.Body when done reading from it.

func Post Uses

func Post(url string, a *Args) (resp *Response, err error)

Post issues a POST to the specified URL.

Caller should close resp.Body when done reading from it.

Code:

c := new(http.Client)
args := request.NewArgs(c)
args.Data = map[string]string{
    "a": "1",
    "b": "2",
}
url := "http://httpbin.org/post"
resp, _ := request.Post(url, args)
defer resp.Body.Close()

func Put Uses

func Put(url string, a *Args) (resp *Response, err error)

Put issues a PUT to the specified URL.

Caller should close resp.Body when done reading from it.

func (*Response) Content Uses

func (resp *Response) Content() (b []byte, err error)

Content return Response Body as []byte

func (*Response) Json Uses

func (resp *Response) Json() (*simplejson.Json, error)

Json return Response Body as simplejson.Json

func (*Response) OK Uses

func (resp *Response) OK() bool

OK check Response StatusCode < 400 ?

func (*Response) Ok Uses

func (resp *Response) Ok() bool

Ok check Response StatusCode < 400 ?

func (*Response) Reason Uses

func (resp *Response) Reason() string

Reason return Response Status

func (*Response) Text Uses

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

Text return Response Body as string

func (*Response) URL Uses

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

URL return finally request url

Package request imports 17 packages (graph) and is imported by 6 packages. Updated 2017-10-24. Refresh now. Tools for package owners.