package main

import (
    "bytes"
    "crypto/tls"
    "flag"
    "fmt"
    "io"
    "io/ioutil"
    "math/rand"
    "net"
    "net/http"
    "net/http/httputil"
    "runtime"
    "time"
)

// Console flags
//参数解析
var (
    listen                = flag.String("l", ":8888", "port to accept requests")  //接收请求端口 默认渡口是8888
    targetProduction      = flag.String("a", "localhost:8080", "where production traffic goes. http://localhost:8080/production")  //a代表产品机器  默认端口是8080
    altTarget             = flag.String("b", "localhost:8081", "where testing traffic goes. response are skipped. http://localhost:8081/test")  //b 测试机器 端口是8081 
    debug                 = flag.Bool("debug", false, "more logging, showing ignored output")  //日志开关
    productionTimeout     = flag.Int("a.timeout", 3, "timeout in seconds for production traffic")// 生产机器请求超时时间
    alternateTimeout      = flag.Int("b.timeout", 1, "timeout in seconds for alternate site traffic")//测试机器清酒超时时间
    productionHostRewrite = flag.Bool("a.rewrite", false, "rewrite the host header when proxying production traffic") //生产机器是重定向开关  
    alternateHostRewrite  = flag.Bool("b.rewrite", false, "rewrite the host header when proxying alternate site traffic")//测试机器是否重定向开关
    percent               = flag.Float64("p", 100.0, "float64 percentage of traffic to send to testing")// 生产数据发给测试机器数据的百分比  流量分割
    tlsPrivateKey         = flag.String("key.file", "", "path to the TLS private key file") //TSL 私钥证书
    tlsCertificate        = flag.String("cert.file", "", "path to the TLS certificate file")//Tsl 龚玥证书
)

// handler contains the address of the main Target and the one for the Alternative target
//handler 包含连个地址  其中一个是生产服务器  另个一是测试服务器
type handler struct {
    Target      string
    Alternative string
    Randomizer  rand.Rand
}

// ServeHTTP duplicates the incoming request (req) and does the request to the Target and the Alternate target discading the Alternate response
//sereHttp 复制获取到的req 并且发送到生产服务器和测试服务器   测试服务器丢弃响应结果
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    var productionRequest, alternativeRequest *http.Request
    if *percent == 100.0 || h.Randomizer.Float64()*100 < *percent {
        alternativeRequest, productionRequest = DuplicateRequest(req) //复制数据到生产和测试请求中
        go func() {
            defer func() {
                if r := recover(); r != nil && *debug {
                    fmt.Println("Recovered in f", r)
                }
            }()
            // Open new TCP connection to the server
                      //获取客户端连接 带有超时时间   
            clientTcpConn, err := net.DialTimeout("tcp", h.Alternative, time.Duration(time.Duration(*alternateTimeout)*time.Second))
            if err != nil {
                if *debug {
                    fmt.Printf("Failed to connect to %s\n", h.Alternative)
                }
                return
            }
            clientHttpConn := httputil.NewClientConn(clientTcpConn, nil) // Start a new HTTP connection on it
            defer clientHttpConn.Close()                                 // Close the connection to the server
            if *alternateHostRewrite {
                alternativeRequest.Host = h.Alternative
            }
            err = clientHttpConn.Write(alternativeRequest) // Pass on the request
            if err != nil {
                if *debug {
                    fmt.Printf("Failed to send to %s: %v\n", h.Alternative, err)
                }
                return
            }
            _, err = clientHttpConn.Read(alternativeRequest) // Read back the reply
            if err != nil {
                if *debug {
                    fmt.Printf("Failed to receive from %s: %v\n", h.Alternative, err)
                }
                return
            }
        }()
    } else {
        productionRequest = req
    }
    defer func() {
        if r := recover(); r != nil && *debug {
            fmt.Println("Recovered in f", r)
        }
    }()

    // Open new TCP connection to the server
       //生产服务器
    clientTcpConn, err := net.DialTimeout("tcp", h.Target, time.Duration(time.Duration(*productionTimeout)*time.Second))
    if err != nil {
        fmt.Printf("Failed to connect to %s\n", h.Target)
        return
    }
    clientHttpConn := httputil.NewClientConn(clientTcpConn, nil) // Start a new HTTP connection on it
    defer clientHttpConn.Close()                                 // Close the connection to the server
    if *productionHostRewrite {
        productionRequest.Host = h.Target
    }
    err = clientHttpConn.Write(productionRequest) // Pass on the request
    if err != nil {
        fmt.Printf("Failed to send to %s: %v\n", h.Target, err)
        return
    }
    resp, err := clientHttpConn.Read(productionRequest) // Read back the reply
    if err != nil {
        fmt.Printf("Failed to receive from %s: %v\n", h.Target, err)
        return
    }
    defer resp.Body.Close()
    for k, v := range resp.Header {
        w.Header()[k] = v
    }
    w.WriteHeader(resp.StatusCode)
    body, _ := ioutil.ReadAll(resp.Body)
    w.Write(body)
}

func main() {
    flag.Parse()

    runtime.GOMAXPROCS(runtime.NumCPU())

    var err error

    var listener net.Listener

    if len(*tlsPrivateKey) > 0 {
        cer, err := tls.LoadX509KeyPair(*tlsCertificate, *tlsPrivateKey)
        if err != nil {
            fmt.Printf("Failed to load certficate: %s and private key: %s", *tlsCertificate, *tlsPrivateKey)
            return
        }

        config := &tls.Config{Certificates: []tls.Certificate{cer}}
        listener, err = tls.Listen("tcp", *listen, config)
        if err != nil {
            fmt.Printf("Failed to listen to %s: %s\n", *listen, err)
            return
        }
    } else {
        listener, err = net.Listen("tcp", *listen)
        if err != nil {
            fmt.Printf("Failed to listen to %s: %s\n", *listen, err)
            return
        }
    }

    h := handler{
        Target:      *targetProduction,
        Alternative: *altTarget,
        Randomizer:  *rand.New(rand.NewSource(time.Now().UnixNano())),
    }
    http.Serve(listener, h)
}

type nopCloser struct {
    io.Reader
}

func (nopCloser) Close() error { return nil }
//复制req到生茶服务器和测试服务器
func DuplicateRequest(request *http.Request) (request1 *http.Request, request2 *http.Request) {
    b1 := new(bytes.Buffer)
    b2 := new(bytes.Buffer)
    w := io.MultiWriter(b1, b2)  //同时向多个对象中写入数据
    io.Copy(w, request.Body) //复制数据到  w中
    defer request.Body.Close()
    request1 = &http.Request{
        Method:        request.Method,
        URL:           request.URL,
        Proto:         request.Proto,
        ProtoMajor:    request.ProtoMajor,
        ProtoMinor:    request.ProtoMinor,
        Header:        request.Header,
        Body:          nopCloser{b1},
        Host:          request.Host,
        ContentLength: request.ContentLength,
    }
    request2 = &http.Request{
        Method:        request.Method,
        URL:           request.URL,
        Proto:         request.Proto,
        ProtoMajor:    request.ProtoMajor,
        ProtoMinor:    request.ProtoMinor,
        Header:        request.Header,
        Body:          nopCloser{b2},
        Host:          request.Host,
        ContentLength: request.ContentLength,
    }
    return
}

teeporxy.go的更多相关文章

随机推荐

  1. 面试之路(3)-详解MVC,MVP,MVVM

    一:mvc mvc结构: 视图(View):用户界面. 控制器(Controller):业务逻辑 模型(Model):数据保存 mvc各部分的通信方式 mvc互动模式 通过 View 接受指令,传递给 ...

  2. Java不走弯路教程(5.Client-Server模式(2)-Client)

    5.Client-Server模式(2)-Client 在上一章,我们完成一个简单的数据库服务器,并在客户端用telnet方式成功进行通信. 本章将用Java实现客户端程序,来代替telnet. 先看 ...

  3. 我对IoC/DI的理解

    IoC IoC: Inversion of Control,控制反转, 控制权从应用程序转移到框架(如IoC容器),是框架共有特性 1.为什么需要IoC容器 1.1.应用程序主动控制对象的实例化及依赖 ...

  4. 三大框架:Struts+Hibernate+Spring

    三大框架:Struts+Hibernate+Spring Java三大框架主要用来做WEN应用. Struts主要负责表示层的显示 Spring利用它的IOC和AOP来处理控制业务(负责对数据库的操作 ...

  5. 双机热备ROSE HA工作原理

    双机热备ROSE HA工作原理 当双机热备软件启动后,ROSE HA首先启动HA Manager管理程序,根据高可靠性系统的配置结构初始化,然后启动必要的服务和代理程序来监控和管理系统服务.HA代理程 ...

  6. Appium-Desktop基本安装教程

    点击详见我的简书博客 一.下载桌面程序安装包 点击此处下载--Appium Desktop下载地址 此处楼主下载的是1.4.0Windows桌面版的 二.配置好自己的Android环境 环境变量: A ...

  7. golang升级

    系统安装软件一般在/usr/share,可执行的文件在/usr/bin,配置文件可能安装到了/etc下等. 文档一般在 /usr/share 可执行文件 /usr/bin 配置文件 /etc lib文 ...

  8. Aptana下Django1.6以后的项目模板结构改造

    Django1.6以后的manage.py放在项目包目录的根目录下,这种情况下在create app的app也在这个目录下面,由此可能导致app的名称有可能会和广大的内建包或者第三方包发生命名冲突,解 ...

  9. Android Third Party Libraries and SDK's

    http://javatechig.com/Android/android-third-party-libraries-sdks Over past few years, the age of mob ...

  10. (七):C++分布式实时应用框架 2.0

    C++分布式实时应用框架 2.0 技术交流合作QQ群:436466587 欢迎讨论交流 上一篇:(六):大型项目容器化改造 版权声明:本文版权及所用技术归属smartguys团队所有,对于抄袭,非经同 ...