Better late than never.

golang 实现简单http、https 的反向代理

go-reverse-proxy

基于go实现简单http/https的反向代理服务 github

起因

用jquery ajax 请求第三方服务提供的接口的时候遇到跨域问题,解决这个问题网上的答案已经总结的很好了,前后端都有相关方案,这里就不做过多的说明了。自己常用的就是利用nginx的反向代理来处理跨域问题,只是在本地环境弄一个纯前端的项目(不基于node的npm开发),又不想借助nginx的配置来解决,就想着不如用go实现一个简单的反代功能?golang能写出frp这样的工具,弄个简单的反代功能应该不需要多少代码吧,果然网上一波搜索,就有现成的代码段:

package main

import(
        "log"
        "net/url"
        "net/http"
        "net/http/httputil"
)

func main() {
        remote, err := url.Parse("http://baidu.com")
        if err != nil {
                panic(err)
        }

        proxy := httputil.NewSingleHostReverseProxy(remote)
        http.HandleFunc("/", handler(proxy))
        err = http.ListenAndServe(":8080", nil)
        if err != nil {
                panic(err)
        }
}

func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
        return func(w http.ResponseWriter, r *http.Request) {
                log.Println(r.URL)
                w.Header().Set("X-Ben", "Rad")
                p.ServeHTTP(w, r)
        }
}

这里主要是通过golang httputil 库的 NewSingleHostReverseProxy 方法实现反代,果然很方便, 乍一看好像没啥问题,但是一运行就发现 http 报错,https 直接403,代理本地其他端口到是没问题,继续找解决方案,在看到 这篇文章之后,大概知道了个所以然,接着去到go sdk源码 一顿copy 魔改,如下:

// 完整代码可直接查看github源码
func GoReverseProxy(this *RProxy) *httputil.ReverseProxy {
    remote := this.remote

    proxy := httputil.NewSingleHostReverseProxy(remote)

    proxy.Director = func(request *http.Request) {
        targetQuery := remote.RawQuery
        request.URL.Scheme = remote.Scheme
        request.URL.Host = remote.Host
        request.Host = remote.Host // todo 这个是关键
        request.URL.Path, request.URL.RawPath = joinURLPath(remote, request.URL)

        if targetQuery == "" || request.URL.RawQuery == "" {
            request.URL.RawQuery = targetQuery + request.URL.RawQuery
        } else {
            request.URL.RawQuery = targetQuery + "&" + request.URL.RawQuery
        }
        if _, ok := request.Header["User-Agent"]; !ok {
            // explicitly disable User-Agent so it's not set to default value
            request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36")
        }
        log.Println("request.URL.Path:", request.URL.Path, "request.URL.RawQuery:", request.URL.RawQuery)
    }

    // 修改响应头
    proxy.ModifyResponse = func(response *http.Response) error {
        response.Header.Add("Access-Control-Allow-Origin", "*")
        response.Header.Add("Reverse-Proxy-Server-PowerBy", "(Hzz)https://hzz.cool")
        return nil
    }

    return proxy
}

使用

  • windows64 直接下载 releases
  • 编译
git clone 
cd go-reverse-proxy

# 编译
go build -ldflags "-s -w"

# 执行启动
./go-reverse-proxy

参数说明

./go-reverse-proxy.exe -h

-p string
      本地监听的端口 (default "1874")
-r string
      需要代理的地址 (default "https://hzz.cool")

-- END

写的不错,赞助一下主机费

扫一扫,用支付宝赞赏
扫一扫,用微信赞赏

暂无评论~~