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. gcc如何生成预编译头文件(.gch)

    1 建立comm.h 2 main.c中包含comm.h : #include "comm.h" 3 gcc -o comm.h.gch comm.h(低版本gcc会有bug) 4 ...

  2. 修改win7系统sid

    百度百科定义: Windows使用SID来表示所有的安全对象(security principals).安全对象包括主机,域计算机账户,用户和安全组.名字Name是用来代表SID的一个方法,可以允许用 ...

  3. nodejs+express blog项目分享

    项目简介:项目采用nodejs+express+typescript+mongodb技术搭建 主要功能: 1.用户注册 2.用户登录 3.文章管理模块 4.图片管理模块 5.token认证 6.密码加 ...

  4. java并发包分析之———concurrentHashMap

    一.Map体系 Hashtable是JDK 5之前Map唯一线程安全的内置实现(Collections.synchronizedMap不算).Hashtable继承的是Dictionary(Hasht ...

  5. J2EE架构师之路

    不经意的回首,工作进入第五个年头了,发现走过了从Java程序员到J2EE架构师的历程. 发现电脑上安装了各种各样的J2EE工具:JBuilder, WSAD, Eclipse, Rose, Toget ...

  6. [ SSH框架 ] Hibernate框架学习之四(JPA)

    一.JPA概述以及它和Hibernate之间的关系 1.1.Hibernate 概述 JPA Java Persistence API,是EJB3规范中负责对象持久化的应用程序编程接口(ORM接口), ...

  7. ubuntu10.04 安装oracle server 版 笔记

    1:从oracle 官网下载oracle 10g ,然后解压出一个database文件夹. 2 :创建RedHat的版本声明文件[默认ubuntu无法通过oracle 的检查] 在/etc/redha ...

  8. php添加日志文件

    记录一下. 有时候写测试代码的时候,不习惯直接在屏幕上输出反馈,那么可以配置日志文件,把需要输出的内容追加到日志文件里面,就很方便. Php自带日志系统,可以参考网上的博客配置. 我要说的是,如果你的 ...

  9. 0510JS流程语句

    |--跳转语句|----break; 终止整个循环,不再进行判断|----continue; 终止本次循环,接着去判断是否执行下次循环 |-选择(判断)结构|--if 如果|----if(条件1){  ...

  10. Page_Load不要忘了if (!IsPostBack)

    Page_Load不要忘了if (!IsPostBack) 问题:在DropDownList的SelectedIndexChanged事件中绑定数据,运行时,DropDownList控件的Select ...