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的更多相关文章
随机推荐
- python 3下基于select模型的事件驱动机制程序
它的基本原理就是select/epoll这个function会不断的轮询所负责的所有socket,当某个socket有数据到达了,就通知用户进程.它的流程如图: 当用户进程调用了select,那么整个 ...
- Jquery Easing函数库
从jQuery API 文档中可以知道,jQuery自定义动画的函数.animate( properties [, duration] [, easing] [, complete] )有四个参数: ...
- 在MinGW下编译ffmpeg
因为需要使用ffmpeg的相关库和执行文件,所以需要编译最新的ffmpeg代码.为了能在编译成Windows native执行程序(需要在.net中调用该执行程序),这里我们使用MinGW. 1,安装 ...
- 从输入一个URL到页面完全显示发生了什么?
这是经典的前端问题,主要是对浏览器的工作原理有个理解! 网络通信走的一般是五层因特网协议,详见下图.图片来自于https://images2018.cnblogs.com/blog/882926/20 ...
- iframe 背景透明设置--兼容IE
iframe标签添加: allowTransparency="true"属性. 子文件body背景设置透明: background-color: transparent;.
- sql语句联表更新(从一个数据库中的一张表更新到另一个数据库的另一张表)
一.sql server数据库写法: update a set a.ksgmm=b.ksgmm,a.ksgm=b.ksgm,a.scztm=b.scztm,a.sczt=b.sczt from lan ...
- 微信授权、获取用户openid-纯前端实现——jsonp跨域访问返回json数据会报错的纯前端解决办法
近来,倒霉的后台跟我说让我拿个openid做微信支付使用,寻思很简单,开始干活. 首先引导用户打开如下链接,只需要将appid修改为自己的就可以,redirect_url写你的重定向url https ...
- Win10 UWP开发系列:解决Win10不同版本的Style差异导致的兼容性问题
最近在开发一个项目时,遇到了一个奇怪的问题,项目依赖的最低版本是10586,目标版本是14393,开发完毕发布到商店后,很多用户报无法正常加载页面.经查,有问题的都是Win10 10586版本. 我上 ...
- Java并发之乐观锁悲观锁
定义 乐观锁和悲观锁这两种锁机制,是在多用户环境并发控制的两种所机制. 悲观锁:假定会发生并发冲突,屏蔽一切可能违反数据完整性的操作.[1]常见实现如独占锁.乐观锁:假设不会发生并发冲突,只在提交操作 ...
- swoft 源码解读【转】
官网: https://www.swoft.org/ 源码解读: http://naotu.baidu.com/file/814e81c9781b733e04218ac7a0494e2a?toke ...