Skip to content

Instantly share code, notes, and snippets.

@MadVikingGod
Created February 1, 2024 16:17
Show Gist options
  • Save MadVikingGod/16a92daebf61c67a7ff7d846b11d93c4 to your computer and use it in GitHub Desktop.
Save MadVikingGod/16a92daebf61c67a7ff7d846b11d93c4 to your computer and use it in GitHub Desktop.
Self Running demo of http.Request Host behavior
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for k, v := range r.Header {
fmt.Println(k, v)
}
fmt.Println("Host", r.Host)
fmt.Println("--------------")
}))
defer srv.Close()
client := srv.Client()
header := http.Header{
"test": []string{"bar"},
"Host": []string{"foo.com"},
}
req, _ := http.NewRequest("GET", srv.URL, nil)
req.Header = header
fmt.Println("Request.Host", req.Host)
fmt.Println("Url.Host", req.URL.Host)
fmt.Println("Header.Host", req.Header.Get("Host"))
fmt.Println("--------------")
client.Do(req)
req.Host = "bar.net"
client.Do(req)
}
go run .
Request.Host 127.0.0.1:42387
Url.Host 127.0.0.1:42387
Header.Host foo.com
--------------
User-Agent [Go-http-client/1.1]
Test [bar]
Accept-Encoding [gzip]
Host 127.0.0.1:42387
--------------
Test [bar]
Accept-Encoding [gzip]
User-Agent [Go-http-client/1.1]
Host bar.net
--------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment