utils

package
v0.0.0-...-4486514 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2025 License: Apache-2.0 Imports: 26 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 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 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 ReportFlagActivation

func ReportFlagActivation(ctx *gin.Context, flag string, variant string)

ReportFlagActivation reports flag activation as a header

func RequestIDMiddleware

func RequestIDMiddleware(c *gin.Context)

func SkipTestIfCI

func SkipTestIfCI(t *testing.T) bool

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 interface {
	Encode() string
}

type CursorWithOffset

type CursorWithOffset[T Cursor] interface {
	GetOffset() int
	NewWithOffset(offset int) T
	Encode() string
}

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 PaginationResult

type PaginationResult[t any] struct {
	Items       []t
	Total       int
	First       int
	Offset      int
	Cursor      Cursor
	NextCursor  Cursor
	HasNext     bool
	HasPrevious bool
}

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

func Paginate

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

Paginate performs pagination on a collection of items with support for both offset-based and cursor-based pagination. It returns a PaginationResult containing the paginated items and metadata about the pagination state.

Behavior:

  • Cursor-based pagination takes precedence over offset-based pagination when both are provided
  • If no pagination parameters are provided, defaults to first 20 items
  • The function is safe to use with nil slices (returns empty result)
  • Handles out-of-bounds offsets gracefully

Example (offset-based):

result := Paginate(items, ptr(10), ptr(20), nil, nil)
// Returns items 20-29 (inclusive) from the collection

Example (cursor-based):

cursor := ParseOffsetCursor("eyJvZmZzZXQiOjIwfQ==")
result := Paginate(items, ptr(10), nil, nil, cursor)
// Returns next 10 items starting from the cursor position

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
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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