easy_http

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

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

Go to latest
Published: Aug 29, 2021 License: Apache-2.0 Imports: 15 Imported by: 0

README

easy_http

介绍

easy_http是对golang的http client的简单封装,不依赖第三方库

  1. 提供了链式调用和方便使用的接口

  2. easy_http 支持https双向证书校验

  3. 支持代理,可以方便的设置代理

  4. easy_http 具有很强的拓展性,可以在easy_http的基础上非常方便的定制自己http请求

  5. easy_http 封装了multipart 协议, 可以方便的上传文件

  6. http Response 支持异步回调

  7. 可以方便的自定义Response

安装教程
  1. 运行下面的命令

    $ go get -u gitee.com/bruce_le/easy_http

  2. 把代码引入你的代码

    "import "gitee.com/bruce_le/easy_http"

使用说明
创建一个客户端
//new 一个构造器
builder := NewClientBuilder()

//是否跳过服务器证书校验
builder.SkipVerify(false)

//设置超时时间
builder.TimeOut(time.Second * 5)

//设置代理
builder.ProxyUrl("http://127.0.0.1:10809")

//设置根证书
var certPool [1]string
certPool[0] = "D:\\server.pem"
builder.Cert(certPool[:])
//设置双向校验证书
var tlsPath [1]*TlsPath
tlsPath[0] = &TlsPath{
    CertFile: "D:\\client.pem",
    KeyFile:  "D:\\client.key",
}

builder.Tls(tlsPath[:])

//设置http请求header
header := make(map[string]string)
header["Accept-Language"] = "Accept-Language: en,zh"
builder.Header(header)

//设置http请求cookie
cookie := make(map[string]string)
cookie["name"] = "value"
builder.Cookie(EasyCookie(cookie))

//开启cookie jar
builder.Jar(true, nil)

//设置 Response 处理函数
builder.BuildResponse(EasyBuildResponse)

//构造client
client, err := builder.Build()
if err != nil {
	fmt.Println(err)
	return
}
response := client.Get("https://baidu.com")
fmt.Println(response.Error())
fmt.Println(response.StatusCode())
fmt.Println(string(response.Content()))
post请求
builder := NewClientBuilder()
client, err := builder.Build()

if err != nil {
	panic(err)
}

data := make(map[string]string)
data["name"] = "vvvvv1"
data["name2"] = "2222222"
client.PostForm("http://127.0.0.1:8088", EasyPost(data))
json请求
builder := NewClientBuilder()
client, err := builder.Build()
if err != nil {
	panic(err)
}
type T struct {
	Name string `json:"name"`
}
tt := &T{Name: "aaaaaaaa"}

response := client.PostJson("http://127.0.0.1:8088", tt)
fmt.Println(response.Error())
bytes请求
builder := NewClientBuilder()
client, err := builder.Build()
if err != nil {
	panic(err)
}
type T struct {
	Name string `json:"name"`
}
tt := &T{Name: "aaaaaaaa"}
bytes, _ := json.Marshal(tt)
response := client.PostBytes("http://127.0.0.1:8088", bytes, nil)
fmt.Println(response.Error())
文件上传
builder := NewClientBuilder()
client, err := builder.Build()

if err != nil {
	panic(err)
}

data := make(map[string]string)
data["name"] = "vvvvv1"
data["name2"] = "2222222"

multipartBuilder := NewMultipartBuilder()
multipart, err := multipartBuilder.FromDate(data).AddFile("file", "D:\\a.txt").
	AddFile("file2", "D:\\b.log").Builder()

if err != nil {
	panic(err)
}
client.PostMultipart("http://127.0.0.1:8088", multipart)
异步请求
//函数回调
func call(response IResponse) {
	fmt.Println(response.Error())
	fmt.Println(string(response.Content()))
}
builder := NewClientBuilder()
client, _ := builder.Build()
client.GetAsyn("http://baidu.com", call)
time.Sleep(5 * time.Second)

//接口回调方式
type Get struct {
}

func (g Get) call(response IResponse) {
	fmt.Println(response.Error())
	fmt.Println(string(response.Content()))
}

builder := NewClientBuilder()
client, err := builder.Build()
if err != nil {
	panic(err.Error())
}

client.GetAsynWithCallback("http://baidu.com", &Get{})
builder := NewClientBuilder()
client, _ := builder.Build()
cookie := make(map[string]string)
cookie["name"] = "value"

header := make(map[string]string)
header["Accept-Language"] = "Accept-Language: en,zh"

client.Cookies(EasyCookie(cookie)).Header(header).Get("http://127.0.0.1:8088/")
自定义请求
builder := NewClientBuilder()
client, err := builder.Build()
if err != nil {
	panic(err)
}
response := client.SendWithMethod("http://127.0.0.1:8088", http.MethodGet, nil, func(request *http.Request) {

})
fmt.Println(response)
使用http 原生的 请求
builder := NewClientBuilder()
client, err := builder.Build()
if err != nil {
	panic(err)
}

request, err := http.NewRequest(http.MethodGet, "http://baidu.com", nil)
if err != nil {
	panic(err)
}
response, err := client.DoRequest(request)
if err != nil {
	fmt.Println(err)
} else {
	fmt.Println(response)
}
easy函数 使用
//构造 post form 的 value
values := make(map[string]string)
values["a"] = "aaaaaa"
values["b"] = "bbbbbb"
values["c"] = "中文"
EasyPost(values).Encode()

//构造 cookie 
cookie := make(map[string]string)
cookie["name"] = "value"
EasyCookie(cookie)

//构造 post 上传文件的 multipart
multipartBuilder := NewMultipartBuilder()
multipartBuilder.AddFile("file1", "d:\\a.txt")
multipartBuilder.AddFromDate("name", "value")
builder, err := multipartBuilder.Builder()

参与贡献
  1. Fork 本仓库
  2. 新建 Feat_xxx 分支
  3. 提交代码
  4. 新建 Pull Request

Documentation

Index

Constants

View Source
const (
	//chrome pc
	HTTP_USER_AGENT_CHROME_PC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
	//chrome mobile
	HTTP_USER_AGENT_CHROME_MOBILE = "" /* 147-byte string literal not displayed */

	//Firefox pc
	HTTP_USER_AGENT_FIREFOX_PC = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"
	//Firefox Mobil
	HTTP_USER_AGENT_FIREFOX_MOBLIE = "Mozilla/5.0 (Androdi; Linux armv7l; rv:5.0) Gecko/ Firefox/5.0 fennec/5.0"

	//IE11
	HTTP_USER_AGENT_IE11 = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko"
)

User-agent

View Source
const (
	HTTP_CONTENT_TYPE_FROM_DATA = "application/x-www-form-urlencoded"
	HTTP_CONTENT_TYPE_TEXT      = "text/plain"
	HTTP_CONTENT_TYPE_JSON      = "application/json"
	HTTP_CONTENT_TYPE_XML       = "application/xml"
)

Content-Type

Variables

This section is empty.

Functions

func EasyCookie

func EasyCookie(simple map[string]string) []*http.Cookie

构造一个简单的HTTP请求cookie

func EasyGet

func EasyGet(strUrl string, values map[string]string) string

构造一个简单的GET请求协议

func EasyPost

func EasyPost(values map[string]string) url.Values

构造一个简单的POST body,

func EasyPostFromRequest

func EasyPostFromRequest(r *http.Request)

POST请求中,处理request的函数

func EasyPostJsonRequest

func EasyPostJsonRequest(r *http.Request)

POST请求中,处理request的函数,设置`Content-Type` 为 json

func EasyPostXmlRequest

func EasyPostXmlRequest(r *http.Request)

POST请求中,处理request的函数,设置`Content-Type` 为 xml

Types

type BuildResponse

type BuildResponse func(resp *http.Response, err error) IResponse

type CheckRedirect

type CheckRedirect func(req *http.Request, via []*http.Request) error

request重定向的回调函数

type Client

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

func (*Client) AddCookies

func (c *Client) AddCookies(cookies []*http.Cookie)

为client添加cookie,原来的会保留,整个生命周期有效

func (*Client) AddHeader

func (c *Client) AddHeader(header map[string]string)

为client添加header,原来的会保留,整个生命周期有效

func (*Client) Cookies

func (c *Client) Cookies(cookies []*http.Cookie) *Client

为这次请求设置cookie,只有这次会生效

func (*Client) DoRequest

func (c *Client) DoRequest(r *http.Request) (*http.Response, error)

发起HTTP请求

func (*Client) Get

func (c *Client) Get(url string) IResponse

发起GET 请求

func (*Client) GetAsyn

func (c *Client) GetAsyn(url string, call func(response IResponse)) error

GET 异步请求,使用回调函数

func (*Client) GetAsynWithCallback

func (c *Client) GetAsynWithCallback(url string, call ICallBack) error

GET 异步请求,使用接口回调

func (*Client) Header

func (c *Client) Header(header map[string]string) *Client

为这次请求设置header,只有这次会生效

func (*Client) PostBytes

func (c *Client) PostBytes(url string, value []byte, req func(request *http.Request)) IResponse

post 的bytes请求

func (*Client) PostBytesAsyn

func (c *Client) PostBytesAsyn(url string, value []byte, req func(request *http.Request), call func(response IResponse)) error

post 的bytes请求

func (*Client) PostForm

func (c *Client) PostForm(url string, values url.Values) IResponse

post 的form请求

func (*Client) PostFormAsyn

func (c *Client) PostFormAsyn(url string, values url.Values, call func(response IResponse)) error

Post form 异步请求,使用回调函数

func (*Client) PostFormAsynWithCallback

func (c *Client) PostFormAsynWithCallback(url string, values url.Values, call ICallBack) error

Post form 异步请求,使用接口回调

func (*Client) PostJson

func (c *Client) PostJson(url string, value interface{}) IResponse

post 的json请求

func (*Client) PostJsonAsyn

func (c *Client) PostJsonAsyn(url string, value interface{}, call func(response IResponse)) error

Post json 异步请求,使用回调函数

func (*Client) PostJsonAsynWithCallback

func (c *Client) PostJsonAsynWithCallback(url string, values interface{}, call ICallBack) error

Post json 异步请求,使用接口回调

func (*Client) PostMultipart

func (c *Client) PostMultipart(url string, body IMultipart) IResponse

post 的multipart请求

func (*Client) PostMultipartAsyn

func (c *Client) PostMultipartAsyn(url string, body IMultipart, call func(response IResponse)) error

post 的multipart请求,使用回调函数

func (*Client) PostMultipartAsynWithCallback

func (c *Client) PostMultipartAsynWithCallback(url string, body IMultipart, call ICallBack) error

post 的multipart请求,使用接口回调

func (*Client) PostXml

func (c *Client) PostXml(url string, value interface{}) IResponse

post 的xml请求

func (*Client) PostXmlAsyn

func (c *Client) PostXmlAsyn(url string, value interface{}, call func(response IResponse)) error

Post xml 异步请求,使用回调函数

func (*Client) PostXmlAsynWithCallback

func (c *Client) PostXmlAsynWithCallback(url string, values interface{}, call ICallBack) error

Post xml 异步请求,使用接口回调

func (*Client) SendWithMethod

func (c *Client) SendWithMethod(url, method string, body io.Reader, req func(request *http.Request)) IResponse

指定请求的方法,发送请求 `req` 参数 可以处理这次请求的request

func (*Client) SendWithMethodCallBack

func (c *Client) SendWithMethodCallBack(url, method string, body io.Reader, req func(request *http.Request), call func(response IResponse)) error

使用异步回调的方式,指定请求的方法,发送请求 `req` 参数 可以处理这次请求的request `call` 参数,请求成功后的回调函数

func (*Client) SetCookies

func (c *Client) SetCookies(cookies []*http.Cookie)

为client设置新的cookie,原来的会删除,整个生命周期有效

func (*Client) SetHeader

func (c *Client) SetHeader(header map[string]string)

为client设置新的header,原来的会删除,整个生命周期有效

type ClientBuilder

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

client 构造器 用来初始化一个client 不建议直接new client使用

func NewClientBuilder

func NewClientBuilder() *ClientBuilder

初始化 clientBuilder

func (*ClientBuilder) Build

func (builder *ClientBuilder) Build() (*Client, error)

构造 client

func (*ClientBuilder) BuildResponse

func (builder *ClientBuilder) BuildResponse(build BuildResponse) *ClientBuilder

func (*ClientBuilder) Cert

func (builder *ClientBuilder) Cert(cert []string) *ClientBuilder

func (*ClientBuilder) CheckRedirect

func (builder *ClientBuilder) CheckRedirect(checkRedirect CheckRedirect) *ClientBuilder

func (*ClientBuilder) Cookie

func (builder *ClientBuilder) Cookie(cookie []*http.Cookie) *ClientBuilder

func (*ClientBuilder) Header

func (builder *ClientBuilder) Header(header map[string]string) *ClientBuilder

func (*ClientBuilder) Jar

func (builder *ClientBuilder) Jar(options *cookiejar.Options) *ClientBuilder

func (*ClientBuilder) ProxyUrl

func (builder *ClientBuilder) ProxyUrl(u string) *ClientBuilder

func (*ClientBuilder) SkipVerify

func (builder *ClientBuilder) SkipVerify(skip bool) *ClientBuilder

func (*ClientBuilder) TimeOut

func (builder *ClientBuilder) TimeOut(t time.Duration) *ClientBuilder

func (*ClientBuilder) Tls

func (builder *ClientBuilder) Tls(tlsPath []*TlsPath) *ClientBuilder

type EasyMultipart

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

func (*EasyMultipart) ContentType

func (m *EasyMultipart) ContentType() string

func (*EasyMultipart) Read

func (m *EasyMultipart) Read(p []byte) (n int, err error)

type HttpResponse

type HttpResponse struct {
	ResponseContent []byte
	// contains filtered or unexported fields
}

func (*HttpResponse) Content

func (h *HttpResponse) Content() []byte

func (*HttpResponse) ContentLength

func (h *HttpResponse) ContentLength() int64

func (*HttpResponse) Cookie

func (h *HttpResponse) Cookie(name string) *http.Cookie

func (*HttpResponse) Error

func (h *HttpResponse) Error() error

func (*HttpResponse) Header

func (h *HttpResponse) Header() http.Header

func (*HttpResponse) Request

func (h *HttpResponse) Request() *http.Request

func (*HttpResponse) Resp

func (h *HttpResponse) Resp() *http.Response

func (*HttpResponse) StatusCode

func (h *HttpResponse) StatusCode() int

type ICallBack

type ICallBack interface {
	EasyResponseCallback(IResponse)
}

异步回调的接口

type IMultipart

type IMultipart interface {
	//实现 Read函数
	io.Reader

	//获取这次的 boundary 字符串
	ContentType() string
}

用于 post multipart 的接口

type IResponse

type IResponse interface {
	//返回这个请求的错误
	Error() error

	//返回这个请求的http状态码
	StatusCode() int

	//返回HTTP请求的header信息
	Header() http.Header

	//返回HTTP内容长度
	ContentLength() int64

	//返回HTTP的内容
	Content() []byte

	//返回HTTP包中的 response信息
	Resp() *http.Response

	//返回这次请求的request信息
	Request() *http.Request

	//根据name 返回response的cookie
	Cookie(name string) *http.Cookie
}

使用client发去请求后,返回一个实现了这个接口的对象 只要实现这个接口,就能作为返回值 在 `BuildResponse` 函数中构造出返回的对象 默认提供了 `HttpResponse` 实现了这个接口 可以根据自己的需求自己重新实现这个接口

func EasyBuildResponse

func EasyBuildResponse(resp *http.Response, err error) IResponse

默认构造HTTP response的函数

type MultipartBuilder

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

用于构造一个 multipart

func NewMultipartBuilder

func NewMultipartBuilder() *MultipartBuilder

初始化一个 multipart 构造器

func (*MultipartBuilder) AddBytes

func (m *MultipartBuilder) AddBytes(name string, bytes []byte) *MultipartBuilder

添加[]byte, name, form-data的name

func (*MultipartBuilder) AddFile

func (m *MultipartBuilder) AddFile(name, fileName string) *MultipartBuilder

添加文件 name upload时的name fileName 文件的路径+文件名

func (*MultipartBuilder) AddFromDate

func (m *MultipartBuilder) AddFromDate(name, value string) *MultipartBuilder

添加form-data数据

func (*MultipartBuilder) Builder

func (m *MultipartBuilder) Builder() (*EasyMultipart, error)

构造 MultipartDate

func (*MultipartBuilder) FromDate

func (m *MultipartBuilder) FromDate(value map[string]string) *MultipartBuilder

以map的形式 添加form-data数据, k=>form-data的name, v=>form-data的Valve

type MultipartDateContent

type MultipartDateContent struct {
	Type    MultipartDateType
	Content []byte
}

用于 `MultipartBuilder` 中的内容记录

type MultipartDateType

type MultipartDateType int8
const (
	MultipartDateTypeFile MultipartDateType = iota
	MultipartDateTypeFormDate
	MultipartDateTypeContent
)

MultipartDateType 的枚举

type TlsPath

type TlsPath struct {
	//cert (pem) 路径
	CertFile string
	//key 路径
	KeyFile string
}

Jump to

Keyboard shortcuts

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