rest

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2024 License: MIT Imports: 20 Imported by: 0

README

REST Client

This is a README file for a REST client built using the Go programming language. The client provides a simple and efficient way to interact with RESTful APIs in Go.



Features

  • HTTP methods: GET, POST, PUT, DELETE
  • Query parameters
  • Request headers
  • Retry
  • CircuitBreaker Configuration
  • Proxy Configuration
  • TLS Configuration
  • Transport Layer Configuration
    • MaxIdle Connections
    • Connection Timeout
    • TLS Handshake Timeout
  • SSL Verification and Configuration
  • CA Certs Configuration
  • Error handling
    • ErrorOnHttpStatus : sets the list of status codes that can be considered failures

Installation

To install the REST client, use the following command:

go get oss.nandlabs.io/golly/clients/rest

Usage

To use the REST client in your Go project, you first need to import the package:

import "oss.nandlabs.io/golly/clients/rest"
HTTP Methods : Sending a GET Request
package main

import (
  "fmt"
  "oss.nandlabs.io/golly/clients/rest"
)

func main() {
  client := rest.NewClient()
  req := client.NewRequest("http://localhost:8080/api/v1/getData", "GET")
  res, err := client.Execute(req)
  if err != nil {
    // handle error
    fmt.Errorf("error executing request: %v", err)
  }
  // handle response
  fmt.Println(res)
}
Retry Configuration
package main

import (
  "fmt"
  "oss.nandlabs.io/golly/clients/rest"
)

func main() {
  client := rest.NewClient()
  req := client.NewRequest("http://localhost:8080/api/v1/getData", "GET")
  // maxRetries -> 3, wait -> 5 seconds
  client.Retry(3, 5)
  res, err := client.Execute(req)
  if err != nil {
    // handle error
    fmt.Errorf("error executing request: %v", err)
  }
  // handle response
  fmt.Println(res)
}
CircuitBreaker Configuration
package main

import (
  "fmt"
  "oss.nandlabs.io/golly/clients/rest"
)

func main() {
  client := rest.NewClient()
  req := client.NewRequest("http://localhost:8080/api/v1/getData", "GET")
  client.UseCircuitBreaker(1, 2, 1, 3)
  res, err := client.Execute(req)
  if err != nil {
    // handle error
    fmt.Errorf("error executing request: %v", err)
  }
  // handle response
  fmt.Println(res)
}
Proxy Configuration
package main

import (
  "fmt"
  "oss.nandlabs.io/golly/clients/rest"
)

func main() {
  client := rest.NewClient()
  req := client.NewRequest("http://localhost:8080/api/v1/getData", "GET")
  err := client.SetProxy("proxy:url", "proxy_user", "proxy_pass")
  if err != nil {
	  fmt.Errorf("unable to set proxy: %v", err)
  }
  res, err := client.Execute(req)
  if err != nil {
    // handle error
    fmt.Errorf("error executing request: %v", err)
  }
  // handle response
  fmt.Println(res)
}
TLS Configuration
package main

import (
  "crypto/tls"
  "fmt"
  "oss.nandlabs.io/golly/clients/rest"
)

func main() {
  client := rest.NewClient()
  req := client.NewRequest("http://localhost:8080/api/v1/getData", "GET")
  client, err := client.SetTLSCerts(tls.Certificate{})
  if err != nil {
    fmt.Errorf("error adding tls certificates: %v", err)
  }
  res, err := client.Execute(req)
  if err != nil {
    // handle error
    fmt.Errorf("error executing request: %v", err)
  }
  // handle response
  fmt.Println(res)
}
SSL Verification and CA Certs Configuration
package main

import (
  "fmt"
  "oss.nandlabs.io/golly/clients/rest"
)

func main() {
  client := rest.NewClient()
  req := client.NewRequest("http://localhost:8080/api/v1/getData", "GET")
  client, err := client.SSlVerify(true)
  if err != nil {
	  fmt.Errorf("unable to set ssl verification, %v", err)
  }
  client, err = client.SetCACerts("./test-cert.pem", "./test-cert-2.pem")
  if err != nil {
    fmt.Errorf("error adding ca certificates: %v", err)
  }
  res, err := client.Execute(req)
  if err != nil {
    // handle error
    fmt.Errorf("error executing request: %v", err)
  }
  // handle response
  fmt.Println(res)
}

Documentation

Overview

Package rest provides a set of utilities for making RESTful API calls.

This package includes functions for sending HTTP requests, handling responses, and managing authentication and authorization headers.

Example usage:

// Create a new REST client
client := rest.NewClient()

// Set the base URL for the API
client.SetBaseURL("https://api.example.com")

// Set the authentication token
client.SetAuthToken("YOUR_AUTH_TOKEN")

// Send a GET request
response, err := client.Get("/users")
if err != nil {
    log.Fatal(err)
}

// Print the response body
fmt.Println(response.Body)

// Close the response body
response.Close()

For more information and examples, please refer to the package documentation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client represents a REST client.

func NewClient

func NewClient() *Client

NewClient creates a new REST client with default values.

func (*Client) AddCodecOption

func (c *Client) AddCodecOption(k string, v interface{}) *Client

AddCodecOption sets the option for the codec to be used.

func (*Client) Close

func (c *Client) Close() (err error)

Close closes all idle connections that are available.

func (*Client) ErrorOnHttpStatus

func (c *Client) ErrorOnHttpStatus(statusCodes ...int) *Client

ErrorOnHttpStatus sets the list of status codes that can be considered failures. This is useful for QualityOfService features like CircuitBreaker.

func (*Client) Execute

func (c *Client) Execute(req *Request) (res *Response, err error)

Execute sends the client request and returns the response object.

func (*Client) IdleTimeout

func (c *Client) IdleTimeout(t uint) *Client

IdleTimeout sets the maximum amount of time a connection can stay idle (keep-alive) before closing itself.

func (*Client) MaxIdle

func (c *Client) MaxIdle(maxIdleConn int) *Client

MaxIdle sets the maximum number of idle connections that can stay idle (keep-alive).

func (*Client) MaxIdlePerHost

func (c *Client) MaxIdlePerHost(maxIdleConnPerHost int) *Client

MaxIdlePerHost sets the maximum number of idle connections that can stay idle (keep-alive) for a given hostname.

func (*Client) NewRequest

func (c *Client) NewRequest(url, method string) *Request

NewRequest creates a new request object for the client.

func (*Client) ReqTimeout

func (c *Client) ReqTimeout(t uint) *Client

ReqTimeout sets the overall client timeout for a request. The default value is 60 seconds.

func (*Client) Retry

func (c *Client) Retry(maxRetries, wait int) *Client

Retry sets the maximum number of retries and wait interval in seconds between retries. The client does not retry by default. If retry configuration is set along with UseCircuitBreaker, then the retry config is ignored.

func (*Client) SSlVerify

func (c *Client) SSlVerify(verify bool) (*Client, error)

SSlVerify sets the SSL verify value.

func (*Client) SetCACerts

func (c *Client) SetCACerts(caFilePath ...string) (*Client, error)

SetCACerts sets the CA certificates for the client.

func (*Client) SetProxy

func (c *Client) SetProxy(proxyUrl, user, password string) (err error)

SetProxy sets the proxy configuration for the client.

func (*Client) SetTLSCerts

func (c *Client) SetTLSCerts(certs ...tls.Certificate) (*Client, error)

SetTLSCerts sets the client certificate key pair for the client.

func (*Client) UseCircuitBreaker

func (c *Client) UseCircuitBreaker(failureThreshold, successThreshold uint64, maxHalfOpen, timeout uint32) *Client

UseCircuitBreaker sets the circuit breaker configuration for this client. The circuit breaker pattern has higher precedence than the retry pattern. If both are set, then the retry configuration is ignored.

func (*Client) UseEnvProxy

func (c *Client) UseEnvProxy(urlParam, userParam, passwdParam string) (err error)

UseEnvProxy ensures that the proxy settings are loaded using environment parameters.

type MultipartFile

type MultipartFile struct {
	ParamName string
	FilePath  string
}

type Request

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

Request struct holds the http Request for the rest client

func (*Request) AddFormData

func (r *Request) AddFormData(k string, v ...string) *Request

AddFormData function adds the form data with the name specified by k list of values in order as specified in v If the key does not exist then it creates a new form data by calling url.Values.Set() function on the first key and the value Setting form data will have precedence over to setting body directly.

func (*Request) AddHeader

func (r *Request) AddHeader(k string, v ...string) *Request

func (*Request) AddPathParam

func (r *Request) AddPathParam(k string, v string) *Request

AddPathParam function adds the path parameter with key as the name of the parameter and v as the value of the parameter that needs to be replaced

func (*Request) AddQueryParam

func (r *Request) AddQueryParam(k string, v ...string) *Request

AddQueryParam function adds the query parameter with the name specified by k list of values in order as specified in v If the key does not exist then it creates a new form data by calling url.Values.Set() function passing the first key and value

func (*Request) Method

func (r *Request) Method() string

Method function prints the current method for this Request

func (*Request) SeBodyReader

func (r *Request) SeBodyReader(reader io.Reader) *Request

func (*Request) SetBody

func (r *Request) SetBody(v interface{}) *Request

func (*Request) SetContentType

func (r *Request) SetContentType(contentType string) *Request

func (*Request) SetMultipartFiles

func (r *Request) SetMultipartFiles(files ...*MultipartFile) *Request

type Response

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

func (*Response) Decode

func (r *Response) Decode(v interface{}) (err error)

Decode Function decodes the response body to a suitable object. The format of the body is determined by Content-Type header in the response

func (*Response) GetError

func (r *Response) GetError() (err error)

GetError gets the error with status code and value

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess determines if the response is a success response

func (*Response) Raw

func (r *Response) Raw() *http.Response

Raw Provides the backend raw response

func (*Response) Status

func (r *Response) Status() string

Status Provides status text of the http response

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode provides the status code of the response

Jump to

Keyboard shortcuts

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