util

package
v0.0.0-...-a942fbd Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2023 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CTXKeyUser          contextKey = "user"
	CTXKeyAccessToken   contextKey = "access_token"
	CTXKeyRequestID     contextKey = "request_id"
	CTXKeyDisableLogger contextKey = "disable_logger"
	CTXKeyCacheControl  contextKey = "cache_control"
)
View Source
const (
	DateFormat = "2006-01-02"
)
View Source
const (
	HTTPHeaderCacheControl = "Cache-Control"
)

Variables

View Source
var (
	ErrWaitTimeout = errors.New("WaitGroup has timed out")
)

Functions

func AddMonths

func AddMonths(d time.Time, months int) time.Time

func AddWeeks

func AddWeeks(d time.Time, weeks int) time.Time

func BindAndValidate deprecated

func BindAndValidate(c echo.Context, v runtime.Validatable, vs ...runtime.Validatable) error

BindAndValidate binds the request, parsing path+query+body and validating these structs.

Deprecated: Use our dedicated BindAndValidate* mappers instead:

BindAndValidateBody(c echo.Context, v runtime.Validatable) error // preferred
BindAndValidatePathAndQueryParams(c echo.Context, v runtime.Validatable) error  // preferred
BindAndValidatePathParams(c echo.Context, v runtime.Validatable) error // rare usecases
BindAndValidateQueryParams(c echo.Context, v runtime.Validatable) error // rare usecases

BindAndValidate works like Echo <v4.2.0. It was preferred to .Bind() everything (query, params, body) to a single struct in one pass. Thus we included additional handling to allow multiple body rebindings (though copying while restoring), as goswagger generated structs per endpoint are typically **separated** into one params struct (path and query) and one body struct. Echo >=v4.2.0 DefaultBinder now supports binding query, path params and body to their **own** structs natively. Thus, you areencouraged to use our new dedicated BindAndValidate* mappers, which are relevant for the structs goswagger autogenerates for you.

Original: Parses body (depending on the `Content-Type` request header) and performs payload validation as enforced by the Swagger schema associated with the provided type. In addition to binding the body, BindAndValidate also assigns query and URL parameters (if any) to a struct and perform validations on those.

Providing more than one struct allows for binding payload and parameters simultaneously since echo and goswagger expect data to be structured differently. If you do not require parsing of both body and params, additional structs can be omitted.

Returns an error that can directly be returned from an echo handler and sent to the client should binding or validating of any model fail.

func BindAndValidateBody

func BindAndValidateBody(c echo.Context, v runtime.Validatable) error

BindAndValidateBody binds the request, parsing **only** its body (depending on the `Content-Type` request header) and performs validation as enforced by the Swagger schema associated with the provided type.

Note: In contrast to BindAndValidate, this method does not restore the body after binding (it's considered consumed). Thus use BindAndValidateBody only once per request!

Returns an error that can directly be returned from an echo handler and sent to the client should binding or validating of any model fail.

func BindAndValidatePathAndQueryParams

func BindAndValidatePathAndQueryParams(c echo.Context, v runtime.Validatable) error

BindAndValidatePathAndQueryParams binds the request, parsing **only** its path **and** query params and performs validation as enforced by the Swagger schema associated with the provided type.

Returns an error that can directly be returned from an echo handler and sent to the client should binding or validating of any model fail.

func BindAndValidatePathParams

func BindAndValidatePathParams(c echo.Context, v runtime.Validatable) error

BindAndValidatePathParams binds the request, parsing **only** its path params and performs validation as enforced by the Swagger schema associated with the provided type.

Returns an error that can directly be returned from an echo handler and sent to the client should binding or validating of any model fail.

func BindAndValidateQueryParams

func BindAndValidateQueryParams(c echo.Context, v runtime.Validatable) error

BindAndValidateQueryParams binds the request, parsing **only** its query params and performs validation as enforced by the Swagger schema associated with the provided type.

Returns an error that can directly be returned from an echo handler and sent to the client should binding or validating of any model fail.

func ContainsAllString

func ContainsAllString(slice []string, sub ...string) bool

ContainsAllString checks whether the given string slice contains all strings provided.

func ContainsString

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

ContainsString checks whether the given string slice contains the string provided.

func Date

func Date(year int, month int, day int, loc *time.Location) time.Time

func DateFromString

func DateFromString(dateString string) (time.Time, error)

func DayBefore

func DayBefore(d time.Time) time.Time

func DisableLogger

func DisableLogger(ctx context.Context, shouldDisable bool) context.Context

DisableLogger toggles the indication whether `util.LogFromContext` should return a disabled logger for a context if none has been set by our logging middleware before. Whilst the usecase for a disabled logger are relatively minimal (we almost always want to have some log output, even if the context was not directly derived from a HTTP request), this functionality was provideds so you can switch back to the old zerolog behavior if so desired.

func EndOfDay

func EndOfDay(d time.Time) time.Time

func EndOfMonth

func EndOfMonth(d time.Time) time.Time

func Float64PtrToInt64PtrWithCents

func Float64PtrToInt64PtrWithCents(f *float64) *int64

func Float64PtrToInt64WithCents

func Float64PtrToInt64WithCents(f *float64) int64

func Float64PtrToIntPtrWithCents

func Float64PtrToIntPtrWithCents(f *float64) *int

func Float64PtrToIntWithCents

func Float64PtrToIntWithCents(f *float64) int

func GenerateRandomBase64String

func GenerateRandomBase64String(n int) (string, error)

GenerateRandomBase64String returns a string with n random bytes securely generated using the system's default CSPRNG in base64 encoding. The resulting string might not be of length n as the encoding for the raw bytes generated may vary.

An error will be returned if reading from the secure random number generator fails, at which point the returned result should be discarded and not used any further.

func GenerateRandomBytes

func GenerateRandomBytes(n int) ([]byte, error)

GenerateRandomBytes returns n random bytes securely generated using the system's default CSPRNG.

An error will be returned if reading from the secure random number generator fails, at which point the returned result should be discarded and not used any further.

func GenerateRandomHexString

func GenerateRandomHexString(n int) (string, error)

GenerateRandomHexString returns a string with n random bytes securely generated using the system's default CSPRNG in hexadecimal encoding. The resulting string might not be of length n as the encoding for the raw bytes generated may vary.

An error will be returned if reading from the secure random number generator fails, at which point the returned result should be discarded and not used any further.

func GenerateRandomString

func GenerateRandomString(n int, ranges []CharRange, extra string) (string, error)

GenerateRandomString returns a string with n random bytes securely generated using the system's default CSPRNG. The characters within the generated string will either be part of one ore more supplied range of characters, or based on characters in the extra string supplied.

An error will be returned if reading from the secure random number generator fails, at which point the returned result should be discarded and not used any further.

func GetEnv

func GetEnv(key string, defaultVal string) string

func GetEnvAsBool

func GetEnvAsBool(key string, defaultVal bool) bool

func GetEnvAsInt

func GetEnvAsInt(key string, defaultVal int) int

func GetEnvAsLanguageTag

func GetEnvAsLanguageTag(key string, defaultVal language.Tag) language.Tag

func GetEnvAsLanguageTagArr

func GetEnvAsLanguageTagArr(key string, defaultVal []language.Tag, separator ...string) []language.Tag

GetEnvAsLanguageTagArr reads ENV and returns the parsed values as []language.Tag split by separator.

func GetEnvAsStringArr

func GetEnvAsStringArr(key string, defaultVal []string, separator ...string) []string

GetEnvAsStringArr reads ENV and returns the values split by separator.

func GetEnvAsStringArrTrimmed

func GetEnvAsStringArrTrimmed(key string, defaultVal []string, separator ...string) []string

GetEnvAsStringArrTrimmed reads ENV and returns the whitespace trimmed values split by separator.

func GetEnvAsURL

func GetEnvAsURL(key string, defaultVal string) *url.URL

func GetEnvAsUint32

func GetEnvAsUint32(key string, defaultVal uint32) uint32

func GetEnvAsUint8

func GetEnvAsUint8(key string, defaultVal uint8) uint8

func GetEnvEnum

func GetEnvEnum(key string, defaultVal string, allowedValues []string) string

func GetMgmtSecret

func GetMgmtSecret(envKey string) string

GetMgmtSecret returns the management secret for the app server, mainly used by health check and readiness endpoints. It first attempts to retrieve a value from the given environment variable and generates a cryptographically secure random string should no env var have been set. Failure to generate a random string will cause a panic as secret security cannot be guaranteed otherwise. Subsequent calls to GetMgmtSecret during the server's runtime will always return the same randomly generated secret for consistency.

func GetProjectRootDir

func GetProjectRootDir() string

GetProjectRootDir returns the path as string to the project_root for a **running application**. Note: This function should not be used for generation targets (go generate, make go-generate). Thus it's explicitly excluded from the build tag scripts, see instead: * /scripts/get_project_root_dir.go * ./get_project_root_dir_scripts.go (delegates to above) https://stackoverflow.com/questions/43215655/building-multiple-binaries-using-different-packages-and-build-tags

func Int64PtrWithCentsToFloat64Ptr

func Int64PtrWithCentsToFloat64Ptr(c *int64) *float64

func Int64WithCentsToFloat64Ptr

func Int64WithCentsToFloat64Ptr(c int64) *float64

func IntPtrWithCentsToFloat64Ptr

func IntPtrWithCentsToFloat64Ptr(c *int) *float64

func IntWithCentsToFloat64Ptr

func IntWithCentsToFloat64Ptr(c int) *float64

func LogFromContext

func LogFromContext(ctx context.Context) *zerolog.Logger

LogFromContext returns a request-specific zerolog instance using the provided context. The returned logger will have the request ID as well as some other value predefined. If no logger is associated with the context provided, the global zerolog instance will be returned instead - this function will _always_ return a valid (enabled) logger. Should you ever need to force a disabled logger for a context, use `util.DisableLogger(ctx, true)` and pass the context returned to other code/`LogFromContext`.

func LogFromEchoContext

func LogFromEchoContext(c echo.Context) *zerolog.Logger

LogFromEchoContext returns a request-specific zerolog instance using the echo.Context of the request. The returned logger will have the request ID as well as some other value predefined.

func LogLevelFromString

func LogLevelFromString(s string) zerolog.Level

func MaxInt

func MaxInt(a, b int) int

func MergeStringMap

func MergeStringMap(base map[string]string, toMerge map[string]string) map[string]string

func MinInt

func MinInt(a, b int) int

func ParseFileUpload

func ParseFileUpload(c echo.Context, formNameFile string, allowedMIMETypes []string) (*multipart.FileHeader, multipart.File, *mimetype.MIME, error)

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) (string, error)

RequestIDFromContext returns the ID of the (HTTP) request, returning an error if it is not present.

func RunningInTest

func RunningInTest() bool

RunningInTest returns true if the current executing is within the go test framework. The function first checks the `CI` env variable defined by various CI environments, then tests whether the executable ends with the `.test` suffix generated by `go test`.

func ShouldDisableLogger

func ShouldDisableLogger(ctx context.Context) bool

ShouldDisableLogger checks whether the logger instance should be disabled for the provided context. `util.LogFromContext` will use this function to check whether it should return a default logger if none has been set by our logging middleware before, or fall back to the disabled logger, suppressing all output. Use `ctx = util.DisableLogger(ctx, true)` to disable logging for the given context.

func StartOfMonth

func StartOfMonth(d time.Time) time.Time

func StartOfQuarter

func StartOfQuarter(d time.Time) time.Time

func StartOfWeek

func StartOfWeek(d time.Time) time.Time

StartOfWeek returns the monday (assuming week starts at monday) of the week of the date

func TimeFromString

func TimeFromString(timeString string) (time.Time, error)

TimeFromString returns an instance of time.Time from a given string asuming RFC3339 format

func TouchFile

func TouchFile(absolutePathToFile string) (time.Time, error)

TouchFile creates an empty file if the file doesn’t already exist. If the file already exists then TouchFile updates the modified time of the file. Returns the modification time of the created / updated file.

func TruncateTime

func TruncateTime(d time.Time) time.Time

func UniqueString

func UniqueString(slice []string) []string

UniqueString takes the string slice provided and returns a new slice with all duplicates removed.

func ValidateAndReturn

func ValidateAndReturn(c echo.Context, code int, v runtime.Validatable) error

ValidateAndReturn returns the provided data as a JSON response with the given HTTP status code after performing payload validation as enforced by the Swagger schema associated with the provided type. `v` must implement `github.com/go-openapi/runtime.Validatable` in order to perform validations, otherwise an internal server error is thrown. Returns an error that can directly be returned from an echo handler and sent to the client should sending or validating fail.

func WaitTimeout

func WaitTimeout(wg *sync.WaitGroup, timeout time.Duration) error

WaitTimeout waits for the waitgroup for the specified max timeout. Returns nil on completion or ErrWaitTimeout if waiting timed out. See https://stackoverflow.com/questions/32840687/timeout-for-waitgroup-wait Note that the spawned goroutine to wg.Wait() gets leaked and will continue running detached

Types

type CacheControlDirective

type CacheControlDirective uint8
const (
	CacheControlDirectiveNoCache CacheControlDirective = 1 << iota
	CacheControlDirectiveNoStore
)

func CacheControlDirectiveFromContext

func CacheControlDirectiveFromContext(ctx context.Context) CacheControlDirective

func ParseCacheControlDirective

func ParseCacheControlDirective(d string) CacheControlDirective

func ParseCacheControlHeader

func ParseCacheControlHeader(val string) CacheControlDirective

func (*CacheControlDirective) AddDirective

func (d *CacheControlDirective) AddDirective(dir CacheControlDirective)

func (*CacheControlDirective) ClearDirective

func (d *CacheControlDirective) ClearDirective(dir CacheControlDirective)

func (CacheControlDirective) HasDirective

func (d CacheControlDirective) HasDirective(dir CacheControlDirective) bool

func (CacheControlDirective) String

func (d CacheControlDirective) String() string

func (*CacheControlDirective) ToggleDirective

func (d *CacheControlDirective) ToggleDirective(dir CacheControlDirective)

type CharRange

type CharRange int
const (
	CharRangeNumeric CharRange = iota
	CharRangeAlphaLowerCase
	CharRangeAlphaUpperCase
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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