utils

package
v0.0.0-...-8eba3d0 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: Apache-2.0 Imports: 27 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsInt

func AsInt(intString string) int

AsInt implies that the string exclusively contains an int

func AsIntOrNil

func AsIntOrNil(intString string) *int

AsIntOrNil returns an int or pointer

func AsNullInt

func AsNullInt(intString *string) null.Int

AsNullInt implies that the pointer string should contain a number if not null

func AsUuid

func AsUuid(s string) uuid.UUID

AsUuid parses string as Uuid, and returns it or an empty uuid.

func Base64DecodeAndUnmarshal

func Base64DecodeAndUnmarshal[T any](data string) (*T, error)

Base64DecodeAndUnmarshal decodes base64 and marshals

func FallbackLanguages

func FallbackLanguages() *[]string

An ordered list of fallback languages to use. Our content should always be available in at least one of these languages.

Returns a pointer to simplify usage when passing to other functions.

func FormatInLocale

func FormatInLocale(timeStamp time.Time, languages []string) string

FormatInLocale formats timestamp in locale

func GenerateRandomSecureString

func GenerateRandomSecureString(length int) string

GenerateRandomSecureString generates a random secure string

func GetOrSetContextWithLock

func GetOrSetContextWithLock[T any](ctx context.Context, key string, factory func() (*T, error)) (*T, error)

GetOrSetContextWithLock gets or sets a value in the context with a lock

func GinContextToContextMiddleware

func GinContextToContextMiddleware() gin.HandlerFunc

GinContextToContextMiddleware injects the Gin context into the normal context to be later extracted

func GinCtx

func GinCtx(ctx context.Context) (*gin.Context, error)

GinCtx extract the GIN context from a normal context

func LargestTime

func LargestTime(timeStamps ...time.Time) time.Time

LargestTime returns the largest time of the alternatives

func LegacyLanguageCodeTo639_1

func LegacyLanguageCodeTo639_1(code string) string

LegacyLanguageCodeTo639_1 converts language codes used in the legacy system and the smil file to proper ISO 639-1 codes as used in our DB

func Lock

func Lock(key string) *sync.Mutex

Lock returns a new stored lock

func LogError

func LogError(f func() error)

LogError if it occurs

func MapAsInt

func MapAsInt(intString string, _ int) int

MapAsInt is for usage in lo.Map

func MapAsIntegers

func MapAsIntegers(intStrings []string) []int

MapAsIntegers is for usage in lo.Map

func MapWith

func MapWith[T any, R any](collection []T, with func(T) R) []R

MapWith function

func MapWithCtx

func MapWithCtx[T any, TOut any](ctx context.Context, list []T, f func(context.Context, T) TOut) []TOut

MapWithCtx performs a lo.Map but adds ctx as the 1st param to the map function and ignores index

func MarshalAndBase64Encode

func MarshalAndBase64Encode[T any](data T) (string, error)

MarshalAndBase64Encode marshals to json and base64 encodes result

func MustCreateDBClient

func MustCreateDBClient(ctx context.Context, config DatabaseConfig) (*sql.DB, <-chan error)

MustCreateDBClient returns also a channel for async pinging

func MustCreateRedisClient

func MustCreateRedisClient(ctx context.Context, config RedisConfig) (*redis.Client, <-chan error)

MustCreateRedisClient throws a panic if redis is not reachable

func MustSetupTracing

func MustSetupTracing(serviceName string, config TracingConfig)

MustSetupTracing for Google Stack driver

It uses the following ENV vars to do some auto config:

  • GOOGLE_CLOUD_PROJECT
  • TRACE_SAMPLING_FREQUENCY - A number between 0.0 and 1.0 that determines how often requests should be traced. 1.0 means every request. Default is 0.1, 10% of requests

func ParseAcceptLanguage

func ParseAcceptLanguage(acceptLanguage string) []string

ParseAcceptLanguage HTTP header

func PointerArrayToArray

func PointerArrayToArray[K any](collection []*K) []K

PointerArrayToArray converts an array of pointers to array. Nil values will be filtered out

func PointerIntArrayToIntArray

func PointerIntArrayToIntArray(collection []*int) []int

PointerIntArrayToIntArray converts an array of int pointers to array of ints

func ShuffleSegmentedArray

func ShuffleSegmentedArray[T comparable](segments [][]T, minimumSegmentLength int, randomFactor float64, seed int64) []T

ShuffleSegmentedArray shuffles the segments and flattens to one array and tries to keep segments shuffled within segmentLength MinimumSegmentLength to make sure big batches of shorts still get prioritized more than the rest It adds random entries to the segments based on the randomFactor. A factor of 1 adds the same amount of random entries as the segment length. If the segment is 10 and the factor is 0.5, 5 random entries will be added to the segment, and so on.

func SmallestTime

func SmallestTime(timeStamps ...time.Time) time.Time

SmallestTime returns the smallest time of the alternatives

func TimestampFromString

func TimestampFromString(timestamp *string) (*time.Time, error)

TimestampFromString returns a validated time from a string

Types

type Cursor

type Cursor[K comparable] struct {
	Seed         *int64  `json:"seed"`
	RandomFactor float64 `json:"randomProportion"`
	CurrentIndex int     `json:"currentIndex"`
}

Cursor contains basic cursor data

func NewCursor

func NewCursor[K comparable](withSeed bool, randomFactor float64) *Cursor[K]

NewCursor creates a new cursor

func ParseCursor

func ParseCursor[K comparable](cursorString string) (*Cursor[K], error)

ParseCursor decodes from base64 and will unmarshal from json

func (Cursor[K]) ApplyTo

func (c Cursor[K]) ApplyTo(keys []K) []K

ApplyTo applies the cursor to a collection of keys

func (Cursor[K]) ApplyToSegments

func (c Cursor[K]) ApplyToSegments(segments [][]K, minimumSegmentLength int) []K

ApplyToSegments applies the cursor to segments of keys

func (Cursor[K]) Encode

func (c Cursor[K]) Encode() (string, error)

Encode marshals to json and encodes to base64

type DatabaseConfig

type DatabaseConfig struct {
	ConnectionString   string
	MaxConnections     *int
	MaxIdleConnections *int
}

DatabaseConfig contains configuration options for the database connection (Postgres)

type FeatureFlag

type FeatureFlag struct {
	Key     string
	Variant string
}

FeatureFlag is a feature flag

type FeatureFlags

type FeatureFlags []FeatureFlag

FeatureFlags is a list of feature flags

func GetFeatureFlags

func GetFeatureFlags(ctx *gin.Context) FeatureFlags

GetFeatureFlags returns flags for unleash

func (FeatureFlags) GetVariant

func (f FeatureFlags) GetVariant(key string) (string, bool)

GetVariant returns a flag for unleash

func (FeatureFlags) Has

func (f FeatureFlags) Has(key string) bool

Has returns true if a flag is present

func (FeatureFlags) List

func (f FeatureFlags) List() []string

List returns a list of flags

type ItemCursor

type ItemCursor[K comparable] struct {
	Keys         []K `json:"keys"`
	CurrentIndex int `json:"currentIndex"`
}

ItemCursor contains cursor data for pagination

func ParseItemCursor

func ParseItemCursor[K comparable](cursorString string) (*ItemCursor[K], error)

ParseItemCursor parses the base64 encoded cursor into a ItemCursor struct

func ToItemCursor

func ToItemCursor[K comparable](ids []K, id K) *ItemCursor[K]

ToItemCursor returns a cursor for the specified ids

func (*ItemCursor[K]) CursorFor

func (c *ItemCursor[K]) CursorFor(id K) *ItemCursor[K]

CursorFor returns the cursor for the specified string

func (*ItemCursor[K]) Encode

func (c *ItemCursor[K]) Encode() (string, error)

Encode encodes the cursor to a base64 string

func (*ItemCursor[K]) NextKeys

func (c *ItemCursor[K]) NextKeys(limit int) []K

NextKeys returns the next keys with this specified limit

type PaginationResult

type PaginationResult[t any] struct {
	Items  []t
	Total  int
	First  int
	Offset int
}

PaginationResult contains the result of the pagination and the effective first & offset

func Paginate

func Paginate[t any](collection []t, first *int, offset *int, dir *string) PaginationResult[t]

Paginate a collection with specified parameters

type RedisConfig

type RedisConfig struct {
	Address  string
	Username string
	Password string
	Database int
}

RedisConfig contains configuration of the redis client

type SyncMap

type SyncMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

SyncMap is a generic wrapper for sync.Map

func (*SyncMap[K, V]) Delete

func (m *SyncMap[K, V]) Delete(key K)

Delete deletes the value for a key.

func (*SyncMap[K, V]) Load

func (m *SyncMap[K, V]) Load(key K) (value V, ok bool)

Load returns the value stored in the map for a key, or nil if no value is present. The ok result indicates whether value was found in the map.

func (*SyncMap[K, V]) LoadAndDelete

func (m *SyncMap[K, V]) LoadAndDelete(key K) (value V, loaded bool)

LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.

func (*SyncMap[K, V]) LoadOrStore

func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

func (*SyncMap[K, V]) Range

func (m *SyncMap[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently (including by f), Range may reflect any mapping for that key from any point during the Range call. Range does not block other methods on the receiver; even f itself may call any method on m.

Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.

func (*SyncMap[K, V]) Store

func (m *SyncMap[K, V]) Store(key K, value V)

Store sets the value for a key.

type TracingConfig

type TracingConfig struct {
	UptraceDSN        string
	SamplingFrequency string
	TracePrettyPrint  string
}

Jump to

Keyboard shortcuts

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