Golang 代理https

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

大家好,欢迎来到IT知识分享网。

前言

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

代理服务器设置

package main

import (
	"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

在这里插入图片描述
在这里插入图片描述

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/20835.html

(0)
上一篇 2024-02-04 22:45
下一篇 2024-02-05 13:00

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信