首页 > 代码库 > golang爬坑:一个简单的http内网转发

golang爬坑:一个简单的http内网转发

最近有一个需求,就是需要从内网服务器的一个端口请求数据,问题是这个内网端口不能被外网访问到,所以需要做一个转发代理服务。原理就是当请求到达时,将本机的地址替换成目标地址,然后其他格式不变,待目标请求返回后,又将目标的报文头及报文返回给客户端。具体代码如下:

func main() {
    localHost := "127.0.0.1:9001"
    targetHost := "127.0.0.1:8001"
    httpsServer(localHost, targetHost)
    log.Error("http server down!!!")
}

func httpsServer(addr string, remote_addr string) {

    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        cli := &http.Client{}
        body := make([]byte, 0)
        n, err := io.ReadFull(req.Body, body)
        if err != nil {
            io.WriteString(w, "Request Data Error")
            return
        }
        reqUrl := "http://" + remote_addr + req.URL.Path

        req2, err := http.NewRequest(req.Method, reqUrl, strings.NewReader(string(body)))
        if err != nil {
            io.WriteString(w, "Request Error")
            return
        }
        // set request content type
        contentType := req.Header.Get("Content-Type")
        req2.Header.Set("Content-Type", contentType)
        // request
        rep2, err := cli.Do(req2)
        if err != nil {
            io.WriteString(w, "Not Found!")
            return
        }
        defer rep2.Body.Close()
        n, err = io.ReadFull(rep2.Body, body)
        if err != nil {
            io.WriteString(w, "Request Error")
            return
        }
        // set response header
        for k, v := range rep2.Header {
            w.Header().Set(k, v[0])
        }
        io.WriteString(w, string(body[:n]))
    })
    var err error = nil
    err = http.ListenAndServe(":12307", nil)
    if err != nil {
        log.Fatal("server down!!!")
    }
}

  

  至此,一个简单的代理服务完成。

golang爬坑:一个简单的http内网转发