Skip to content

Commit

Permalink
Added PushJSONToRemote
Browse files Browse the repository at this point in the history
  • Loading branch information
onattech committed Jan 12, 2023
1 parent e5ad8c6 commit 84ac6dd
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
34 changes: 34 additions & 0 deletions tools.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package toolkit

import (
"bytes"
"crypto/rand"
"encoding/json"
"errors"
Expand Down Expand Up @@ -299,3 +300,36 @@ func (t *Tools) ErrorJSON(w http.ResponseWriter, err error, status ...int) error

return t.WriteJSON(w, statusCode, payload)
}

// PushJSONToRemote posts arbitrary data to some URL as JSON, and returns the response, status code, and error, if any.
// The final parameter, client, is optional. If none is specified, we use the standard http.Client.
func (t *Tools) PushJSONToRemote(uri string, data any, client ...*http.Client) (*http.Response, int, error) {
// create json
jsonData, err := json.Marshal(data)
if err != nil {
return nil, 0, err
}

// check for custom http client
httpClient := &http.Client{}
if len(client) > 0 {
httpClient = client[0]
}

// build the request and set the header
request, err := http.NewRequest("POST", uri, bytes.NewBuffer(jsonData))
if err != nil {
return nil, 0, err
}
request.Header.Set("Content-Type", "application/json")

// call the remote uri
response, err := httpClient.Do(request)
if err != nil {
return nil, 0, err
}
defer response.Body.Close()

// send response back
return response, response.StatusCode, nil
}
34 changes: 34 additions & 0 deletions tools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,40 @@ import (
"testing"
)

type RoundTripFunc func(req *http.Request) *http.Response

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}

func NewTestClient(fn RoundTripFunc) *http.Client {
return &http.Client{
Transport: fn,
}
}

func TestTools_PushJSONToRemote(t *testing.T) {
client := NewTestClient(func(req *http.Request) *http.Response {
// Test Request Parameters
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString("ok")),
Header: make(http.Header),
}
})

var testTools Tools
var foo struct {
Bar string `json:"bar"`
}
foo.Bar = "bar"

_, _, err := testTools.PushJSONToRemote("http://example.com/some/path", foo, client)
if err != nil {
t.Error("failed to call remote url:", err)
}
}

func TestTools_RandomString(t *testing.T) {
var testTools Tools

Expand Down

0 comments on commit 84ac6dd

Please sign in to comment.