From 36e317c1c51bb07b8583157bd001da9ef890abec Mon Sep 17 00:00:00 2001 From: Brandon Berhent Date: Thu, 27 Jun 2024 08:00:48 -0400 Subject: [PATCH] Optimize RPC client --- server/main.go | 2 +- server/net/rpc_client.go | 35 +++++++++++++++++++++++++---------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/server/main.go b/server/main.go index 6b733e8..fbc2648 100644 --- a/server/main.go +++ b/server/main.go @@ -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 diff --git a/server/net/rpc_client.go b/server/net/rpc_client.go index 3f7b4d9..519c434 100644 --- a/server/net/rpc_client.go +++ b/server/net/rpc_client.go @@ -4,8 +4,9 @@ import ( "bytes" "encoding/json" "errors" - "io/ioutil" + "io" "net/http" + "time" "github.com/appditto/natricon/server/model" "github.com/appditto/natricon/server/utils" @@ -13,23 +14,37 @@ import ( ) 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