common

package
v0.0.0-...-2a4c2d2 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2024 License: MIT Imports: 22 Imported by: 319

README

GoCryptoTrader package Common

Build Status Software License GoDoc Coverage Status Go Report Card

This common package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on our GoCryptoTrader Kanban board.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Current Features for common

This package collates basic broad functions that are used throughout this codebase.
  • Coding example
import "github.com/thrasher-corp/gocryptotrader/common"

testString := "aAaAa"

upper := strings.ToUpper(testString)

// upper == "AAAAA"
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc

Documentation

Index

Constants

View Source
const (
	// SimpleTimeFormatWithTimezone a common, but non-implemented time format in golang
	SimpleTimeFormatWithTimezone = time.DateTime + " MST"
	// GctExt is the extension for GCT Tengo script files
	GctExt = ".gct"
)
View Source
const (
	SmallLetters     = "abcdefghijklmnopqrstuvwxyz"
	CapitalLetters   = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	NumberCharacters = "0123456789"
)

Strings representing the full lower, upper case English character alphabet and base-10 numbers for generating a random string.

Variables

View Source
var (
	ErrNotYetImplemented    = errors.New("not yet implemented")
	ErrFunctionNotSupported = errors.New("unsupported wrapper function")

	ErrDateUnset              = errors.New("date unset")
	ErrStartAfterEnd          = errors.New("start date after end date")
	ErrStartEqualsEnd         = errors.New("start date equals end date")
	ErrStartAfterTimeNow      = errors.New("start date is after current time")
	ErrNilPointer             = errors.New("nil pointer")
	ErrEmptyParams            = errors.New("empty parameters")
	ErrCannotCalculateOffline = errors.New("cannot calculate offline, unsupported")
	ErrNoResponse             = errors.New("no response")
	ErrTypeAssertFailure      = errors.New("type assert failure")
	ErrUnknownError           = errors.New("unknown error")
	ErrGettingField           = errors.New("error getting field")
	ErrSettingField           = errors.New("error setting field")
)

Public common Errors

Functions

func AddPaddingOnUpperCase

func AddPaddingOnUpperCase(s string) string

AddPaddingOnUpperCase adds padding to a string when detecting an upper case letter. If there are multiple upper case items like `ThisIsHTTPExample`, it will only pad between like this `This Is HTTP Example`.

func AppendError

func AppendError(original, incoming error) error

AppendError appends an error to a list of exesting errors Either argument may be: * A vanilla error * An error implementing Unwrap() []error e.g. fmt.Errorf("%w: %w") * nil The result will be an error which may be a multiError if multipleErrors were found

func Batch

func Batch[S ~[]E, E any](blobs S, batchSize int) []S

Batch takes a slice type and converts it into a slice of containing slices of length batchSize, and any remainder in the final batch batchSize <= 0 will return the entire input slice in one batch

func ChangePermission

func ChangePermission(directory string) error

ChangePermission lists all the directories and files in an array

func CreateDir

func CreateDir(dir string) error

CreateDir creates a directory based on the supplied parameter

func EncodeURLValues

func EncodeURLValues(urlPath string, values url.Values) string

EncodeURLValues concatenates url values onto a url string and returns a string

func ExcludeError

func ExcludeError(err, excl error) error

ExcludeError returns a new error excluding any errors matching excl For a standard error it will either return the error unchanged or nil For an error which implements Unwrap() []error it will remove any errors matching excl and return the remaining errors or nil Any non-error messages and formatting from fmt.Errorf will be lost; This function is written for conditions

func ExtractHost

func ExtractHost(address string) string

ExtractHost returns the hostname out of a string

func ExtractPort

func ExtractPort(host string) int

ExtractPort returns the port name out of a string

func GenerateRandomString

func GenerateRandomString(length uint, characters ...string) (string, error)

GenerateRandomString generates a random string provided a length and list of Character types { SmallLetters, CapitalLetters, NumberCharacters}. if no characters are provided, the function uses a NumberCharacters(string of numeric characters).

func GetDefaultDataDir

func GetDefaultDataDir(env string) string

GetDefaultDataDir returns the default data directory Windows - C:\Users\%USER%\AppData\Roaming\GoCryptoTrader Linux/Unix or OSX - $HOME/.gocryptotrader

func GetExecutablePath

func GetExecutablePath() (string, error)

GetExecutablePath returns the executables launch path

func GetTypeAssertError

func GetTypeAssertError(required string, received interface{}, fieldDescription ...string) error

GetTypeAssertError returns additional information for when an assertion failure occurs. fieldDescription is an optional way to return what the affected field was for

func GetURIPath

func GetURIPath(uri string) string

GetURIPath returns the path of a URL given a URI

func IsEnabled

func IsEnabled(isEnabled bool) string

IsEnabled takes in a boolean param and returns a string if it is enabled or disabled

func IsValidCryptoAddress

func IsValidCryptoAddress(address, crypto string) (bool, error)

IsValidCryptoAddress validates your cryptocurrency address string using the regexp package // Validation issues occurring because "3" is contained in litecoin and Bitcoin addresses - non-fatal

func MatchesEmailPattern

func MatchesEmailPattern(value string) bool

MatchesEmailPattern ensures that the string is an email address by regexp check

func NewHTTPClientWithTimeout

func NewHTTPClientWithTimeout(t time.Duration) *http.Client

NewHTTPClientWithTimeout initialises a new HTTP client and its underlying transport IdleConnTimeout with the specified timeout duration

func SendHTTPRequest

func SendHTTPRequest(ctx context.Context, method, urlPath string, headers map[string]string, body io.Reader, verbose bool) ([]byte, error)

SendHTTPRequest sends a request using the http package and returns the body contents

func SetHTTPClient

func SetHTTPClient(client *http.Client) error

SetHTTPClient sets a custom HTTP client.

func SetHTTPClientWithTimeout

func SetHTTPClientWithTimeout(t time.Duration) error

SetHTTPClientWithTimeout sets a new *http.Client with different timeout settings

func SetHTTPUserAgent

func SetHTTPUserAgent(agent string) error

SetHTTPUserAgent sets the user agent which will be used for all common HTTP requests.

func SliceDifference

func SliceDifference[T comparable](slice1, slice2 []T) []T

SliceDifference returns the elements that are in slice1 or slice2 but not in both

func SortStrings

func SortStrings[S ~[]E, E fmt.Stringer](x S) S

SortStrings takes a slice of fmt.Stringer implementers and returns a new ascending sorted slice

func StartEndTimeCheck

func StartEndTimeCheck(start, end time.Time) error

StartEndTimeCheck provides some basic checks which occur frequently in the codebase

func StringSliceCompareInsensitive

func StringSliceCompareInsensitive(haystack []string, needle string) bool

StringSliceCompareInsensitive returns whether case insensitive needle exists within haystack

func StringSliceContains

func StringSliceContains(haystack []string, needle string) bool

StringSliceContains returns whether case sensitive needle is contained within haystack

func StringSliceContainsInsensitive

func StringSliceContainsInsensitive(haystack []string, needle string) bool

StringSliceContainsInsensitive returns whether case insensitive needle is contained within haystack

func YesOrNo

func YesOrNo(input string) bool

YesOrNo returns a boolean variable to check if input is "y" or "yes"

Types

type Counter

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

Counter is a thread-safe counter.

func (*Counter) IncrementAndGet

func (c *Counter) IncrementAndGet() int64

IncrementAndGet returns the next count after incrementing.

type ErrorCollector

type ErrorCollector struct {
	C  chan error
	Wg sync.WaitGroup
}

ErrorCollector allows collecting a stream of errors from concurrent go routines Users should call e.Wg.Done and send errors to e.C

func CollectErrors

func CollectErrors(n int) *ErrorCollector

CollectErrors returns an ErrorCollector with WaitGroup and Channel buffer set to n

func (*ErrorCollector) Collect

func (e *ErrorCollector) Collect() (errs error)

Collect runs waits for e.Wg to be Done, closes the error channel, and return a error collection

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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