Skip to content

Commit

Permalink
adds HttpPutJSON() and HttpPostJSON() (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
jritsema authored Oct 22, 2022
1 parent bfeb449 commit b49cc3f
Showing 1 changed file with 52 additions and 2 deletions.
54 changes: 52 additions & 2 deletions json.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gotoolbox

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
Expand Down Expand Up @@ -31,19 +32,68 @@ func ReadJSONFile(fileName string) (map[string]string, error) {
// HttpGetJSON fetches the contents of the given URL
// and decodes it as JSON into the given result,
// which should be a pointer to the expected data.
// returns an error if http response code is not 200
func HttpGetJSON(url string, result interface{}) error {

resp, err := http.Get(url)
if err != nil {
return fmt.Errorf("cannot fetch URL %q: %v", url, err)
return fmt.Errorf("cannot fetch URL %q: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected http GET status: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
return fmt.Errorf("cannot decode JSON: %v", err)
return fmt.Errorf("cannot decode JSON: %w", err)
}
return nil
}

// HttpPutJSON encodes a struct as JSON and
// HTTP PUTs it to the specified endpoint
// returns an error if http response code is not 200
func HttpPutJSON(url string, o interface{}) error {

payload := new(bytes.Buffer)
json.NewEncoder(payload).Encode(o)
req, err := http.NewRequest(http.MethodPut, url, payload)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("unexpected http PUT error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected http PUT status: %s", resp.Status)
}
return nil
}

// HttpPostJSON encodes a struct as JSON and
// HTTP POSTs it to the specified endpoint
// returns an error if http response code does not match specified
func HttpPostJSON(url string, o interface{}, httpStatusCodeToCheck int) error {

payload := new(bytes.Buffer)
json.NewEncoder(payload).Encode(o)
req, err := http.NewRequest(http.MethodPost, url, payload)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("unexpected http PUT error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != httpStatusCodeToCheck {
return fmt.Errorf("unexpected http POST status: %s", resp.Status)
}
return nil
}

0 comments on commit b49cc3f

Please sign in to comment.