Skip to content

Commit

Permalink
added push Json to remote
Browse files Browse the repository at this point in the history
  • Loading branch information
rozdolsky33 committed Sep 28, 2024
1 parent 82404fa commit f4b84b8
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
32 changes: 32 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 @@ -281,3 +282,34 @@ func (t *Tools) ErrorJSON(w http.ResponseWriter, err error, status ...int) error

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

// PushJSONToRemote sends the given data as a JSON payload to the specified URI via HTTP POST using an optional custom HTTP client.
func (t *Tools) PushJSONToRemote(uri string, data interface{}, 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(http.MethodPost, 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
}
33 changes: 33 additions & 0 deletions tools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,39 @@ 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: ioutil.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.Errorf("failed to call remote url: %s", err)
}
}

// TestTools_RandomString verifies that the RandomString method returns a string of the correct length.
func TestTools_RandomString(t *testing.T) {
var testTools Tools
Expand Down

0 comments on commit f4b84b8

Please sign in to comment.