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的更多相关文章

  1. 储物柜soket通信协议和中间件实现技术细节

    一.中间件程序的职责: 1)对柜机提供soket长连接的服务器端,就是soket server.可提供上万的客户端同时连接.用来实时响应控制请求,中间件必须随时知道某个柜机的在线状态,外部请求时才能判 ...

  2. 突破短板,传统桌面程序 使用webapi 扩展迎合web和移动端融合的需求

    传统桌面程序不能完全被web和移动端替代,但是需要改造.这里要说的是巧用webapi把以前用dll和com组件,ocx等方式做接口,做分布式开发的方式,改成restful 风格api的方式实现跨平台, ...

  3. PHP API 框架开发的学习

    基于互联网的应用正变得越来越普及,在这个过程中,有更多的站点将自身的资源开放给开发者来调用.对外提供的API 调用使得站点之间的内容关联性更强,同时这些开放的平台也为用户.开发者和中小网站带来了更大的 ...

  4. jQuery里面ajax请求的封装

    为了避免ajax漫天飞,我们需要对jQuery的代码进行封装,封装代码: function api_request(name, params, cb, scope, async, el) { if ( ...

  5. Python 基于request库的get,post,delete,封装

    # coding=utf-8 import json import requests class TestApi(object): """ /* @param: @ses ...

  6. 听说PHP的生成器yield处理大量数据杠杠的

    官方解释yield yield生成器是php5.5之后出现的,官方文档这样解释:yield提供了一种更容易的方法来实现简单的迭代对象,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大 ...

  7. 如何使用PHP的生成器yield处理大量数据业务

    官方解释yield yield生成器是php5.5之后出现的,官方文档这样解释:yield提供了一种更容易的方法来实现简单的迭代对象,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大 ...

  8. 20191011-构建我们公司自己的自动化接口测试框架-testrun最重要的模块

    testrun模块呢就是最终自动化测试入口,调用前面封装的各个模块主要流程是: 1. 获取测试集种待执行的测试用例 2. 处理测试用例获取的数据,包括转换数据格式,处理数据的中的关联等 3. 处理完数 ...

  9. 20191011-构建我们公司自己的自动化接口测试框架-Util的getTestSuite模块

    getTestSuite主要是用于在testData里面获取测试集以及对应的测试数据,包括2个主要的方法,一个是获取测试集,一个是获取测试集里面要执行的测试用例 获取测试集方法: from Util. ...

随机推荐

  1. linux 常见命令及说明杂记

    systemctl 命令: systemctl 是管制服务的主要工具, 它整合了chkconfig 与 service功能于一体.示例:systemctl is-enabled iptables.se ...

  2. 重定向和servlet生命周期

    重定向(1)什么是重定向服务器通知浏览器向一个新的地址发送请求.注:可以发送一个302状态码和一个Location消息头.(该消息头包含了一个地址,称之为重定向地址),浏览器收到之后,会立即向重定向地 ...

  3. ant 脚本使用技巧

    assoc命令 要删除文件扩展名为 .txt 的文件类型关联,请键入: assoc .txt =

  4. 企业级web负载均衡完美架构

    转载:揭秘企业级web负载均衡完美架构(图) 2010-07-06 15:16 抚琴煮酒 51CTO.com 字号:T | T 相信很多朋友对企业级的负载均衡高可用实例非常感兴趣,此篇文章根据成熟的线 ...

  5. [更新]单线程的JS引擎与 Event Loop

    先来思考一个问题,JS 是单线程的还是多线程的?如果是单线程,为什么JavaScript能让AJAX异步发送和回调请求,还有setTimeout也看起来像是多线程的?还有non-blocking IO ...

  6. linux 下查看wwn号

    PC server主机与FC存储进行连接时,一般需要加装HBA卡,两者之间衔接的一个重要参数就是wwn号.redhat或suse下查看wwn号的方法如下.一.SuSE Linux 9查看 /proc/ ...

  7. How to change from default to alternative Python version on Debian Linux

    https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux You ...

  8. 彪悍开源的分析数据库-ClickHouse

    https://zhuanlan.zhihu.com/p/22165241 今天介绍一个来自俄罗斯的凶猛彪悍的分析数据库:ClickHouse,它是今年6月开源,俄语社区为主,好酒不怕巷子深. 本文内 ...

  9. nginx flv点播服务器搭建

    首先选用Nginx+Nginx-rtmp-module作为点播服务器,安装文章:https://www.atlantic.NET/community/howto/install-rtmp-ubuntu ...

  10. Ubuntu 安装LAMP

    简要记录一下. 环境准备 虚拟机环境 lz@starnight:~$ sudo -i [sudo] password for lz: root@starnight:~# cat /etc/issue ...