在golang HTTP API的开发中,偶尔会碰到,需要在某个子项目中,反向代理其他API的情况,下面是一个例子,供参考:

代码中使用了gow框架:

实现代码:

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "github.com/zituocn/gow"
    "io/ioutil"
    "net/http"
    "net/http/httputil"
    "net/url"
)

func main() {
    r := gow.Default()
    r.Any("/{match_all}", httpReverseProxyHandler)
    r.Run()

}

var (
    // 上层网站或接口(被反向代理的接口)
    website, _ = url.Parse("https://www.baidu.com")
)

func httpReverseProxyHandler(c *gow.Context) {
    simpleHostProxy := httputil.ReverseProxy{
        Director: func(req *http.Request) {
            req.URL.Scheme = website.Scheme
            req.URL.Host = website.Host
            req.Host = website.Host
        },

        ModifyResponse: func(resp *http.Response) error {
            if resp.Header.Get("Content-Encoding") == "gzip" {
                resp.Header.Del("Content-Encoding")
                gzipBody, err := gzip.NewReader(resp.Body)
                if err != nil {
                    return err
                }
                resp.Body = gzipBody
            }

            //如果要对resp.Body做些处理
            // 拿出数据
            body,err:=ioutil.ReadAll(resp.Body)
            if err!=nil{
                return err
            }
            resp.ContentLength = int64(len(body))
            fmt.Println(string(body))


            //把数据丢回去
            resp.Body = ioutil.NopCloser(bytes.NewReader(body))

            return nil
        },
    }

    simpleHostProxy.ServeHTTP(c.Writer, c.Request)
}

使用浏览器访问

http://127.0.0.1:8080