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?
Your code is not a proxy but a simple handler on default route /. You can’t get the server address from your remote request but you can write a simple service for this. See a dummy example below.
package main
import (
"net/http"
)
var s string
func main() {
ip := "127.0.0.1"
port := "8080"
s = ip + ":" + port
http.ListenAndServe(s, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
println(ip)
}))
}
Ok, that was an example. You can get the server address from system but not from the request. From remote request you can only obtain the remote (requester) ip, if you want r.Host from your first code.
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) {
println(r.Host)
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())
}))
}