api_request.go
package http_api
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type deadlinedConn struct {
Timeout time.Duration
net.Conn
}
func (c *deadlinedConn) Read(b []byte) (n int, err error) {
return c.Conn.Read(b)
}
func (c *deadlinedConn) Write(b []byte) (n int, err error) {
return c.Conn.Write(b)
}
// A custom http.Transport with support for deadline timeouts
func NewDeadlineTransport(connectTimeout time.Duration, requestTimeout time.Duration) *http.Transport {
transport := &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, connectTimeout)
if err != nil {
return nil, err
}
return &deadlinedConn{connectTimeout, c}, nil
},
ResponseHeaderTimeout: requestTimeout,
}
return transport
}
type Client struct {
c *http.Client
}
func NewClient(tlsConfig *tls.Config, connectTimeout time.Duration, requestTimeout time.Duration) *Client {
transport := NewDeadlineTransport(connectTimeout, requestTimeout)
transport.TLSClientConfig = tlsConfig
return &Client{
c: &http.Client{
Transport: transport,
Timeout: requestTimeout,
},
}
}
// NegotiateV1 is a helper function to perform a v1 HTTP request
// and fallback to parsing the old backwards-compatible response format
// storing the result in the value pointed to by v.
//
// TODO: deprecated, remove in 1.0 (replace calls with GETV1)
func (c *Client) NegotiateV1(endpoint string, v interface{}) error {
retry:
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return err
}
req.Header.Add("Accept", "application/vnd.nsq; version=1.0")
resp, err := c.c.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 403 && !strings.HasPrefix(endpoint, "https") {
endpoint, err = httpsEndpoint(endpoint, body)
if err != nil {
return err
}
goto retry
}
return fmt.Errorf("got response %s %q", resp.Status, body)
}
if len(body) == 0 {
body = []byte("{}")
}
// unwrap pre-1.0 api response
if resp.Header.Get("X-NSQ-Content-Type") != "nsq; version=1.0" {
var u struct {
StatusCode int64 `json:"status_code"`
Data json.RawMessage `json:"data"`
}
err := json.Unmarshal(body, u)
if err != nil {
return err
}
if u.StatusCode != 200 {
return fmt.Errorf("got 200 response, but api status code of %d", u.StatusCode)
}
body = u.Data
}
return json.Unmarshal(body, v)
}
// GETV1 is a helper function to perform a V1 HTTP request
// and parse our NSQ daemon's expected response format, with deadlines.
func (c *Client) GETV1(endpoint string, v interface{}) error {
retry:
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return err
}
req.Header.Add("Accept", "application/vnd.nsq; version=1.0")
resp, err := c.c.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 403 && !strings.HasPrefix(endpoint, "https") {
endpoint, err = httpsEndpoint(endpoint, body)
if err != nil {
return err
}
goto retry
}
return fmt.Errorf("got response %s %q", resp.Status, body)
}
err = json.Unmarshal(body, &v)
if err != nil {
return err
}
return nil
}
// PostV1 is a helper function to perform a V1 HTTP request
// and parse our NSQ daemon's expected response format, with deadlines.
func (c *Client) POSTV1(endpoint string) error {
retry:
req, err := http.NewRequest("POST", endpoint, nil)
if err != nil {
return err
}
req.Header.Add("Accept", "application/vnd.nsq; version=1.0")
resp, err := c.c.Do(req)
if err != nil {
return err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 403 && !strings.HasPrefix(endpoint, "https") {
endpoint, err = httpsEndpoint(endpoint, body)
if err != nil {
return err
}
goto retry
}
return fmt.Errorf("got response %s %q", resp.Status, body)
}
return nil
}
func httpsEndpoint(endpoint string, body []byte) (string, error) {
var forbiddenResp struct {
HTTPSPort int `json:"https_port"`
}
err := json.Unmarshal(body, &forbiddenResp)
if err != nil {
return "", err
}
u, err := url.Parse(endpoint)
if err != nil {
return "", err
}
host, _, err := net.SplitHostPort(u.Host)
if err != nil {
return "", err
}
u.Scheme = "https"
u.Host = net.JoinHostPort(host, strconv.Itoa(forbiddenResp.HTTPSPort))
return u.String(), nil
}
api_request.go的更多相关文章
- 储物柜soket通信协议和中间件实现技术细节
一.中间件程序的职责: 1)对柜机提供soket长连接的服务器端,就是soket server.可提供上万的客户端同时连接.用来实时响应控制请求,中间件必须随时知道某个柜机的在线状态,外部请求时才能判 ...
- 突破短板,传统桌面程序 使用webapi 扩展迎合web和移动端融合的需求
传统桌面程序不能完全被web和移动端替代,但是需要改造.这里要说的是巧用webapi把以前用dll和com组件,ocx等方式做接口,做分布式开发的方式,改成restful 风格api的方式实现跨平台, ...
- PHP API 框架开发的学习
基于互联网的应用正变得越来越普及,在这个过程中,有更多的站点将自身的资源开放给开发者来调用.对外提供的API 调用使得站点之间的内容关联性更强,同时这些开放的平台也为用户.开发者和中小网站带来了更大的 ...
- jQuery里面ajax请求的封装
为了避免ajax漫天飞,我们需要对jQuery的代码进行封装,封装代码: function api_request(name, params, cb, scope, async, el) { if ( ...
- Python 基于request库的get,post,delete,封装
# coding=utf-8 import json import requests class TestApi(object): """ /* @param: @ses ...
- 听说PHP的生成器yield处理大量数据杠杠的
官方解释yield yield生成器是php5.5之后出现的,官方文档这样解释:yield提供了一种更容易的方法来实现简单的迭代对象,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大 ...
- 如何使用PHP的生成器yield处理大量数据业务
官方解释yield yield生成器是php5.5之后出现的,官方文档这样解释:yield提供了一种更容易的方法来实现简单的迭代对象,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大 ...
- 20191011-构建我们公司自己的自动化接口测试框架-testrun最重要的模块
testrun模块呢就是最终自动化测试入口,调用前面封装的各个模块主要流程是: 1. 获取测试集种待执行的测试用例 2. 处理测试用例获取的数据,包括转换数据格式,处理数据的中的关联等 3. 处理完数 ...
- 20191011-构建我们公司自己的自动化接口测试框架-Util的getTestSuite模块
getTestSuite主要是用于在testData里面获取测试集以及对应的测试数据,包括2个主要的方法,一个是获取测试集,一个是获取测试集里面要执行的测试用例 获取测试集方法: from Util. ...
随机推荐
- rails项目如何改变已建立的model结构
有时候第一次用rails g model或者scaffold建立数据模型的时候难免会出错,比如字段类型错误或者字段名称错误,甚至少添加或多添加了几个字段哦.这种情况下手动去修改数据结构是比较头疼的,官 ...
- RecyclerView 与 Scrollview 搭配使用的两个坑
RecyclerView & Scrollview & wrap_content RecyclerView wrap_content 用android.support.v4.widge ...
- Spring Boot Kafka
1.创建集群 http://kafka.apache.org/documentation/#quickstart 有一句我觉得特别重要: For Kafka, a single broker is j ...
- 模拟IC芯片设计开发的流程
模拟IC芯片设计开发的流程 IC的设计,模拟和数字, 还有混合IC, 在设计方法, 注意点, 工具等有明显的区别, 我主要以模拟无线接收IC系统设计为例说明. 一个IC芯片的设计开发大致包括如下步骤. ...
- Linux中使用export命令设置环境变量
Linux export 命令 2011-08-31 22:36:39| 分类: 命令总结|举报|字号 订阅 功能说明:设置或显示环境变量. ######################## ...
- mysql 带条件的sum/count 使用技巧
本测试只是简单测试,其用途不在于代替count函数配合where函数进行聚合计算,而是在复杂查询中在sum/count中加入条件,一次性求出不同条件下的聚合结果. 1.插入测试数据如图 2.sum计算 ...
- Java面试与回答技巧(1.如何正确的面试)
在IT行业中,大部分公司很难用有效的方式招到合适的人.直接暴露出来的问题是:・花重金招了一个人,但实际的战斗力还比不上应届毕业生.・招聘了一个知名企业的高管,引入了一些高大上的技术,结果本来稳定的生产 ...
- python---生成器、迭代器
# -*- coding:utf-8 -*- # LC # 列表生成式 def func(x): print(x) return 2*x print([ func(i) for i in range( ...
- java.lang.SecurityException: Can't make field constructor accessible
原本使用GsonConvertor,在Android版本5.1.1上没有任何问题,结果切换到版本6.0.1上,出现以下所示问题: java.lang.IllegalArgumentException: ...
- java-将评论内容过滤特殊表情emoj符号,保存到mysql中
正常操作评论,保存时,若评论内容含有特殊表情符号,后台将报错如下: Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_ ...