gitlab.com/ignitionrobotics/web/ign-go@v1.0.0-rc4/net/client.go (about) 1 package net 2 3 import ( 4 "context" 5 "errors" 6 "gitlab.com/ignitionrobotics/web/ign-go/encoders" 7 "reflect" 8 ) 9 10 var ( 11 // ErrNilValuesIO is returned when either the input or the output are nil. 12 ErrNilValuesIO = errors.New("nil input or output values") 13 14 // ErrOutputMustBePointer is returned if the output is not a pointer. 15 ErrOutputMustBePointer = errors.New("output must be a pointer") 16 ) 17 18 // Client is a generic wrapper for creating API clients with different encodings and transport layers 19 type Client struct { 20 // caller holds a transport layer implementation used to call to a certain endpoint. 21 caller Caller 22 23 // marshaller holds a encoders.Marshaller implementation to convert to and from an intermediate representation 24 // to transfer through the wire. 25 marshaller encoders.Marshaller 26 } 27 28 // Call calls the given endpoint with the given input as payload. If there's a response back from the endpoint, it will be 29 // stored in the output variable. 30 func (c *Client) Call(ctx context.Context, endpoint string, in, out interface{}) error { 31 if in == nil || out == nil { 32 return ErrNilValuesIO 33 } 34 if reflect.ValueOf(out).Kind() != reflect.Ptr { 35 return ErrOutputMustBePointer 36 } 37 38 body, err := c.marshaller.Marshal(in) 39 if err != nil { 40 return err 41 } 42 43 body, err = c.caller.Call(ctx, endpoint, body) 44 if err != nil { 45 return err 46 } 47 48 err = c.marshaller.Unmarshal(body, out) 49 if err != nil { 50 return err 51 } 52 53 return nil 54 } 55 56 // NewClient initializes a new Client using the given Caller and encoders.Marshaller. 57 func NewClient(caller Caller, serializer encoders.Marshaller) Client { 58 return Client{ 59 caller: caller, 60 marshaller: serializer, 61 } 62 }