Skip to content

Commit

Permalink
RPC client improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
bbedward committed Jun 29, 2024
1 parent c7e1b00 commit b370a20
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
4 changes: 1 addition & 3 deletions services/moneybags/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ func main() {
userRepo := repository.NewUserService(db)
workRepo := repository.NewWorkService(db, userRepo)
paymentRepo := repository.NewPaymentService(db)
rppClient := &RPCClient{
Url: os.Getenv("RPC_URL"),
}
rppClient := NewRPCClient(os.Getenv("RPC_URL"))

// Do all of this within a transaction
err = db.Transaction(func(tx *gorm.DB) error {
Expand Down
25 changes: 21 additions & 4 deletions services/moneybags/rpcClient.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,26 @@ import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"io"
"net/http"
"time"

"github.com/bananocoin/boompow/libs/models"
"k8s.io/klog/v2"
)

type RPCClient struct {
Url string
Url string
httpClient *http.Client
}

func NewRPCClient(url string) *RPCClient {
return &RPCClient{
Url: url,
httpClient: &http.Client{
Timeout: time.Second * 30, // Set a timeout for all requests
},
}
}

type SendResponse struct {
Expand All @@ -23,18 +34,24 @@ type SendResponse struct {
func (client RPCClient) makeRequest(request interface{}) ([]byte, error) {
requestBody, _ := json.Marshal(request)
// HTTP post
resp, err := http.Post(client.Url, "application/json", bytes.NewBuffer(requestBody))
resp, err := client.httpClient.Post(client.Url, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
klog.Errorf("Error making RPC request %s", err)
return nil, err
}
defer resp.Body.Close()
// Try to decode+deserialize
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
klog.Errorf("Error decoding response body %s", err)
return nil, err
}

if resp.StatusCode != http.StatusOK {
klog.Errorf("Received non-200 response: %s", body)
return nil, errors.New("non-200 response received")
}

return body, nil
}

Expand Down

0 comments on commit b370a20

Please sign in to comment.