restclient

package
v6.7.4 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2023 License: Apache-2.0 Imports: 9 Imported by: 2

README

REST Client

This package provides a set of services and mocks for working with and testing REST services. An interface is provided to abstract the type of data you work with, and a concrete JSON-data implementation is provided.

HTTPClientInterface

HTTPClientInterface provides an interface to the Go HTTP client. This allows your services to mock HTTP interactions for unit testing.

type HTTPClientInterface interface {
	Do(req *http.Request) (*http.Response, error)
}

As you can see this interface matches the Go http.Client struct, allowing you to use it to fulfill services that depend on the HTTPClientInterface.

JSONClient

JSONClient is used to communicate with REST APIs that deal with JSON inputs and outputs. This service implements the RESTClient interface.

httpClient := &http.Client{} // Here you could use MockHTTPClient for unit tests

config := restclient.JSONClientConfig{
  BaseURL: "http://localhost:8080",
  DebugMode: false,
  HTTPClient: httpClient,
  Logger: logrus.New().WithField("who", "restClient"),
}

client := restclient.NewJSONClient(config)

If you want your requests to include an authorization header return a new instance by calling WithAuthorization. Continuing from the code sample above...

client := client.WithAuthorization("Bearer " + token)
DELETE

DELETE performs an HTTP DELETE operation. You provide a path, which should exclude the TLD, as this is defined in BaseURL.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

successResponse := SuccessStruct{}
errorResponse := ErrorStruct{}

response, err := client.DELETE("/thing", &successResponse, &errorResponse)

if err != nil {
	// Handle the error here
}

if response.StatusCode > 299 {
	// Uh oh, non-success response. errorResponse contains whatever
	// JSON came back
}

// successResponse contains whatever JSON came back from success
GET

GET performs an HTTP GET operation. You provide a path, which should exclude the TLD, as this is defined in BaseURL.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

successResponse := SuccessStruct{}
errorResponse := ErrorStruct{}

response, err := client.GET("/thing", &successResponse, &errorResponse)

if err != nil {
	// Handle the error here
}

if response.StatusCode > 299 {
	// Uh oh, non-success response. errorResponse contains whatever
	// JSON came back
}

// successResponse contains whatever JSON came back from success
NewMultipartWriter

NewMultipartWriter returns MultipartWriter component configured with the same base URL and authorization information as its parent JSONClient. This component is used to POST/PUT multipart forms. This is useful, for example, in performing operations like file uploads.

successResponse := SuccessStruct{}
errorResponse := ErrorStruct{}
fp, _ := os.Open("/path/to/file")

body := SomeStruct{
	SomeKey1: "somevalue1",
	SomeKey2: 2,
}

defer fp.Close()

multipartWriter := client.NewMultipartWriter()

_ = multipartWriter.AddField("field1", body)
_ = multipartWriter.AddFile("file", "filenameHere", fp)

// Doing a POST here. We also have PUT
response, err = multipartWriter.POST("/thing", &successResponse, &errorResponse)

if err != nil {
	// Handle the error here
}

if response.StatusCode > 299 {
	// Non-200 response. Do someething about it
}
POST

POST performs an HTTP POST operation. You provide a path, which should exclude the TLD, as this is defined in BaseURL. The body of the post is an interface, allowing you to pass whatever you wish, and it will be serialized to JSON.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

successResponse := SuccessStruct{}
errorResponse := ErrorStruct{}

body := SomeStruct{
	SomeKey1: "somevalue1",
	SomeKey2: 2,
}

response, err := client.POST("/thing", body, &successResponse, &errorResponse)

if err != nil {
	// Handle the error here
}

if response.StatusCode > 299 {
	// Uh oh, non-success response. errorResponse contains whatever
	// JSON came back
}

// successResponse contains whatever JSON came back from success
PUT

PUT performs an HTTP PUT operation. You provide a path, which should exclude the TLD, as this is defined in BaseURL. The body of the put is an interface, allowing you to pass whatever you wish, and it will be serialized to JSON.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

successResponse := SuccessStruct{}
errorResponse := ErrorStruct{}

body := SomeStruct{
	SomeKey1: "somevalue1",
	SomeKey2: 2,
}

response, err := client.PUT("/thing", body, &successResponse, &errorResponse)

if err != nil {
	// Handle the error here
}

if response.StatusCode > 299 {
	// Uh oh, non-success response. errorResponse contains whatever
	// JSON came back
}

// successResponse contains whatever JSON came back from success
WithAuthorization

WithAuthorization returns a copy of this JSONClient with the Authorization header set. Subsequent HTTP requests will send Authorization: <auth>, with auth being whatever you set in the string argument.

httpClient := &http.Client{} // Here you could use MockHTTPClient for unit tests

config := restclient.JSONClientConfig{
  BaseURL: "http://localhost:8080",
  DebugMode: false,
  HTTPClient: httpClient,
  Logger: logrus.New().WithField("who", "restClient"),
}

client := restclient.NewJSONClient(config)
client := client.WithAuthorization("Bearer " + token)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HTTPClient

type HTTPClient struct {
	*http.Client
}

HTTPClient implements methods as a wrapper over the Go HttpClient

func (*HTTPClient) Do

func (h *HTTPClient) Do(req *http.Request) (*http.Response, error)

Do executes this HTTP request

func (*HTTPClient) SetTransport

func (h *HTTPClient) SetTransport(transport *http.Transport)

SetTransport sets the transport information for this HTTP client

type HTTPClientInterface

type HTTPClientInterface interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClientInterface is an interface over the Go HttpClient

type JSONClient

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

JSONClient provides a set of methods for working with RESTful endpoints that accept and return JSON data

func NewJSONClient

func NewJSONClient(config JSONClientConfig) JSONClient

NewJSONClient creates a new JSON-based REST client

func (JSONClient) DELETE

func (c JSONClient) DELETE(path string, successReceiver, errorReceiver interface{}) (*http.Response, error)

DELETE performs an HTTP DELETE operation. You provide a path, which should exclude the TLD, as this is defined in BaseURL. If your request requires authorization call WithAuthorization first, then DELETE.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

func (JSONClient) GET

func (c JSONClient) GET(path string, successReceiver, errorReceiver interface{}) (*http.Response, error)

GET performs an HTTP GET operation. You provide a path, which should exclude the the TLD, as this is defined in BaseURL. If your request requires authorization call WithAuthorization first, then GET.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

func (JSONClient) NewMultipartWriter added in v6.1.0

func (c JSONClient) NewMultipartWriter() *MultipartWriter

NewMultipartWriter returns a MultipartWriter. This is used to POST and PUT multipart forms. Use this when you need to POST or PUT files, for example.

func (JSONClient) POST

func (c JSONClient) POST(path string, body, successReceiver, errorReceiver interface{}) (*http.Response, error)

POST performs an HTTP POST operation. You provide a path, which should exclude the TLD, as this is defined in BaseURL. If your request requires authorization call WithAuthorization first, then POST.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

func (JSONClient) PUT

func (c JSONClient) PUT(path string, body, successReceiver, errorReceiver interface{}) (*http.Response, error)

PUT performs an HTTP PUT operation. You provide a path, which should exclude the the TLD, as this is defined in BaseURL. If your request requires authorization call WithAuthorization first, then PUT.

If some type of error occurs when creating the request, executing the request, or unmarshalling the response, err will be populated. The http.Response is returned so callers can inspect the status.

func (JSONClient) WithAuthorization

func (c JSONClient) WithAuthorization(auth string) RESTClient

WithAuthorization returns an instance of RESTClient with an authorization header set

type JSONClientConfig added in v6.3.0

type JSONClientConfig struct {
	BaseURL         string
	DebugMode       bool
	HTTPClient      HTTPClientInterface
	Logger          *logrus.Entry
	CustomHeaders   map[string]string
	OmitContentType bool
}

JSONClientConfig is used to configure a JSONClient struct

type MockHTTPClient

type MockHTTPClient struct {
	DoFunc           func(req *http.Request) (*http.Response, error)
	SetTransportFunc func(transport *http.Transport)
}

MockHTTPClient is a mock HTTP client

func (*MockHTTPClient) Do

func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error)

Do mocks the HTTP Do method

func (*MockHTTPClient) SetTransport

func (m *MockHTTPClient) SetTransport(transport *http.Transport)

SetTransport mocks the SetTransport method

type MockRESTClient

type MockRESTClient struct {
	DELETEFunc             func(path string, successReceiver, errorReceiver interface{}) (bool, error)
	GETFunc                func(path string, successReceiver, errorReceiver interface{}) (bool, error)
	NewMultipartWriterFunc func() *MultipartWriter
	POSTFunc               func(path string, body, successReceiver, errorReceiver interface{}) (bool, error)
	PUTFunc                func(path string, body, successReceiver, errorReceiver interface{}) (bool, error)
	WithAuthorizationFunc  func(auth string) RESTClient
}

MockRESTClient is a mock for RESTClient

func (MockRESTClient) DELETE

func (m MockRESTClient) DELETE(path string, successReceiver, errorReceiver interface{}) (bool, error)

DELETE is a mock method

func (MockRESTClient) GET

func (m MockRESTClient) GET(path string, successReceiver, errorReceiver interface{}) (bool, error)

GET is a mock method

func (MockRESTClient) NewMultipartWriter added in v6.1.0

func (m MockRESTClient) NewMultipartWriter() *MultipartWriter

NewMultipartWriter is a mock method

func (MockRESTClient) POST

func (m MockRESTClient) POST(path string, body, successReceiver, errorReceiver interface{}) (bool, error)

POST is a mock method

func (MockRESTClient) PUT

func (m MockRESTClient) PUT(path string, body, successReceiver, errorReceiver interface{}) (bool, error)

PUT is a mock method

func (MockRESTClient) WithAuthorization

func (m MockRESTClient) WithAuthorization(auth string) RESTClient

WithAuthorization is a mock method

type MultipartWriter added in v6.1.0

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

func NewMultipartWriter added in v6.1.0

func NewMultipartWriter(config MultipartWriterConfig) *MultipartWriter

NewMultipartWriter creates a new MultipartWriter

func (*MultipartWriter) AddField added in v6.1.0

func (mw *MultipartWriter) AddField(name string, body interface{}) error

AddField adds a field to this multipart form. It accepts two types: string, json.Marshaler. For the latter, this would be any struct or type that implements the json.Marshaler interface.

func (*MultipartWriter) AddFile added in v6.1.0

func (mw *MultipartWriter) AddFile(name, fileName string, fileContents io.Reader) error

AddFile adds a file to this multipart form.

func (*MultipartWriter) POST added in v6.1.0

func (mw *MultipartWriter) POST(path string, successReceiver, errorReceiver interface{}) (*http.Response, error)

POST sends a multipart form via POST. The fields being sent should be added prior to calling POST by using the AddField and AddFile methods.

func (*MultipartWriter) PUT added in v6.1.0

func (mw *MultipartWriter) PUT(path string, successReceiver, errorReceiver interface{}) (*http.Response, error)

PUT sends a multipart form via PUT. The fields being sent should be added prior to calling PUT by using the AddField and AddFile methods.

type MultipartWriterConfig added in v6.3.0

type MultipartWriterConfig struct {
	Authorization string
	BaseURL       string
	DebugMode     bool
	HTTPClient    HTTPClientInterface
	Logger        *logrus.Entry
}

type RESTClient

type RESTClient interface {
	DELETE(path string, successReceiver, errorReceiver interface{}) (*http.Response, error)
	GET(path string, successReceiver, errorReceiver interface{}) (*http.Response, error)
	NewMultipartWriter() *MultipartWriter
	POST(path string, body, successReceiver, errorReceiver interface{}) (*http.Response, error)
	PUT(path string, body, successReceiver, errorReceiver interface{}) (*http.Response, error)
	WithAuthorization(auth string) RESTClient
}

RESTClient defines an interface for working with RESTful endpoints

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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