teeporxy.go
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的更多相关文章
随机推荐
- 恶补web之二:css知识(2)
css字体属性定义文本的字体系列,大小,加粗,风格和变形等. css中包含两种字体系列:通用字体系列和特定字体系列. font-family属性定义文本的字体系列: body {font-family ...
- RHEL 6 mdadm 实现Soft Raid
环境:RHEL 6.9 x64 1.mdadm命令用于管理系统软件RAID硬盘阵列 格式为:"mdadm [模式] <RAID设备名称> [选项] [成员设备名称]". ...
- Java杂记9—NIO
前言 非阻塞IO,也被称之为新IO,它重新定义了一些概念. 缓冲buffer 通道 channel 通道选择器 BIO 阻塞IO,几乎所有的java程序员都会的字节流,字符流,输入流,输出流等分类就是 ...
- Ocelot中文文档-Raft(实验功能不能用于生产环境)
Ocelot最近整合了Rafty,这是我在去年一直研究的Raft的一个实现. 这个项目实验性非常强,所以在我认为它没问题之前,请不要在生产环境中使用Ocelot的这个功能. Raft是一种分布式一致性 ...
- 在UltraEdit中如何像NotePad++一样实现双击单词在全文中高亮
NotePad++中有个功能特别好用,就是双击某个单词,这个单词就会在全文档中高亮,如下图 我经常用UltraEdit,结果是UE中没有这个功能,这么实用的功能居然没有? 没关系,在UE中shift+ ...
- lintcode 在O(1)时间复杂度删除链表节点
题目要求 给定一个单链表中的一个等待被删除的节点(非表头或表尾).请在在O(1)时间复杂度删除该链表节点. 样例 Linked list is 1->2->3->4, and giv ...
- 2018年,传言QQ首次被神秘黑客DDOS攻击,Python可以实现?
于2018-5-10日晚 网络流传黑客DDOS攻击了QQ服务器,导致大家聊天发送内容时出现感叹号.我们都知道一般情况下出现感叹号都是你的网络不稳定,或者...别人已经删除你了.然而昨晚很奇怪,发出的内 ...
- 19.QT-事件发送函数sendEvent()、postEvent()
Qt发送事件分为两种 -阻塞型事件发送 需要重写接收对象的event()事件处理函数 当事件发送后,将会立即进入event()事件处理函数进行事件处理 通过sendEvent()静态函数实现阻塞发送: ...
- ThreadPoolExcuter源码解析(一)
1.ThreadPoolExcuter原理说明 首先我们要知道为什么要使用ThreadPoolExcuter,具体可以看看文档中的说明: 线程池可以解决两个不同问题:由于减少了每个任务的调用开销,在执 ...
- city-picker插件使用-移动h5三级联动
首先访问该链接:http://www.jq22.com/jquery-info12914 看看是否是你要找的三级联动插件,(主要看注释的部分!) 好了,不知道是不是我傻,没有找到初始化数据的方法,本人 ...