If anyone is still finding answers on how to do it, this is how I am doing it.
package main
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"time"
)
func httpClient() *http.Client {
client := &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: 20,
},
Timeout: 10 * time.Second,
}
return client
}
func sendRequest(client *http.Client, method string) []byte {
endpoint := "https://httpbin.org/post"
req, err := http.NewRequest(method, endpoint, bytes.NewBuffer([]byte("Post this data")))
if err != nil {
log.Fatalf("Error Occured. %+v", err)
}
response, err := client.Do(req)
if err != nil {
log.Fatalf("Error sending request to API endpoint. %+v", err)
}
// Close the connection to reuse it
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatalf("Couldn't parse response body. %+v", err)
}
return body
}
func main() {
c := httpClient()
response := sendRequest(c, http.MethodPost)
log.Println("Response Body:", string(response))
}
Go Playground: https://play.golang.org/p/cYWdFu0r62e
In summary, I am creating a different method to create an HTTP client and assigning it to a variable, and then using it to make requests.
Note the
defer response.Body.Close()
This will close the connection after the request is complete at the end of the function execution and you can reuse the client as many times.
If you want to send a request in a loop call the function that sends the request in a loop.
If you want to change anything in the client transport configuration, like add proxy config, make a change in the client config.
Hope this will help someone.