request

package module
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2019 License: MIT Imports: 17 Imported by: 0

README

request

Build Status Coverage Status Go Report Card GoDoc

A developer-friendly HTTP request library for Gopher. Inspired by Python-Requests.

Installation

go get -u github.com/melonwool/request

Documentation

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

Usage

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

GET:

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

POST:

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

Cookies:

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

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")

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:

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")

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")

or https://github.com/melonwool/request/tree/develop/_example/proxy

HTTP Basic Authentication:

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

License

Under the MIT License.

Documentation

Overview

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

Constants

View Source
const Version = "0.9.0"

Version export version

Variables

View Source
var DefaultClient = new(http.Client)

DefaultClient for NewArgs and NewRequest

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

DefaultContentType define default Content-Type Header for form body

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

DefaultHeaders define default headers

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

DefaultJsonType define default Content-Type Header for json body

View Source
var DefaultRedirectLimit = 10

DefaultRedirectLimit define max redirect counts

View Source
var DefaultUserAgent = "go-request/" + Version

DefaultUserAgent define default User-Agent header

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

ErrMaxRedirect when redirect times great than DefaultRedirectLimit will return this error

Functions

This section is empty.

Types

type Args

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
	Close     bool
}

Args for request args

func NewArgs

func NewArgs(c *http.Client) *Args

NewArgs return a *Args

type BasicAuth added in v0.2.0

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth struct for http basic auth

type FileField

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

FileField struct for upload file

type Hook added in v0.8.0

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 added in v0.3.0

type Request struct {
	*Args
}

Request is alias Args

func NewRequest added in v0.3.0

func NewRequest(c *http.Client) *Request

NewRequest return a *Request

func (*Request) Delete added in v0.3.0

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 added in v0.3.0

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

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/melonwool/request"
)

func main() {
	c := new(http.Client)
	req := request.NewRequest(c)
	url := "https://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
https://httpbin.org/get
Example (Cookies)
package main

import (
	"net/http"

	"github.com/melonwool/request"
)

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

Example (CustomHeaders)
package main

import (
	"fmt"
	"net/http"

	"github.com/melonwool/request"
)

func main() {
	c := new(http.Client)
	req := request.NewRequest(c)
	req.Headers = map[string]string{
		"X-Abc":      "abc",
		"User-Agent": "go-request-test",
	}
	url := "https://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
Example (Params)
package main

import (
	"fmt"
	"net/http"

	"github.com/melonwool/request"
)

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

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

func (*Request) GetResult added in v0.9.5

func (req *Request) GetResult(url, result interface{}) (err error)

GetResult issues a GET to the specified URL.

url can be string or *url.URL or ur.URL result is an url *output struct

func (*Request) Head added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

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 added in v0.3.0

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

Example
package main

import (
	"net/http"

	"github.com/melonwool/request"
)

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

Example (Files)
package main

import (
	"net/http"
	"os"

	"github.com/melonwool/request"
)

func main() {
	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 := "https://httpbin.org/post"
	resp, _ := req.Post(url)
	defer resp.Body.Close()
}
Output:

Example (RawBody)
package main

import (
	"net/http"
	"strings"

	"github.com/melonwool/request"
)

func main() {
	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 := "https://httpbin.org/post"
	resp, _ := req.Post(url)
	defer resp.Body.Close()
}
Output:

func (*Request) PostForm added in v0.5.0

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) PostResult added in v0.9.5

func (req *Request) PostResult(url, result interface{}) (err error)

PostResult issues a POST to the specified URL.

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

result is an url *output struct

func (*Request) Put added in v0.3.0

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 added in v0.5.0

func (req *Request) Reset()

Reset all fields to default values

type Response

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

Response ...

func Delete

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

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.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/melonwool/request"
)

func main() {
	c := new(http.Client)
	args := request.NewArgs(c)
	url := "https://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
https://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

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

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

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.

Example
package main

import (
	"net/http"

	"github.com/melonwool/request"
)

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

func Put

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

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

Content return Response Body as []byte

func (*Response) Json

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

Json return Response Body as simplejson.Json

func (*Response) OK

func (resp *Response) OK() bool

OK check Response StatusCode < 400 ?

func (*Response) Ok

func (resp *Response) Ok() bool

Ok check Response StatusCode < 400 ?

func (*Response) Reason

func (resp *Response) Reason() string

Reason return Response Status

func (*Response) Text

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

Text return Response Body as string

func (*Response) URL added in v0.2.0

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

URL return finally request url

Directories

Path Synopsis
_example

Jump to

Keyboard shortcuts

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