我在Go中编写了一个简单的http代理,需要读取HTTP POST发送的参数的值。
在创建反向代理之前,我已在应用程序中调用request.ParseForm(),但得到了这些参数,但我的反向代理停止了工作。当我在反向代理之后调用request.ParseForm()时,我得到空值。
执行中的错误:
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)
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
}