request

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2021 License: MIT Imports: 15 Imported by: 0

README

go-request

Advanced HTTP client for golang.

Installation

go get github.com/mingming-cn/go-request

Usage

import (
    "github.com/mingming-cn/go-request"
)

GET:

req := request.New()
resp, err := req.Get("https://httpbin.org/get")
j, err := resp.JSON()

POST:

req := request.New()
req.FormData.Set("key", "value")
req.FormData.Set("a", "123")
resp, err := req.Post("https://httpbin.org/post")

Cookies:

req := request.New()
req.Cookies.Set("key", "value")
req.Cookies.Set("a", "123")
resp, err := req.Get("https://httpbin.org/cookies")

Headers:

req := request.New()
req.Headers.Set("Accept-Encoding", "gzip,deflate,sdch",)
req.Headers.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",)
resp, err := req.Get("https://httpbin.org/get")

Files:

req := request.New()
f, err := os.Open("test.txt")
req.AddFile(request.FileField{"file", "test.txt", f})
resp, err := req.Post("https://httpbin.org/post")

Json:

req := request.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")

HTTP Basic Authentication:

req := request.New()
req.SetBasicAuth("user", "passwd")
resp, err := req.Get("https://httpbin.org/basic-auth/user/passwd")

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

Examples

Constants

View Source
const Version = "0.0.1"

Version 版本号

Variables

View Source
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

View Source
var (
	// DefaultTimeout 默认超时时间
	DefaultTimeout = time.Second * 10

	// DefaultTransport 默认的 transport
	DefaultTransport http.RoundTripper = transport()

	// DefaultClient 默认的HTTP Client
	DefaultClient = newDefaultClient
)
View Source
var DefaultHeaders = map[string]string{
	"Connection":      "keep-alive",
	"Accept-Encoding": "gzip, deflate",
	"Accept":          "*/*",
	"User-Agent":      DefaultUserAgent,
}

DefaultHeaders 定义默认的 headers

View Source
var DefaultRedirectLimit = 10

DefaultRedirectLimit 最大重定向次数

View Source
var DefaultReqHooks []Hook

DefaultReqHooks 默认的Hook 比Args中的Hooks先执行

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

DefaultUserAgent 定义默认的 User-Agent

View Source
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请求所使用的参数结构

func NewArgs

func NewArgs() *Args

NewArgs 返回一个新的 *Args

func (*Args) Reset

func (a *Args) Reset()

Reset 重置所有的参数

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth http basic auth 结构体

type ContentType

type ContentType struct {
	Type     string
	Charset  string
	Boundary string
}

ContentType IContentType实现

func (ContentType) GetBoundary

func (c ContentType) GetBoundary() string

GetBoundary 获取boundary

func (ContentType) GetCharset

func (c ContentType) GetCharset() string

GetCharset 获取charset

func (ContentType) String

func (c ContentType) String() string

String 实现Stringer接口,转为string类型

type FileField

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

FileField 上传文件的结构体

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

type IContentType interface {
	String() string
	GetCharset() string
	GetBoundary() string
}

IContentType ContentType接口

func NewContentType

func NewContentType(contentType string) IContentType

NewContentType 生成ContentType

type Request

type Request struct {
	*Args
}

Request Args的别名,主要对外提供调用方法

func New

func New() *Request

New 返回*Request

func (*Request) AddFile

func (req *Request) AddFile(file FileField) *Request

AddFile 添加需要上传的文件

func (*Request) AddFormData

func (req *Request) AddFormData(key, value string) *Request

AddFormData 添加Form参数 多次添加相同的参数,将在发送请求中发送多个相同的参数

func (*Request) AddHook

func (req *Request) AddHook(hook Hook) *Request

AddHook 添加请求处理钩子

func (*Request) AddHooks

func (req *Request) AddHooks(hooks ...Hook) *Request

AddHooks 批量添加请求处理钩子

func (*Request) AddParam

func (req *Request) AddParam(key, value string) *Request

AddParam 添加查询参数 多次添加相同的参数,将在发送请求中发送多个相同的参数

func (*Request) Delete

func (req *Request) Delete(url string) (*Response, error)

Delete 发送HTTP DELETE 请求到指定的URL

func (*Request) Get

func (req *Request) Get(url string) (*Response, error)

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

func (req *Request) Head(url string) (*Response, error)

Head 发送HTTP HEAD 请求到指定的URL

func (*Request) Options

func (req *Request) Options(url string) (*Response, error)

Options 发送HTTP OPTIONS 请求到指定的URL

func (*Request) Patch

func (req *Request) Patch(url string) (*Response, error)

Patch 发送HTTP PATCH 请求到指定的URL

func (*Request) Post

func (req *Request) Post(url string) (*Response, error)

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

func (req *Request) Put(url string) (*Response, error)

Put 发送HTTP PUT 请求到指定的URL

func (*Request) Reset

func (req *Request) Reset() *Request

Reset 重置所有参数

func (*Request) SetBasicAuth

func (req *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth 设置 http BasicAuth需要的用户名和密码

func (*Request) SetBody

func (req *Request) SetBody(body io.Reader) *Request

SetBody 设置 Body Reader

func (*Request) SetContentType

func (req *Request) SetContentType(contentType IContentType) *Request

SetContentType 设置 Content-Type 如果不设置,默认使用 DefaultContentType

func (*Request) SetCookie

func (req *Request) SetCookie(key, value string) *Request

SetCookie 设置 Cookie

func (*Request) SetFormData

func (req *Request) SetFormData(key, value string) *Request

SetFormData 设置Form参数 如果key已经存在将会覆盖旧的数据,如果key不存在将会添加一对新的key value

func (*Request) SetHeader

func (req *Request) SetHeader(key, value string) *Request

SetHeader 设置 Header 如果不设置,将只使用DefaultHeaders中定义的header

func (*Request) SetJSON

func (req *Request) SetJSON(json interface{}) *Request

SetJSON 设置 JSON Object

func (*Request) SetParam

func (req *Request) SetParam(key, value string) *Request

SetParam 设置查询参数 如果key已经存在将会覆盖旧的数据,如果key不存在将会添加一对新的key value

func (*Request) SetTimeout

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

SetTimeout 设置HTTP请求超时时间

type Response

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

Response ...

func Delete

func Delete(url string, args *Args) (*Response, error)

Delete 发送HTTP DELETE 请求到指定的URL

func Get

func Get(url string, args *Args) (*Response, error)

Get 发送HTTP GET 请求到指定的URL

func Head(url string, args *Args) (*Response, error)

Head 发送HTTP HEAD 请求到指定的URL

func Options

func Options(url string, args *Args) (*Response, error)

Options 发送HTTP OPTIONS 请求到指定的URL

func Patch

func Patch(url string, args *Args) (*Response, error)

Patch 发送HTTP PATCH 请求到指定的URL

func Post

func Post(url string, args *Args) (*Response, error)

Post 发送HTTP POST 请求到指定的URL

func Put

func Put(url string, args *Args) (*Response, error)

Put 发送HTTP PUT 请求到指定的URL

func Send

func Send(method, url string, args *Args) (*Response, error)

Send 发送HTTP请求到指定的URL

func (*Response) Content

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

Content 返回[]byte格式的Body数据

func (*Response) JSON

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

JSON 返回 simplejson.JSON 类型的Body数据

func (*Response) JSONUnmarshal

func (resp *Response) JSONUnmarshal(destPtr interface{}) error

JSONUnmarshal 解析JSON格式的数据到destPtr指针中 destPtr 只能传指针

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

func (resp *Response) Reader() (reader io.ReadCloser, err error)

Reader 获取body reader

func (*Response) Reason

func (resp *Response) Reason() string

Reason return Response Status

func (*Response) Text

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

Text 获取文本格式的Body数据

func (*Response) URL

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

URL return finally Send url

type RoundTripFunc

type RoundTripFunc func(req *http.Request) *http.Response

RoundTripFunc convert func to RoundTripFunc of implement RoundTripper interface

func (RoundTripFunc) RoundTrip

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implement RoundTripper interface

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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