Reputation: 453
I am trying to serve a proxy like this:
package main
import (
"net/http"
)
func main() {
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
println(r.Host)
}))
}
and calling it with curl
curl -k -x http://localhost:8080 http://golang.org/
I get golang.org
printed out. Why I do not get the proxy hostname localhost
? is that a bug or limitation with the http proxy?
To clarify, what I am looking for is something like Nginx server address http://nginx.org/en/docs/http/ngx_http_core_module.html#var_server_addr
Upvotes: 1
Views: 266
Reputation: 453
I should use LocalAddrContextKey but looks like there is a known bug with setting it https://github.com/golang/go/issues/18686
A workaround is to hijack the http.ResponseWriter
ex:
package main
import (
"net/http"
)
func main() {
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hij, ok := w.(http.Hijacker)
if !ok {
panic("http server does not support hijacker")
}
clientConn, _, err := hij.Hijack()
if err != nil {
panic(err.Error())
}
println(clientConn.LocalAddr().String())
}))
}
Upvotes: 1