util

package
v0.0.0-...-f36573f Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// KB is the number of bytes in a kilobyte
	KB = 1024
	// MB is the number of bytes in a megabyte
	MB = 1024 * KB
	// GB is the number of bytes in a gigabyte
	GB = 1024 * MB
	// TB is the number of bytes in a terabyte
	TB = 1024 * GB
	// PB is the number of bytes in a petabyte
	PB = 1024 * TB
	// EB is the number of bytes in an exabyte
	EB = 1024 * PB
)
View Source
const DefaultSearchDepth = 5

DefaultSearchDepth represents the maximum amount of nested maps (aka recursions) that can be searched

View Source
const GinContextKey string = "GinContextKey"

Variables

This section is empty.

Functions

func AllEqual

func AllEqual[T comparable](xs []T) bool

func Base64Decode

func Base64Decode(s string, encodings ...*base64.Encoding) ([]byte, error)

func BodyAsError

func BodyAsError(res *http.Response) error

BodyAsError returns the HTTP body as an error Returns ErrReadBody if the body cannot be read

func Chunk

func Chunk[T any](s []T, chunkSize int) [][]T

func ChunkBy

func ChunkBy[T any](items []T, chunkSize int) (chunks [][]T)

ChunkBy splits a slice into chunks of a given size

func Contains

func Contains[T comparable](s []T, str T) bool

func ContainsAnyString

func ContainsAnyString(s string, strs ...string) bool

ContainsAnyString checks whether a string contains any of the given substrings

func ContainsString

func ContainsString(s []string, str string) bool

ContainsString checks whether an item exists in a slice

func CopyMax

func CopyMax(writer io.Writer, it io.Reader, max int64) error

CopyMax will copy until a certain point and error after that point

func Dedupe

func Dedupe[T comparable](src []T, filterInPlace bool) []T

Dedupe removes duplicate elements from a slice, preserving the order of the remaining elements.

func DedupeWithTranslate

func DedupeWithTranslate[T any, V comparable](src []T, filterInPlace bool, translate func(T) V) []T

DedupeWithTranslate can be used when T is not good for comparison or there should be some other value used for comparison as opposed to golang equality check

func Difference

func Difference[T comparable](old []T, new []T) []T

Difference will take in 2 arrays and return the elements that exist in the second array but are not in the first

func ErrResponse

func ErrResponse(c *gin.Context, code int, err error)

ErrResponse sends a json response for an error during endpoint execution

func ErrorAs

func ErrorAs[T error](e error) (T, bool)

ErrorAs unwraps errors until it finds an error of type T. The second return value will be true if an error was found and returned, and false otherwise.

func ErrorIs

func ErrorIs[T error](e error) bool

ErrorIs returns true if the given error is of type T

func FillSliceWithValue

func FillSliceWithValue[T any](s []T, fillWith T) []T

func Filter

func Filter[T any](s []T, f func(T) bool, filterInPlace bool) []T

func FindFile

func FindFile(f string, searchDepth int) (string, error)

FindFile finds a file relative to the working directory by searching outer directories up to the search depth. Mostly for testing purposes.

func FindFirst

func FindFirst[T any](s []T, f func(T) bool) (T, bool)

func FindFirstFieldFromMap

func FindFirstFieldFromMap(it map[string]any, fields ...string) any

FindFirstFieldFromMap finds the first field in the map that contains the given field

func FirstNonEmptyString

func FirstNonEmptyString(strs ...string) string

func FirstNonErrorWithValue

func FirstNonErrorWithValue[T any](ctx context.Context, autoCancel bool, returnOnError func(error) bool, runs ...func(context.Context) (T, error)) (T, error)

func FromPointer

func FromPointer[T comparable](s *T) T

FromPointer returns the value of a pointer, or the zero value of the pointer's type if the pointer is nil.

func FromPointerSlice

func FromPointerSlice[T any](s []*T) []T

func GetErrFromResp

func GetErrFromResp(res *http.Response) error

func GetGinContext

func GetGinContext(ctx context.Context) *gin.Context

GetGinContext retrieves a gin.Context previously stored in the request context via the GinContextToContext middleware, or nil if no gin.Context is found.

func GetOptionalValue

func GetOptionalValue[T any](optional *T, fallback T) T

func GetURIPath

func GetURIPath(initial string, withoutQuery bool) string

GetURIPath takes a uri in any form and returns just the path

func GetValueFromMap

func GetValueFromMap(m map[string]any, key string, searchDepth int) any

GetValueFromMap is a function that returns the value at the first occurence of a given key in a map that potentially contains nested maps

func GetValueFromMapUnsafe

func GetValueFromMapUnsafe(m map[string]any, key string, searchDepth int) any

GetValueFromMapUnsafe is a function that returns the value at the first occurence of a given key in a map that potentially contains nested maps This function is unsafe because it will also return if the specified key is a substring of any key found in the map

func GroupBy

func GroupBy[T any, K comparable](s []T, f func(T) K) map[K][]T

func HealthCheckHandler

func HealthCheckHandler() gin.HandlerFunc

func InByteSizeFormat

func InByteSizeFormat(bytes uint64) string

InByteSizeFormat converts a number of bytes to a human-readable string using SI units (kB, MB, GB, TB, PB, EB, ZB, YB)

func InDocker

func InDocker() bool

InDocker returns true if the service is running as a container.

func IsEmpty

func IsEmpty[T any](s *T) bool

func LoadEncryptedEnvFile

func LoadEncryptedEnvFile(filePath string)

LoadEncryptedEnvFile configures the environment with the configured input file.

func LoadEncryptedServiceKey

func LoadEncryptedServiceKey(filePath string) []byte

LoadEncryptedServiceKey loads an encrypted service key JSON file from disk

func LoadEncryptedServiceKeyOrError

func LoadEncryptedServiceKeyOrError(filePath string) ([]byte, error)

LoadEncryptedServiceKeyOrError loads an encrypted service key JSON file from disk or errors

func LoadEnvFile

func LoadEnvFile(filePath string)

LoadEnvFile configures the environment with the configured input file.

func Map

func Map[T, U any](xs []T, f func(T) (U, error)) ([]U, error)

Map applies a function to each element of a slice, returning a new slice of the same length.

func MapFindOrNil

func MapFindOrNil[K comparable, T any](s map[K]T, key K) *T

func MapKeys

func MapKeys[T comparable, V any](m map[T]V) []T

func MapValues

func MapValues[T comparable, V any](m map[T]V) []V

func MapWithoutError

func MapWithoutError[T, U any](xs []T, f func(T) U) []U

MapWithoutError applies a function to each element of a slice, returning a new slice of the same length.

func MustFindFile

func MustFindFile(f string) string

MustFindFile panics if the file is not found up to the default search depth.

func MustFindFileOrError

func MustFindFileOrError(f string) (string, error)

MustFindFile panics if the file is not found up to the default search depth.

func MustGetGinContext

func MustGetGinContext(ctx context.Context) *gin.Context

MustGetGinContext retrieves a gin.Context previously stored in the request context via the GinContextToContext middleware, or panics if no gin.Context is found.

func RandEthAddress

func RandEthAddress() string

RandEthAddress returns a random ethereum address

func RandHexString

func RandHexString(n int) string

RandHexString returns a random hex string of given length

func RandStringBytes

func RandStringBytes(n int) string

RandStringBytes returns a random alphanumeric string of given length

func RemoveBOM

func RemoveBOM(bs []byte) []byte

RemoveBOM removes the byte order mark from a byte array

func RemoveLeftPaddedZeros

func RemoveLeftPaddedZeros(str string) string

RemoveLeftPaddedZeros is a function that removes the left padded zeros from a large hex string

func ResolveEnvFile

func ResolveEnvFile(service string, env string) string

ResolveEnvFile finds the appropriate env file to use for the service.

func SetConditionalValue

func SetConditionalValue[T any](value *T, param *T, conditional *bool)

func SqlStringIsNullOrEmpty

func SqlStringIsNullOrEmpty(s sql.NullString) bool

func StringToPointerIfNotEmpty

func StringToPointerIfNotEmpty(str string) *string

StringToPointerIfNotEmpty returns a pointer to the string if it is a non-empty string

func StringersToStrings

func StringersToStrings[T fmt.Stringer](stringers []T) []string

func ToNullInt32

func ToNullInt32(i *int) sql.NullInt32

func ToNullString

func ToNullString(s string, emptyIsNull bool) sql.NullString

func ToNullStringEmptyNull

func ToNullStringEmptyNull(s string) sql.NullString

func ToPGJSONB

func ToPGJSONB[T any](v T) (pgtype.JSONB, error)

func ToPointer

func ToPointer[T any](s T) *T

func ToPointerSlice

func ToPointerSlice[T any](s []T) []*T

func Track

func Track(s string, startTime time.Time)

Track the time it takes to execute a function

func TruncateWithEllipsis

func TruncateWithEllipsis(s string, length int) string

func UnmarshallBody

func UnmarshallBody(pInput any, body io.Reader) error

UnmarshallBody takes a request body and unmarshals it into the given struct input must be a pointer to a struct with json tags

func VarNotSetTo

func VarNotSetTo(envVar, emptyVal string)

VarNotSetTo panics if an environment variable is not set or set to `emptyVal`.

Types

type ErrHTTP

type ErrHTTP struct {
	URL    string
	Status int
	Err    error
}

ErrHTTP represents an error returned from an HTTP request

func (ErrHTTP) Error

func (h ErrHTTP) Error() string

func (ErrHTTP) Unwrap

func (h ErrHTTP) Unwrap() error

type ErrInvalidInput

type ErrInvalidInput struct {
	Reason string `json:"reason"`
}

ErrInvalidInput is an error response for an invalid input

func (ErrInvalidInput) Error

func (e ErrInvalidInput) Error() string

type ErrReadBody

type ErrReadBody struct {
	Err error
}

func (ErrReadBody) Error

func (e ErrReadBody) Error() string

func (ErrReadBody) Unwrap

func (e ErrReadBody) Unwrap() error

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse represents a json response for an error during endpoint execution

type FileHeaderReader

type FileHeaderReader struct {
	*bufio.Reader
	// contains filtered or unexported fields
}

FileHeaderReader is a struct that wraps an io.Reader and pre-reads the first 512 bytes of the reader When the reader is read, the first 512 bytes are returned first, then the rest of the reader is read, so that the first 512 bytes are not lost

func NewFileHeaderReader

func NewFileHeaderReader(reader io.Reader, bufSize int) *FileHeaderReader

NewFileHeaderReader returns a new FileHeaderReader

func (FileHeaderReader) Close

func (f FileHeaderReader) Close() error

Close closes the given io.Reader if it is also a closer

func (FileHeaderReader) Headers

func (f FileHeaderReader) Headers() ([]byte, error)

Headers returns the first 512 bytes of the reader

type LoggingReader

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

func NewLoggingReader

func NewLoggingReader(ctx context.Context, r io.Reader, w io.WriterTo) *LoggingReader

func (*LoggingReader) Read

func (lr *LoggingReader) Read(p []byte) (n int, err error)

func (*LoggingReader) WriteTo

func (lr *LoggingReader) WriteTo(w io.Writer) (n int64, err error)

type MultiErr

type MultiErr []error

func (MultiErr) Error

func (m MultiErr) Error() string

type SuccessResponse

type SuccessResponse struct {
	Success bool `json:"success"`
}

SuccessResponse represents a true or false success response for an endpoint

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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