Skip to content

Commit

Permalink
Optimize RPC client
Browse files Browse the repository at this point in the history
  • Loading branch information
bbedward committed Jun 27, 2024
1 parent 7d16d3f commit 36e317c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
2 changes: 1 addition & 1 deletion server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func main() {
var rpcClient *net.RPCClient
if *rpcUrl != "" {
glog.Infof("RPC Client configured at %s", *rpcUrl)
rpcClient = &net.RPCClient{Url: *rpcUrl}
rpcClient = net.NewRPCClient(*rpcUrl)
}

// Setup libvips
Expand Down
35 changes: 25 additions & 10 deletions server/net/rpc_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,47 @@ import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"io"
"net/http"
"time"

"github.com/appditto/natricon/server/model"
"github.com/appditto/natricon/server/utils"
"github.com/golang/glog"
)

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
},
}
}

// Base request
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))
func (client *RPCClient) makeRequest(request interface{}) ([]byte, error) {
requestBody, err := json.Marshal(request)
if err != nil {
return nil, err
}
resp, err := client.httpClient.Post(client.Url, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
glog.Errorf("Error making RPC request %s", err)
return nil, err
}
defer resp.Body.Close()
// Try to decode+deserialize
body, err := ioutil.ReadAll(resp.Body)

if resp.StatusCode != http.StatusOK {
return nil, errors.New("non-200 response from server")
}

body, err := io.ReadAll(resp.Body)
if err != nil {
glog.Errorf("Error decoding response body %s", err)
return nil, err
}
return body, nil
Expand Down

0 comments on commit 36e317c

Please sign in to comment.