ravenTree

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2024 License: MIT Imports: 11 Imported by: 0

README

Raven Tree


Latest Version Coverage Status


Is a lightweight Go library designed to simplify HTTP requests by providing an easy-to-use interface, built-in support for various HTTP methods, accepting retry handling, and more.

Installation

To use can install it via go get:

go get github.com/AndresXLP/ravenTree

Usage

package main

import (
  "context"
  "fmt"
  "log"
  "net/http"
  "time"

  "github.com/AndresXLP/ravenTree"
)

func main() {
  tree := ravenTree.NewRavensTree()

  options := &ravenTree.Options{
    Host:        "http://localhost:8080",
    Path:        "/api/resource",
    Method:      http.MethodGet,
    QueryParams: map[string]string{"code": "123"},
    Headers:     map[string]string{"Authorization": "Bearer 1234"},
    Timeout:     5 * time.Second,
    RetryCount:  3,
    Backoff: ravenTree.NewBackoff(
      ravenTree.WithStrategy(ravenTree.Exponential),
      ravenTree.WithBackoffDelay(3*time.Second),
      ravenTree.WithMaxDelay(10*time.Second),
    ),
  }

  resp, err := tree.SendRaven(context.Background(), options)
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(resp.ParseBodyToString())
}


Methods Provided

SendRaven: This method sends an HTTP request based on the provided Options. It supports different HTTP methods such as GET, POST, PUT, DELETE, etc.

Body Management

The Body field in the Options struct can accept any type of data that can be marshaled into JSON. The library automatically handles the marshaling of the Body when sending the request.

Headers and Query Parameters

By default, the Content-Type header is set to application/json.

You can add additional headers and query parameters using the Headers and QueryParams fields in the Options struct.

Timeout and Retry Options
  • Timeout: Specifies the maximum duration for a request. If the request takes longer than this duration, it will be aborted, and an error will be returned.

  • RetryCount: Specifies the number of times to retry the request if it fails. This is useful for handling transient errors or network issues. The library will automatically retry the request up to the specified number of attempts.

Backoff Options

The Backoff struct defines the strategy for implementing backoff delays in retry operations with the following fields:

  • BackoffDelay: Specifies the duration to wait before the next retry.
  • MaxDelay: Specifies the maximum duration for backoff delays.
  • Strategy: Determines the type of backoff (Default, Linear, or Exponential).
Creating a New Backoff

Use the NewBackoff function to create a new Backoff with optional parameters:

  • If no options are provided, it defaults to:
    • BackoffDelay: 0 seconds
    • MaxDelay: 10 seconds
    • Strategy: Default

  • Note: If MaxDelay is set to a value less than BackoffDelay, MaxDelay will be updated to match BackoffDelay to ensure valid configuration.
Example Usage
package main

import (
	"time"

	"github.com/AndresXLP/ravenTree"
)

func main() {
	options := &ravenTree.Options{
		Backoff: ravenTree.NewBackoff(
			WithStrategy(Linear),
			WithBackoffDelay(2*time.Second),
			WithMaxDelay(30*time.Second),
		),
	}

}

Error Handling

Always check for errors after calling SendRaven. If the request fails, the error will provide information about what went wrong.

Thematic Inspiration

The name Raven Tree reflects the connection to the mystical ravens that serve as messengers in both Game of Thrones and Norse mythology, symbolizing communication, wisdom, and the passage of information.

Just as these ravens carry messages across great distances, Raven Tree aims to facilitate seamless communication between your application and external APIs.


Authors


Contributing

Contributions are welcome! Please open an issue or submit a pull request for any features or fixes you want to add.

License

The project is licensed under the MIT License

Documentation

Index

Constants

View Source
const (
	// Default sets BackoffDelay to 0 seconds.
	// This strategy does not impose any additional delay between retries.
	Default strategy = iota

	// Lineal sets BackoffDelay to 1 second and increases the delay linearly with each retry.
	// For example, the delays will be 1s, 2s, 3s, etc., until MaxDelay is reached.
	Lineal

	// Exponential sets BackoffDelay to 1 second and doubles the delay with each retry.
	// For example, the delays will be 1s, 2s, 4s, 8s, etc., until MaxDelay is reached.
	Exponential
)
View Source
const (
	HeaderContentType = "Content-Type"
	// MIMEApplicationJSON JavaScript Object Notation (JSON) https://www.rfc-editor.org/rfc/rfc8259
	MIMEApplicationJSON = "application/json"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Backoff added in v1.1.0

type Backoff struct {
	BackoffDelay time.Duration
	MaxDelay     time.Duration
	Strategy     strategy
}

Backoff defines the strategy for implementing backoff delays in retry operations. Fields:

  • BackoffDelay: Specifies the duration to wait before the next retry.
  • MaxDelay: Specifies the maximum duration to
  • Strategy: Determines the type of backoff (Default, Lineal, or Exponential).

func NewBackoff added in v1.1.0

func NewBackoff(opts ...BackoffOptions) *Backoff

NewBackoff creates a new Backoff with optional parameters.

If no options are provided, it defaults to: - BackoffDelay: 0 seconds - MaxDelay: 10 seconds - strategy: Default

If MaxDelay is set to a value less than BackoffDelay, MaxDelay will be updated to match BackoffDelay to ensure valid configuration.

func (*Backoff) Next added in v1.1.0

func (b *Backoff) Next()

Next applies the specified backoff strategy to wait before the next retry, adjusting the delay based on the strategy (Default, Lineal, or Exponential).

The delay will not exceed maxDelay.

type BackoffOptions added in v1.1.0

type BackoffOptions func(*Backoff)

func WithBackoffDelay added in v1.1.0

func WithBackoffDelay(delay time.Duration) BackoffOptions

WithBackoffDelay sets an initial backoff delay.

func WithMaxDelay added in v1.1.0

func WithMaxDelay(delay time.Duration) BackoffOptions

WithMaxDelay set the maximum backoff delay.

func WithStrategy added in v1.1.0

func WithStrategy(s strategy) BackoffOptions

WithStrategy sets the backoff strategy type (Default, Lineal, Exponential).

If s is not a valid strategy, the function will default to the Default strategy.

type ErrCollections added in v1.1.0

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

func (*ErrCollections) Add added in v1.1.0

func (ec *ErrCollections) Add(errString string)

func (*ErrCollections) CleanCollection added in v1.1.0

func (ec *ErrCollections) CleanCollection()

func (*ErrCollections) Error added in v1.1.0

func (ec *ErrCollections) Error() string

func (*ErrCollections) HasError added in v1.1.0

func (ec *ErrCollections) HasError() error

type Options

type Options struct {
	Host        string
	Path        string
	Method      string
	Body        interface{}
	QueryParams map[string]string
	Headers     map[string]string
	Timeout     time.Duration
	RetryCount  int
	Backoff     *Backoff
}

type Tree

type Tree interface {
	// SendRaven sends a raven to a specified URL using the provided Options.
	//
	// This method constructs an HTTP request based on the given context and Options.
	//
	// By default, it sets the Content-Type header to application/json.
	//
	// It sends the request using an HTTP client and returns a
	// WrapperResponse that encapsulates the HTTP response.
	//
	// Parameters:
	//   - ctx: A context.Context to control the request's lifecycle and manage timeouts.
	//   - opt: A pointer to an Options struct that contains the necessary configuration
	//     for the request.
	//
	// Returns:
	// - WrapperResponse: A wrapper around the HTTP response.
	// - error: An error if the request fails at any point, or nil if the request is successful.
	SendRaven(ctx context.Context, opt *Options) (WrapperResponse, error)
}

Tree defines the methods that any implementation of a RavenTree must provide.

The Tree interface requires a single method, SendRaven, which sends options based on the provided Options and returns a WrapperResponse.

func NewRavensTree

func NewRavensTree() Tree

NewRavensTree creates and returns a new instance of the RavenTree interface.

This function acts as a constructor for the RavenTree implementation, returning an instance of `raven`, a private struct that implements the `Tree` interface. The returned instance includes an internal `http.Client` configured with a default timeout.

Returns: - Tree: An object that implements the RavenTree interface with a pre-configured HTTP client.

type WrapperResponse

type WrapperResponse struct {
	*http.Response
}

func (*WrapperResponse) ParseBodyTo

func (w *WrapperResponse) ParseBodyTo(dest interface{}) error

ParseBodyTo parses the HTTP response body into the provided destination (dest).

This method reads the response body (w.Body) as a byte slice, then attempts to unmarshal the JSON content into the provided `dest` interface.

The response body (w.Body) is then restored so it can be read again later, if necessary.

Parameters:

  • dest (interface{}): A pointer to the destination where the parsed JSON from the response body will be stored. It can be a struct or map that matches the JSON structure.

Returns: - error: Returns an error if the reading of the body or the unmarshalling process fails.

func (*WrapperResponse) ParseBodyToString

func (w *WrapperResponse) ParseBodyToString() string

ParseBodyToString reads the HTTP response body and returns it as a string.

This method reads the entire response body (w.Body) into a byte slice, converts it to a string, and then restores the body so it can be read again later if needed.

Returns: - string: The response body as a string.

Jump to

Keyboard shortcuts

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