restclient

package module
v0.0.0-...-bfd3f69 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 13, 2018 License: Apache-2.0 Imports: 13 Imported by: 9

README

restclient library

This library can be used in Golang projects to simplify and standardise interacting with ReST services.

GoDoc

How to use

Configuration

First define how to access the ReST service. This is done using restclient.Config Create a new config instance:

c := restclient.NewConfig()

You need to at least define an endpoint URL for the ReST service:

c.WithEndPoint("https://somehost:8080")

You can specify user name and password authentication details to this service (currently only basic authentication is supported):

c.WithUserId("userA").WithPassword("pa55word")

If the endpoint is connected to over TLS you can specify a signing certificate to trust for the connection. This can be done either by providing the path to a PEM format certificate file or a pointer to an x509.Certificate object.

c.WithCAFilePath("/path/to/trusted/cert.pem")
c.WithCACert(&x509.Certificate{})

A configuration can also be loaded from a file containing JSON formatted data. For example the JSON configuration file could contain:

{
  "EndPoint": "https://somehost:8080",
  "UserId": "userA",
  "Password": "pa55word",
  "TrustCACert": "/path/to/trusted/cert.pem"
}

It can be loaded with:

c := restclient.Load("/path/to/config.json")

Once the configuration has been completed it is recommended to call it's Validate method to check configuration is valid. For example:

if err := c.Validate(); err != nil {
        panic("Configuration is not valid")
}
Operation

For each operation you want to perform against the ReST service create a new instance of restclient.Operation. First create the Operation instance with the relevant method for the HTTP verb the ReST call requires:

o := restclient.NewGetOperation()
o := restclient.NewPostOperation()
o := restclient.NewPutOperation()
o := restclient.NewPatchOperation()

Define the path in the service the operation will call

o.WithPath("/some/api/path")

If a query string needs to be defined one of the following methods can be used. Note that if you are passing a string you need to first url encode it appropriately.

o.WithQueryDataString("something=value&somethingelse=value2")
o.WithQueryDataURLValues(url.Values{})

If posting data in the call is required it can be provided as either a string, byte array or url.Values with these methods.

o.WithBodyDataString("somedatatosend")
o.WithBodyDataByteArray([]byte{})
o.WithBodyDataURLValues(url.Values{})

If the call returns data you want to retrieve, define a struct that a JSON response will parse into. Create an instance of this struct and provide the pointer to the Operation instance:

type AWSCredentials struct {
	SecretAccessKey string    `json:"SecretAccessKey"`
	SessionToken    string    `json:"SessionToken"`
	Expiration      time.Time `json:"Expiration"`
	AccessKeyID     string    `json:"AccessKeyId"`
}
var d AWSCredentials
o.WithResponseTarget(&d)
Build the Request

With the operation object and a config object created the next step is to build the request:

req, err := restclient.BuildRequest(c, o)

Note: It would be usual to have one config object and multiple operation objects and multiple request object built from these.

Send the Request

Now we have the request we can send it to the service:

httpcode, err := restclient.Send(req)

Any response will be marshalled into the response target struct that you provided to the operation.

Example use

To see an example of this library being used see:

Improvements needed...

  • Logging
  • Tests for query string

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Send

func Send(r *Request) (httpCode *int, err error)

Send the request to the ReST service and marshal any response data into the struct defined in the Operation.

Types

type Config

type Config struct {
	UserId      *string `json:"UserId,omitempty"`
	Password    *string `json:"Password,omitempty"`
	EndPoint    *string
	TrustCACert *string
	HTTPClient  *http.Client `json:"-"`
	// contains filtered or unexported fields
}

A Config specifies the details needed to connect to a ReST service

func Load

func Load(cfgPath string) *Config

func NewConfig

func NewConfig() *Config

Create new, blank ReST client config

func (*Config) Validate

func (c *Config) Validate() (validateErr error)

func (*Config) WithCACert

func (c *Config) WithCACert(cert *x509.Certificate) *Config

Add a trusted x509 certificate to the configuration. If the ReST service implements TLS/SSL then certificates signed by this CA certificate will be trusted.

func (*Config) WithCACertPool

func (c *Config) WithCACertPool(cp *x509.CertPool) *Config

Add a trusted x509 certificate pool to the configuration. If the ReST service implements TLS/SSL then certificates signed by CA certificates in this pool will be trusted.

func (*Config) WithCAFilePath

func (c *Config) WithCAFilePath(caFilePath string) *Config

Add a trusted x509 certificate to the configuration by specifying a path to a PEM format certificate file. If the ReST service implements TLS/SSL then certificates signed by this CA certificate will be trusted.

func (*Config) WithEndPoint

func (c *Config) WithEndPoint(e string) *Config

Specify the URL endpoint of the ReST service in the form http(s)://hostname:port

func (*Config) WithHTTPClient

func (c *Config) WithHTTPClient(client http.Client) *Config

Override with a specific http.Client to be used for the connection to the ReST service.

func (*Config) WithPassword

func (c *Config) WithPassword(p string) *Config

Add a password to the config for basic authentication to the ReST service

func (*Config) WithUserId

func (c *Config) WithUserId(u string) *Config

Add a user ID to the config for basic authentication to the ReST service

type Operation

type Operation struct {
	// contains filtered or unexported fields
}

An Operation is the ReST service API operation to be made. It encapsulates the HTTP method to be used, the path to be called and data to be sent, both post and query string data. It also contains a point to a struct that will be the target to hold any response data from the ReST service.

func NewGetOperation

func NewGetOperation() (o *Operation)

Create an Operation that uses the GET verb against the ReST service.

func NewPatchOperation

func NewPatchOperation() (o *Operation)

Create an Operation that uses the PATCH verb against the ReST service.

func NewPostOperation

func NewPostOperation() (o *Operation)

Create an Operation that uses the POST verb against the ReST service.

func NewPutOperation

func NewPutOperation() (o *Operation)

Create an Operation that uses the PUT verb against the ReST service.

func (*Operation) WithBodyDataByteArray

func (o *Operation) WithBodyDataByteArray(d []byte) *Operation

Add some post data to the Operation by providing a byte array

func (*Operation) WithBodyDataString

func (o *Operation) WithBodyDataString(d string) *Operation

Add some post data to the Operation by providing a string

func (*Operation) WithBodyDataStruct

func (o *Operation) WithBodyDataStruct(d interface{}) *Operation

Add some post data to the Operation by providing a struct instance that will be marshaled into JSON

func (*Operation) WithBodyDataURLValues

func (o *Operation) WithBodyDataURLValues(d url.Values) *Operation

Add some post data to the Operation by providing a url.Values type

func (*Operation) WithPath

func (o *Operation) WithPath(p string) *Operation

Define the path of the ReST service to call.

func (*Operation) WithQueryDataString

func (o *Operation) WithQueryDataString(d string) *Operation

Add data to the query string of the Operation. This method is used to define this using a string. The string will need to be appropriately URL encoded

func (*Operation) WithQueryDataURLValues

func (o *Operation) WithQueryDataURLValues(d url.Values) *Operation

Add data to the query string of the Operation. This method is used to define this using a url.Values type.

func (*Operation) WithResponseTarget

func (o *Operation) WithResponseTarget(v interface{}) *Operation

Define the pointer to a struct that will be used to hold the response data from the ReST call. When the request is sent to the ReST service any response will be marshalled into this struct.

type Request

type Request struct {
	Config       *Config
	Operation    *Operation
	HTTPRequest  *http.Request
	HTTPResponse *http.Response
	StatusCode   int
}

A Request encapsulates the Config (how to connect to the ReST service) with the Operation (what to request)

func BuildRequest

func BuildRequest(c *Config, o *Operation) (r *Request, err error)

Build a Request and make it ready to send to the ReST service

type RequestBuilder

type RequestBuilder interface {
	NewRequest(*Config) error
	Process() error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL