connections

package
v1.3.11 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2021 License: MPL-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package connections allows to establish connections to remote resources which are not immediately available by repeating attempts with sleeping intervals

Index

Examples

Constants

This section is empty.

Variables

View Source
var WaitingConnectorIterativeDelayDuration = time.Second

WaitingConnectorIterativeDelayDuration global var allows to tweak sleeping interval between failed connections

Functions

func SetSleeper

func SetSleeper(sleeper Sleeper)

SetSleeper global func allows to replace sleeping logic with non-sleeping implementation for tests reasons

func WaitForConnection

func WaitForConnection(
	maxConnAttempts int,
	resourceName string,
	resourceCallback func() (interface{}, error),
	outputFunc func(msg string, err error),
) (interface{}, error)

WaitForConnection tries to connect to a remote resource with resourceName using conn function resourceCallback stopping after maxConnAttempts. outputFunc is used to output the info about attempts to std out which can be replaced with some custom output func

Example

This example tries to connect to a non immediately available resource outputting attempts info

attemptsToConnect := 2
connFunc := func() (interface{}, error) {
	if attemptsToConnect > 0 {
		attemptsToConnect--
		return nil, fmt.Errorf("Cannot connect to api.com")
	}
	return "SomeConnectionObject", nil
}

SetSleeper(func(sleepTime time.Duration) {
	//we don't sleep at all to not slow down the test
})

res, err := WaitForConnection(
	3,
	"api.com",
	connFunc,
	func(msg string, err error) {
		if err != nil {
			fmt.Printf("Error:%v", err)
		}
		fmt.Printf("%s", msg)
	},
)
errs.FailOnError(err)

fmt.Printf("This is my resource after 2 connection attempts: '%s'", res.(string))
Output:

Error:api.com connection error: Cannot connect to api.comTrying to reconnect to api.com in 1 s
Error:api.com connection error: Cannot connect to api.comTrying to reconnect to api.com in 2 s
This is my resource after 2 connection attempts: 'SomeConnectionObject'

Types

type Sleeper

type Sleeper func(sleepTime time.Duration)

Jump to

Keyboard shortcuts

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