添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

用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