Documentation ¶
Overview ¶
Package request is a developer-friendly HTTP Send library for Gopher.
GET Request:
resp, err := Send.New().Get("https://httpbin.org/get") j, err := resp.JSON()
POST Request:
req = Send.New() req.SetFormData("key","value") req.SetFormData("a","123") resp, err := req.Post("https://httpbin.org/post")
Custom Cookies:
req = Send.New() req.SetCookie("key": "value") req.SetCookie("a": "123") resp, err := req.Get("https://httpbin.org/cookies")
Custom Headers:
req = Send.New() req.SetHeader("Accept-Encoding", "gzip,deflate,sdch") req.SetHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") resp, err := req.Get("https://httpbin.org/get")
Upload Files:
req = Send.New() f, err := os.Open("test.txt") req.AddFile(Send.FileField{"file", "test.txt", f}) resp, err := req.Post("https://httpbin.org/post")
JSON Body:
req = Send.New() req.SetJSON(map[string]string{ "a": "A", "b": "B", }) resp, err := req.Post("https://httpbin.org/post") req.SetJSON([]int{1, 2, 3}) resp, err = req.Post("https://httpbin.org/post")
others Body:
req = Send.New() req.SetBody(strings.NewReader("<xml><a>abc</a></xml")) req.SetContentType(Send.ApplicationXML) resp, err := req.Post("https://httpbin.org/post") // form req = Send.New() // Default Content-Type is "application/x-www-form-urlencoded" req.Body = strings.NewReader("a=1&b=2") resp, err = req.Post("https://httpbin.org/post")
HTTP Basic Authentication:
req = Send.New() req.SetBasicAuth("user", "passwd") resp, err := req.Get("https://httpbin.org/basic-auth/user/passwd")
Set Timeout:
req = Send.New() req.SetTimeout(5 * time.Second) resp, err := req.Get("http://example.com:12345")
Need more control?
You can setup req.Client(you know, it's an &http.Client), for example: set timeout
Index ¶
- Constants
- Variables
- type Args
- type BasicAuth
- type ContentType
- type FileField
- type Hook
- type IContentType
- type Request
- func (req *Request) AddFile(file FileField) *Request
- func (req *Request) AddFormData(key, value string) *Request
- func (req *Request) AddHook(hook Hook) *Request
- func (req *Request) AddHooks(hooks ...Hook) *Request
- func (req *Request) AddParam(key, value string) *Request
- func (req *Request) Delete(url string) (*Response, error)
- func (req *Request) Get(url string) (*Response, error)
- func (req *Request) Head(url string) (*Response, error)
- func (req *Request) Options(url string) (*Response, error)
- func (req *Request) Patch(url string) (*Response, error)
- func (req *Request) Post(url string) (*Response, error)
- func (req *Request) Put(url string) (*Response, error)
- func (req *Request) Reset() *Request
- func (req *Request) SetBasicAuth(username, password string) *Request
- func (req *Request) SetBody(body io.Reader) *Request
- func (req *Request) SetContentType(contentType IContentType) *Request
- func (req *Request) SetCookie(key, value string) *Request
- func (req *Request) SetFormData(key, value string) *Request
- func (req *Request) SetHeader(key, value string) *Request
- func (req *Request) SetJSON(json interface{}) *Request
- func (req *Request) SetParam(key, value string) *Request
- func (req *Request) SetTimeout(t time.Duration) *Request
- type Response
- func Delete(url string, args *Args) (*Response, error)
- func Get(url string, args *Args) (*Response, error)
- func Head(url string, args *Args) (*Response, error)
- func Options(url string, args *Args) (*Response, error)
- func Patch(url string, args *Args) (*Response, error)
- func Post(url string, args *Args) (*Response, error)
- func Put(url string, args *Args) (*Response, error)
- func Send(method, url string, args *Args) (*Response, error)
- func (resp *Response) Content() (b []byte, err error)
- func (resp *Response) JSON() (*simplejson.Json, error)
- func (resp *Response) JSONUnmarshal(destPtr interface{}) error
- func (resp *Response) OK() bool
- func (resp *Response) Ok() bool
- func (resp *Response) Reader() (reader io.ReadCloser, err error)
- func (resp *Response) Reason() string
- func (resp *Response) Text() (string, error)
- func (resp *Response) URL() (*url.URL, error)
- type RoundTripFunc
Examples ¶
Constants ¶
const Version = "0.0.1"
Version 版本号
Variables ¶
var ( TextXML = NewContentType("text/xml") TextHTML = NewContentType("text/html") TextPlain = NewContentType("text/plain") ApplicationXML = NewContentType("application/xml") ApplicationJSON = NewContentType("application/json") MultipartFormData = NewContentType("multipart/form-data") ApplicationOctetStream = NewContentType("application/octet-stream") ApplicationFormURLEncoded = NewContentType("application/x-www-form-urlencoded") DefaultContentType = ApplicationFormURLEncoded )
常用的 Content-Type
var ( // DefaultTimeout 默认超时时间 DefaultTimeout = time.Second * 10 // DefaultTransport 默认的 transport DefaultTransport http.RoundTripper = transport() // DefaultClient 默认的HTTP Client DefaultClient = newDefaultClient )
var DefaultHeaders = map[string]string{ "Connection": "keep-alive", "Accept-Encoding": "gzip, deflate", "Accept": "*/*", "User-Agent": DefaultUserAgent, }
DefaultHeaders 定义默认的 headers
var DefaultRedirectLimit = 10
DefaultRedirectLimit 最大重定向次数
var DefaultReqHooks []Hook
DefaultReqHooks 默认的Hook 比Args中的Hooks先执行
var DefaultUserAgent = "go-request/" + Version
DefaultUserAgent 定义默认的 User-Agent
var ErrMaxRedirect = errors.New("exceeded max redirects")
ErrMaxRedirect 当重定向次数大于DefaultRedirectLimit是将返回这个错误
Functions ¶
This section is empty.
Types ¶
type Args ¶
type Args struct { Client *http.Client Headers http.Header Cookies map[string]string Body io.Reader Params url.Values FormData url.Values Files []FileField JSON interface{} BasicAuth BasicAuth Hooks []Hook }
Args 发送http请求所使用的参数结构
type ContentType ¶
ContentType IContentType实现
type Hook ¶
type Hook interface { // BeforeRequest // 发送HTTP请求之前将会调用 BeforeRequest, // 如果 resp != nil or err != nil // 将使用这里的 resp and err, 不再继续发送HTTP请求. BeforeRequest(req *http.Request) (resp *http.Response, err error) // AfterRequest // 获取到response之后将调用 AfterRequest // 如果 newResp != nil or newErr != nil // 将使用新的NewResp而不是原始响应. AfterRequest(req *http.Request, resp *http.Response, err error) (newResp *http.Response, newErr error) }
Hook ...
type IContentType ¶
IContentType ContentType接口
func NewContentType ¶
func NewContentType(contentType string) IContentType
NewContentType 生成ContentType
type Request ¶
type Request struct {
*Args
}
Request Args的别名,主要对外提供调用方法
func (*Request) AddFormData ¶
AddFormData 添加Form参数 多次添加相同的参数,将在发送请求中发送多个相同的参数
func (*Request) Get ¶
Get 发送HTTP GET 请求到指定的URL
Example ¶
req := request.New() url := "https://httpbin.org/get" resp, _ := req.Get(url) d, _ := resp.JSON() fmt.Println(resp.Ok()) fmt.Println(d.Get("url").MustString())
Output: true https://httpbin.org/get
Example (Cookies) ¶
req := request.New() req.Cookies = map[string]string{ "name": "value", "foo": "bar", } url := "https://httpbin.org/cookies" _, _ = req.Get(url)
Output:
Example (CustomHeaders) ¶
req := request.New() req.Headers.Set("X-Abc", "abc") req.Headers.Set("User-Agent", "go-Send-test") url := "https://httpbin.org/get" resp, _ := req.Get(url) d, _ := resp.JSON() fmt.Println(d.Get("headers").Get("User-Agent").MustString()) fmt.Println(d.Get("headers").Get("X-Abc").MustString())
Output: go-Send-test abc
Example (Params) ¶
req := request.New() req.Params.Add("a", "1") req.Params.Add("b", "2") url := "https://httpbin.org/get" resp, _ := req.Get(url) d, _ := resp.JSON() fmt.Println(d.Get("url").MustString())
Output: https://httpbin.org/get?a=1&b=2
func (*Request) Post ¶
Post 发送HTTP POST 请求到指定的URL
Example ¶
req := request.New() req.FormData.Add("a", "1") req.FormData.Add("b", "2") url := "https://httpbin.org/post" _, _ = req.Post(url)
Output:
Example (Files) ¶
req := request.New() f, _ := os.Open("test.txt") defer f.Close() req.Files = []request.FileField{ {FieldName: "abc", FileName: "abc.txt", File: f}, } url := "https://httpbin.org/post" _, _ = req.Post(url)
Output:
Example (RawBody) ¶
req := request.New() req.Body = strings.NewReader("a=1&b=2&foo=bar") req.SetContentType(request.DefaultContentType) url := "https://httpbin.org/post" _, _ = req.Post(url)
Output:
func (*Request) SetBasicAuth ¶
SetBasicAuth 设置 http BasicAuth需要的用户名和密码
func (*Request) SetContentType ¶
func (req *Request) SetContentType(contentType IContentType) *Request
SetContentType 设置 Content-Type 如果不设置,默认使用 DefaultContentType
func (*Request) SetFormData ¶
SetFormData 设置Form参数 如果key已经存在将会覆盖旧的数据,如果key不存在将会添加一对新的key value
type Response ¶
Response ...
func (*Response) JSONUnmarshal ¶
JSONUnmarshal 解析JSON格式的数据到destPtr指针中 destPtr 只能传指针
type RoundTripFunc ¶
RoundTripFunc convert func to RoundTripFunc of implement RoundTripper interface