前言

基于我的文章《Golang https设置》
这里使用 ReverseProxy 来进行代理

代理服务器设置

package mainimport ("crypto/tls""crypto/x509""io/ioutil""log""net""net/http""net/http/httputil""net/url""os""time"
)func init() {os.Setenv("GODEBUG", "x509ignoreCN=0")
}func main() {//代理地址parse, err := url.Parse("https://www.open1.com:2001")if err != nil {panic(err)}proxy := httputil.NewSingleHostReverseProxy(parse)// 这里是配置了/etc/hosts www.open1.com 127.0.0.1//由于要代理https(还是希望通过https访问 (https://127.0.0.1:2000 | https://www.open1.com:2000)代理到 https://www.open1.com:2001)//就不能使用默认的http.DefaultTransport//如果不希望通过https代理,可以使用默认的 http.DefaultTransport 或者设置 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}//这样就能通过 (http://127.0.0.1:2000 | http://www.open1.com:2000)访问了proxy.Transport = &http.Transport{DialContext: (&net.Dialer{Timeout:   20 * time.Second,KeepAlive: 30 * time.Second,}).DialContext,//跳过认证//TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},TLSClientConfig: func() *tls.Config {pool := x509.NewCertPool()file, _ := ioutil.ReadFile("/Users/xieruixiang/go/src/gateway/testData/ca.crt")pool.AppendCertsFromPEM(file)return &tls.Config{RootCAs: pool}}(),MaxIdleConns:          100,IdleConnTimeout:       90 * time.Second,TLSHandshakeTimeout:   10 * time.Second,ExpectContinueTimeout: 1 * time.Second,}mux := http.NewServeMux()mux.HandleFunc("/", proxy.ServeHTTP)server := &http.Server{Addr:         ":2000",Handler:      mux,WriteTimeout: time.Second * 3,}//传入ssl证书和服务器私钥//非https的使用 server.ListenAndServe() 启动log.Fatal(server.ListenAndServeTLS("/Users/xieruixiang/go/src/gateway/testData/server.crt", "/Users/xieruixiang/go/src/gateway/testData/server.key"))
}

运行

由于在《Golang https设置》中生成的证书格式
在golang高版本中运行会出现如下错误:
certificate relies on legacy Common Name field, use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0
提供两种方式一种以 GODEBUG=“x509ignoreCN=0” 兼容
另一种更换成SANs证书,参考我的文章《自签名SAN证书》

# 以这种方式运行
# 要保证被代理服务已运行(www.open1.com:2001)
GODEBUG="x509ignoreCN=0" go run main.go