Skip to content

Instantly share code, notes, and snippets.

@ahndmal
Created March 25, 2022 18:42
Show Gist options
  • Save ahndmal/bdf58623beb7621dd048ac2fa7e9360d to your computer and use it in GitHub Desktop.
Save ahndmal/bdf58623beb7621dd048ac2fa7e9360d to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"time"
)
func httpClient() *http.Client {
client := &http.Client{Timeout: 10 * time.Second}
return client
}
func sendRequest(client *http.Client, method string) []byte {
endpoint := "https://httpbin.org/post"
values := map[string]string{"foo": "baz"}
jsonData, err := json.Marshal(values)
req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(jsonData))
if err != nil {
log.Fatalf("Error Occurred. %+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 should be re-used for further calls
c := httpClient()
response := sendRequest(c, http.MethodPost)
log.Println("Response Body:", string(response))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment