fallback

package module
v0.0.0-...-779b186 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2015 License: MIT Imports: 5 Imported by: 0

README

Image of insidethecpu

Go Fallback Package

Build Status godoc

Package fallback enhances the durability of your API by automatically recovering from connectivity failure. It achieves this by providing an enhanced degree of redundancy to HTTP requests, introducing a Chain of Responsibility, consisting of a series of fallback HTTP requests designed to augment an initial HTTP request. Should the initial HTTP request fail, the next fallback HTTP request in the chain will execute.

Any number of fallback HTTP requests can be chained sequentially. Redundancy is achieved by executing each fallback HTTP request in a recursive manner until one of the requests succeeds, or all requests fail.

Icon

Installation

go get github.com/daishisystems/fallback

Sample Code

package main

import (
	"fmt"
	"github.com/daishisystems/fallback"
)

func main() {

	// BasicResponse represents the response issued from the first successful
	// HTTP request, if applicable.
	type BasicResponse struct {
		Text   string
		Detail string
	}

	// BasicError represents the error issued from the last unsuccessful
	// HTTP request, if applicable.
	type BasicError struct {
		Code    int
		Message string
	}

	//
	type PostBody struct {
		Name   string
		Amount int
	}

	basicResponse := &BasicResponse{}
	basicError := &BasicError{}

	postBody := PostBody{
		"Random", 100,
	}

	passPath := "http://demo7227109.mockable.io/get-basic"
	failPath2 := "http://demo7227109.mockable.io/fail-basic"
	failPath1 := "http://demo7227109.mockable.io/fail-basic-post"

	connectionManager := fallback.ConnectionManager{}

	// This Connection will execute last, and will succeed.
	passBuilder := fallback.NewConnectionBuilder("PASS", "GET", passPath, true,
		nil, nil, &basicResponse, &basicError, nil)
	connectionManager.CreateConnection(passBuilder)

	// This Connection will be the 2nd Connection to execute, and will fail.
	failBuilder2 := fallback.NewConnectionBuilder("FAIL2", "POST", failPath2,
		true, nil, nil, &basicResponse, &basicError, passBuilder.Connection)
	connectionManager.CreateConnection(failBuilder2)

	//This Connection will be the 1st Connection to execute, and will fail.
	failBuilder1 := fallback.NewConnectionBuilder("FAIL1", "POST", failPath1,
		true, postBody, nil, &basicResponse, &basicError,
		failBuilder2.Connection)
	connectionManager.CreateConnection(failBuilder1)

	// Each Connection will be invoked in a recursive manner until a
	// Connection succeeds, or all Connections fail. Please refer to the Chain
	// of Responsibility design for more information.
	statusCode, err := failBuilder1.Connection.ExecuteHTTPRequest()
	if err != nil {
		panic(err)
	}

	fmt.Printf("HTTP status code: %d\n", statusCode)
	fmt.Printf("Text: %s\n", basicResponse.Text)
	fmt.Printf("Detail: %s", basicResponse.Detail)
}

Contact the Developer

Please reach out and contact me for questions, suggestions, or to just talk tech in general.

RSSTwitterLinkedInYouTube

Documentation

Overview

Package fallback enhances the durability of your API by automatically recovering from connectivity failure. It achieves this by providing an enhanced degree of redundancy to HTTP requests, introducing a Chain of Responsibility, consisting of a series of fallback HTTP requests designed to augment an initial HTTP request. Should the initial HTTP request fail, the next fallback HTTP request in the chain will execute.

Any number of fallback HTTP requests can be chained sequentially. Redundancy is achieved by executing each fallback HTTP request in a recursive manner until one of the requests succeeds, or all requests fail.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Connecter

type Connecter interface {
	ExecuteHTTPRequest() (int, error)
}

Connecter represents the Handler abstraction in the Chain of Responsibility that consists of a series of fallback HTTP requests. It provides a contract which defines the prerequisites that implementations must adhere to in order to take part in the chain.

type Connection

type Connection struct {
	Name, Method, Path  string
	Body                []byte
	Headers             map[string]string
	Output, CustomError interface{}
	Fallback            Connecter
	Logger              Logger
}

Connection represents a Concrete Handler implementation in the Chain of Responsibility that consists of a series of fallback HTTP requests. Consuming clients can utilise this class directly, or provide custom implementations derived from Connecter.

Name: The name used to describe the Connection

Method: The HTTP Verb (GET, POST, PUT, etc.)

Path: The HTTP URI

Body: The HTTP request Body

Headers: The HTTP request Headers

Output: A custom struct that represents a deserialised object returned as result of a successful HTTP request

CustomError: A custom struct that represents a deserialised object returned as result of an unsuccessful HTTP request

Fallback: The next link in the Chain of Responsibility. Fallback represents an underlying HTTP request that will be invoked in the event of failure during execution of this HTTP request

Logger: Custom Logger implementations that publish events in the event of any Fallback component failing to execute a HTTP request.

func NewConnection

func NewConnection(name, method, path string, body []byte,
	headers map[string]string, output, customError interface{},
	fallback Connecter, logger Logger) *Connection

NewConnection returns a new Connection instance based on the specified metadata pertaining to Connection.

func (Connection) ExecuteHTTPRequest

func (connection Connection) ExecuteHTTPRequest() (int, error)

ExecuteHTTPRequest represents a Chain of Responsibility consisting of a series of fallback HTTP requests that augment an initial HTTP request. Should the initial HTTP request fail, the next fallback HTTP request in the chain will execute. Any number of fallback HTTP requests can be chained sequentially. ExecuteHTTPRequest initially attempts to construct a HTTP connection. Should this fail, the process flow shifts to any fallback method applied to Connection. If no fallback method is specified, the method returns.

Unreachable URIs will yield a HTTP 503 response. Invalid URIs will yield a HTTP 400 response. Neither response will yield a response body.

It is assumed that successful HTTP requests will contain a HTTP Response Body suitable for parsing and applicable to Connection.Output. The HTTP Response Body will be deserialised to Connection.Output, and the method will return the HTTP status code in such cases. If the HTTP Response Body is not set, or cannot be deserialised to Connection.Output, an error is returned along with the HTTP status code.

It is assumed that failed HTTP requests that yield HTTP status codes other than 400 or 503 will contain a HTTP Response Body suitable for parsing, and applicable to Connection.CustomError in terms of deserialization. If no fallback method is specified, the HTTP Response Body will be deserialised to Connection.CustomError, and the method will return the HTTP status code. Otherwise, fallback will occur; the process flow will recursively fall back to each underlying fallback Connection mechanism until a successful attempt is established, or all attempts fail. If the HTTP Response Body is not set, or cannot be deserialised to Connection.CustomError, an error is returned along with the HTTP status code.

type ConnectionBuilder

type ConnectionBuilder struct {
	Connection *Connection
	// contains filtered or unexported fields
}

ConnectionBuilder represents a Builder-pattern based means of constructing Connection instances.

func NewConnectionBuilder

func NewConnectionBuilder(name, method, path string, returnsJSON bool,
	body, output, customError interface{}, headers map[string]string,
	fallback Connecter, logger Logger) *ConnectionBuilder

NewConnectionBuilder returns a new ConnectionBuilder instance based on the specified metadata pertaining to ConnectionBuilder.

type ConnectionManager

type ConnectionManager struct{}

ConnectionManager represents the Director structure that applies to ConnectionBuilder when creating Connection instances.

func (*ConnectionManager) CreateConnection

func (manager *ConnectionManager) CreateConnection(builder *ConnectionBuilder)

CreateConnection represents the constructor method that applies to ConnectionBuilder when creating Connection instances. It invokes each relevant construction method on builder in order to yield a complete Connection instance.

type Logger

type Logger interface {
	Log(message string)
}

Logger represents an abstraction providing custom logging. Clients may apply custom Logger implementations that publish events in the event of any Fallback component failing to execute a HTTP request.

Logger expects a successful response and therefore does not return an error.

Jump to

Keyboard shortcuts

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