Created
March 25, 2022 18:42
-
-
Save ahndmal/bdf58623beb7621dd048ac2fa7e9360d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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