Skip to content

Commit 84ac6dd

Browse files
committed
Added PushJSONToRemote
1 parent e5ad8c6 commit 84ac6dd

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

tools.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package toolkit
22

33
import (
4+
"bytes"
45
"crypto/rand"
56
"encoding/json"
67
"errors"
@@ -299,3 +300,36 @@ func (t *Tools) ErrorJSON(w http.ResponseWriter, err error, status ...int) error
299300

300301
return t.WriteJSON(w, statusCode, payload)
301302
}
303+
304+
// PushJSONToRemote posts arbitrary data to some URL as JSON, and returns the response, status code, and error, if any.
305+
// The final parameter, client, is optional. If none is specified, we use the standard http.Client.
306+
func (t *Tools) PushJSONToRemote(uri string, data any, client ...*http.Client) (*http.Response, int, error) {
307+
// create json
308+
jsonData, err := json.Marshal(data)
309+
if err != nil {
310+
return nil, 0, err
311+
}
312+
313+
// check for custom http client
314+
httpClient := &http.Client{}
315+
if len(client) > 0 {
316+
httpClient = client[0]
317+
}
318+
319+
// build the request and set the header
320+
request, err := http.NewRequest("POST", uri, bytes.NewBuffer(jsonData))
321+
if err != nil {
322+
return nil, 0, err
323+
}
324+
request.Header.Set("Content-Type", "application/json")
325+
326+
// call the remote uri
327+
response, err := httpClient.Do(request)
328+
if err != nil {
329+
return nil, 0, err
330+
}
331+
defer response.Body.Close()
332+
333+
// send response back
334+
return response, response.StatusCode, nil
335+
}

tools_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,40 @@ import (
1717
"testing"
1818
)
1919

20+
type RoundTripFunc func(req *http.Request) *http.Response
21+
22+
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
23+
return f(req), nil
24+
}
25+
26+
func NewTestClient(fn RoundTripFunc) *http.Client {
27+
return &http.Client{
28+
Transport: fn,
29+
}
30+
}
31+
32+
func TestTools_PushJSONToRemote(t *testing.T) {
33+
client := NewTestClient(func(req *http.Request) *http.Response {
34+
// Test Request Parameters
35+
return &http.Response{
36+
StatusCode: http.StatusOK,
37+
Body: io.NopCloser(bytes.NewBufferString("ok")),
38+
Header: make(http.Header),
39+
}
40+
})
41+
42+
var testTools Tools
43+
var foo struct {
44+
Bar string `json:"bar"`
45+
}
46+
foo.Bar = "bar"
47+
48+
_, _, err := testTools.PushJSONToRemote("http://example.com/some/path", foo, client)
49+
if err != nil {
50+
t.Error("failed to call remote url:", err)
51+
}
52+
}
53+
2054
func TestTools_RandomString(t *testing.T) {
2155
var testTools Tools
2256

0 commit comments

Comments
 (0)