dongtan9253 2018-10-31 11:31
浏览 233

GoLang代理http.request POST参数

I have written a simple http proxy in Go and need to read values of an HTTP POST sent parameters.

I have called request.ParseForm() in the application before create the reverse proxy and I got these parameteres but my reverse proxy stopped work. When I call request.ParseForm() after reverse proxy I get empty values.

error in go:

2018/10/31 12:26:45 http: panic serving [::1]:49967: runtime error: invalid 
memory address or nil pointer dereference
goroutine 51 [running]:
net/http.(*conn).serve.func1(0xc0001c2000)
    C:/Go/src/net/http/server.go:1746 +0xd7
panic(0x7ae340, 0xb00ba0)
    C:/Go/src/runtime/panic.go:513 +0x1c7
main.(*myTransport).RoundTrip(0xb2bb10, 0xc000140400, 0xf, 0xc0000ec301, 0x3)

error in chrome: ERR_EMPTY_RESPONSE

func serveReverseProxy(target string, res http.ResponseWriter, req *http.Request) {

    if req.Method == "POST" {

        // req.ParseForm() here broke the reverse proxy but I get value of HTTP POST Param
        req.ParseForm()
        value := req.Form.Get("url")
        fmt.Println(value)

        // parse the url
        url, _ := url.Parse(target)

        // create the reverse proxy
        proxy := httputil.NewSingleHostReverseProxy(url)

        // Update the headers to allow for SSL redirection
        req.URL.Path = url.Path
        req.URL.Host = url.Host
        req.URL.Scheme = url.Scheme
        req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
        req.Host = url.Host


        proxy.Transport = &myTransport{}
        proxy.ServeHTTP(res, req)

        // if I use req.ParseForm() here the reverse proxy works good but I get empty value of HTTP POST param
        req.ParseForm()
        value := req.Form.Get("url")
        fmt.Println(value)

        if(ableToSaveInDB){
            handleInsert(res,req, value)
        }
    }
}


func (t *myTransport) RoundTrip(request *http.Request) (*http.Response, error) {

    response, err := http.DefaultTransport.RoundTrip(request)

    if(response.StatusCode == 200) {
        ableToSaveInDB = true
    }

    return response, err
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 github符合条件20分钟秒到账,github空投 提供github账号可兑换💰感兴趣的可以找我交流一下
    • ¥50 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥200 uniapp长期运行卡死问题解决
    • ¥15 latex怎么处理论文引理引用参考文献
    • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?