Skip to content

Instantly share code, notes, and snippets.

@rachitchauhan43
Last active August 30, 2022 16:20
Show Gist options
  • Save rachitchauhan43/8b7fc6a24074d0d0c0d9095f4e583a07 to your computer and use it in GitHub Desktop.
Save rachitchauhan43/8b7fc6a24074d0d0c0d9095f4e583a07 to your computer and use it in GitHub Desktop.
This gist creates 2 files -- http_connection_reuse_test_server.go will bring up a server and http_connection_reuse_test_client.go will bring a client that make calls to that server. This is to test the TCP connection reuse for new HTTP connections
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
for i := 0; i < 10; i++ {
client := http.Client{}
// I am running a server here that can be found here https://gist.github.com/rachitchauhan43/8b7fc6a24074d0d0c0d9095f4e583a07#file-http_connection_reuse_test_server-go
req, err := http.NewRequest("GET", "http://localhost:8090/hello", nil)
req.Header = http.Header{
"Host": {"www.host.com"},
"Content-Type": {"application/json"},
"Authorization": {"Bearer Token"},
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
//Commenting out bellow line will lead to multiple TCP connections being in TIME_WAIT state
_, err = ioutil.ReadAll(resp.Body)
fmt.Println("Response status:", resp.Status)
}
}
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "helloyellow\n")
}
func headers(w http.ResponseWriter, req *http.Request) {
for name, headers := range req.Header {
for _, h := range headers {
fmt.Fprintf(w, "%v: %v\n", name, h)
}
}
}
func main() {
// This is a simple test server exposing 2 endpoint at port 8090 --> /hello and /headers
http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers)
http.ListenAndServe(":8090", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment