β

gobox中的httpclient

Harries Blog™ 39 阅读

今天来说下使用gobox中 http client ,这个包就相当于命令行的curl工具,用于发起http请求。

重要的对象

config

const (
	DEFAULT_TIMEOUT        = 30 * time.Second
	DEFAULT_KEEPALIVE_TIME = 30 * time.Second

	DEFAULT_MAX_IDLE_CONNS_PER_HOST = 10
)

type Config struct {
	LogLevel int

	Timeout       time.Duration      // 连接及读写超时
	KeepAliveTime time.Duration

	MaxIdleConnsPerHost int
}

request

type Request struct {
	Method     string
	Url        string
	Body       []byte
	Ip         string     // 相当于设置hostIp
	ExtHeaders map[string]string

	*http.Request
}

response

type Response struct {
	T        time.Duration  // 请求耗时
	Contents []byte         // 响应内容

	*http.Response
}

代码 示例

package main

import (
	"github.com/goinbox/gohttp/httpclient"

	"time"
	"net/http"
	"fmt"
)

func main() {
	config := httpclient.NewConfig()
	config.Timeout = time.Second * 1

	client := httpclient.NewClient(config, nil)

	fmt.Println("clientGet")
	clientGet(client)

	fmt.Println("clientPost")
	clientPost(client)
}

func clientGet(client *httpclient.Client) {
	extHeaders := map[string]string{
		"GO-CLIENT-1": "gobox-httpclient-1",
		"GO-CLIENT-2": "gobox-httpclient-2",
	}
	req, _ := httpclient.NewRequest(http.MethodGet, "http://www.vmubt.com/test.php?a=1&b=2", nil, "127.0.0.1", extHeaders)

	resp, err := client.Do(req, 1)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(string(resp.Contents), resp.T.String())
	}
}

func clientPost(client *httpclient.Client) {
	extHeaders := map[string]string{
		"GO-CLIENT-1":  "gobox-httpclient-1",
		"GO-CLIENT-2":  "gobox-httpclient-2",
		"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
	}
	params := map[string]interface{}{
		"a": 1,
		"b": "bb",
		"c": "测试post",
	}
	req, _ := httpclient.NewRequest(http.MethodPost, "http://www.vmubt.com/test.php", httpclient.MakeRequestBodyUrlEncoded(params), "127.0.0.1", extHeaders)

	resp, err := client.Do(req, 1)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(string(resp.Contents), resp.T.String())
	}
}

输出:

clientGet
array(0) {
}
.516315ms

clientPost
array(3) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  string(2) "bb"
  ["c"]=>
  string(10) "测试post"
}
.616384ms

欢迎大家使用,使用中有遇到问题随时反馈,我们会尽快响应,谢谢!

原文

http://blog.7rule.com/2018/08/18/gobox-http-client.html

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。 PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处: Harries Blog™ » gobox中的httpclient

作者:Harries Blog™
追心中的海,逐世界的梦
原文地址:gobox中的httpclient, 感谢原作者分享。

发表评论