defaults

package module
v0.20.1 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2024 License: Apache-2.0 Imports: 18 Imported by: 20

README

Defaults

Build Status GoDoc License GitHub release (latest SemVer)

Provide some global default values, supporting Go 1.22+.

Documentation

Overview

Package defaults provides some global default values.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ToBoolFunc is used to convert an input to bool.
	ToBoolFunc = NewValueWithValidation(tobool, castValidation[bool]("ToBool"))

	// ToInt64Func is used to convert an input to int64.
	ToInt64Func = NewValueWithValidation(toint64, castValidation[int64]("ToInt64"))

	// ToUint64Func is used to convert an input to uint64.
	ToUint64Func = NewValueWithValidation(touint64, castValidation[uint64]("ToUint64"))

	// ToFloat64Func is used to convert an input to float64.
	ToFloat64Func = NewValueWithValidation(tofloat64, castValidation[float64]("ToFloat64"))

	// ToStringFunc is used to convert an input to string.
	ToStringFunc = NewValueWithValidation(tostring, castValidation[string]("ToString"))

	// ToDurationFunc is used to convert an input to time.Duraiton.
	ToDurationFunc = NewValueWithValidation(toduration, castValidation[time.Duration]("ToDuration"))

	// ToTimeFunc is used to convert an input to time.Time.
	ToTimeFunc = NewValueWithValidation(totime, castValidation[time.Time]("ToTime"))
)
View Source
var (
	// ExitFunc is used to exit the program.
	//
	// Default: calling assists.RunExit and os.Exit in turn.
	ExitFunc = NewValueWithValidation(exit, fA1Validation[int]("Exit"))

	// ExitWaitFunc is used to wait until the program exit.
	//
	// Default: assists.WaitExit
	ExitWaitFunc = NewValueWithValidation(assists.WaitExit, fValidation("ExitWait"))

	// ExitContextFunc is used to get the exit context.
	//
	// Default: assists.ExitContext
	ExitContextFunc = NewValueWithValidation(assists.ExitContext, fR1Validation[context.Context]("ExitContext"))

	// ExitSignalsFunc is used to get the signals to let the program exit.
	//
	// For default, on Unix/Linux or Windows, it contains the signals as follow:
	//
	//	os.Interrupt
	//	syscall.SIGTERM
	//	syscall.SIGQUIT
	//	syscall.SIGABRT
	//	syscall.SIGINT
	//
	// On others, it only contains the signal os.Interrupt.
	ExitSignalsFunc = NewValueWithValidation(exitSignalsFunc, fR1Validation[[]os.Signal]("ExitSignals"))
)
View Source
var (
	// HeaderXRequestID is used by GetRequestIDFunc to try
	// to get the request id from the http request.
	HeaderXRequestID = "X-Request-Id"

	// GetRequestIDFunc is used to get the unique request session id.
	//
	// For the default implementation, it only supports the types and interfaces:
	//
	// 	*http.Request
	//	interface{ RequestID() string }
	//	interface{ GetRequestID() string }
	//
	// Or, return "".
	GetRequestIDFunc = NewValueWithValidation(getRequestID, fActxAifaceR1[string]("GetRequestID"))
)
View Source
var (
	TimeFormat   = NewValueWithValidation(time.RFC3339Nano, validateTimeFormat)
	TimeFormats  = NewValueWithValidation([]string{time.RFC3339Nano, "2006-01-02 15:04:05"}, validateTimeFormats)
	TimeLocation = NewValueWithValidation(time.UTC, validateTimeLocation)
	TimeNowFunc  = NewValueWithValidation(time.Now, validateTimeNow)
)

Pre-define some global variables about time.

View Source
var (
	// RuleValidator is used to validate whether a value conforms with the rule.
	//
	// Note: in general, it is used to validate a struct field with the tag rule.
	RuleValidator = NewValue(assists.RuleValidator(nil))

	// StructValidator is used to validate whether a struct value is valid.
	StructValidator = NewValue(assists.StructValidator(nil))
)
View Source
var (
	// FatalFunc is used to log the message with the FATAL level,
	// then the program exits.
	//
	// Default: use slog.LevelError+4 as the FATAL level, then exit by Exit(1).
	FatalFunc = NewValueWithValidation(fatal, fA2Validation[string, []any]("Fatal"))
)
View Source
var (
	// GetClientIPFunc is used to get the client ip of the request.
	//
	// For the default implementation, it only supports the types or interfaces:
	//
	// 	*http.Request
	// 	interface{ ClientIP() netip.Addr }
	// 	interface{ ClientIP() net.IP }
	// 	interface{ ClientIP() string }
	// 	interface{ RemoteAddr() netip.Addr }
	// 	interface{ RemoteAddr() net.Addr }
	// 	interface{ RemoteAddr() string }
	//
	// Or, return nil.
	GetClientIPFunc = NewValueWithValidation(getClientIP, fActxAifaceR1[netip.Addr]("GetClientIP"))
)
View Source
var (
	// HandlePanicFunc is used to handle the panic value returned by recover().
	HandlePanicFunc = NewValueWithValidation(handlePanic, fActxAiface("HandlePanic"))
)
View Source
var (
	// IsZeroFunc is used to check whether a value is ZERO.
	//
	// For the default implementation, it also supports
	//    interface{ IsZero() bool }
	//
	IsZeroFunc = NewValueWithValidation(runtimex.IsZero, fA1R1Validation[any, bool]("IsZero"))
)
View Source
var (
	// StructFieldNameFunc is used to get the obtain the name and arg
	// of the struct field, which needs to return a empty string for
	// the field name, that's "", if the field should be ignored.
	//
	// Example:
	//
	//	StructFieldNameFunc.Set(func(sf reflect.StructField) (name string, arg string) {
	//	    value := sf.Tag.Get("json")
	//	    if index := strings.IndexByte(value, ','); index > -1 {
	//	        arg = strings.TrimSpace(value[index+1:])
	//	        value = strings.TrimSpace(value[:index])
	//	    }
	//
	//	    switch value {
	//	    case "-":
	//	    case "":
	//	        name = sf.Name
	//	    default:
	//	        name = value
	//	    }
	//
	//	    return
	//	})
	//
	StructFieldNameFunc = NewValueWithValidation(assists.StructFieldNameFuncWithTags("json"),
		fA1R2Validation[reflect.StructField, string, string]("StructFieldName"))
)

Functions

func Exit added in v0.13.0

func Exit(code int)

Exit is the proxy of ExitFunc to call the function to exit the program.

func ExitContext added in v0.16.0

func ExitContext() context.Context

ExitContext is the proxy of ExitContextFunc to get the exit context.

func ExitSignals added in v0.17.0

func ExitSignals() []os.Signal

ExitSignals is the proxy of ExitSignalsFunc to call it to get the exit signals.

func ExitWait added in v0.16.0

func ExitWait()

ExitWait is the proxy of ExitContextFunc to call it to wait until the program exit.

func Fatal added in v0.16.0

func Fatal(msg string, args ...any)

Fatal is the proxy of FatalFunc to log the message with the FATAL level, then the program exits.

func GetClientIP added in v0.9.0

func GetClientIP(ctx context.Context, req any) netip.Addr

GetClientIP is the proxy of GetClientIPFunc to call the function.

func GetRequestID added in v0.3.0

func GetRequestID(ctx context.Context, req any) string

GetRequestID is the proxy of GetRequestIDFunc to call the function.

func GetStructFieldName

func GetStructFieldName(sf reflect.StructField) (name, arg string)

GetStructFieldName is the proxy of StructFieldNameFunc to call the function, just like StructFieldNameFunc.Get()(sf).

func HandlePanic added in v0.7.0

func HandlePanic(ctx context.Context, r any)

HandlePanic is the proxy of HandlePanicFunc to call the funciton.

func IsZero added in v0.19.0

func IsZero(value any) bool

IsZero is the proxy of IsZeroFunc to call it.

func Now

func Now() time.Time

Now returns the current time by using TimeNow and TimeLocation.

func OnExit added in v0.15.0

func OnExit(f func())

OnExit registers the exit function f, which is the proxy of assists.OnExit.

func OnExitPost added in v0.18.0

func OnExitPost(f func())

OnExitPost registers the post-exit function f, which is the proxy of assists.OnExitPost.

func OnInit added in v0.15.0

func OnInit(f func())

OnInit registers the init function f, which is the proxy of assists.OnInit.

func OnInitPre added in v0.18.0

func OnInitPre(f func())

OnInitPre registers the pre-init function f, which is the proxy of assists.OnInitPre.

func Recover added in v0.13.0

func Recover(ctx context.Context)

Recover is a convenient function to wrap and recover the panic if occurring, then call HandlePanic to handle it.

NOTICE: It must be called after defer, like

defer Recover(context.Background())

func SignalForExit added in v0.17.0

func SignalForExit()

SignalForExit watches the exit signals and calls the Exit function when any exit signal occurs.

func ToBool added in v0.15.0

func ToBool(input any) (bool, error)

ToBool is the proxy of ToBoolFunc to convert an input to bool.

func ToDuration added in v0.15.0

func ToDuration(input any) (time.Duration, error)

ToDuration is the proxy of ToDurationFunc to convert an input to time.Duration.

func ToFloat64 added in v0.15.0

func ToFloat64(input any) (float64, error)

ToFloat64 is the proxy of ToFloat64Func to convert an input to float64.

func ToInt64 added in v0.15.0

func ToInt64(input any) (int64, error)

ToInt64 is the proxy of ToInt64Func to convert an input to int64.

func ToString added in v0.15.0

func ToString(input any) (string, error)

ToString is the proxy of ToStringFunc to convert an input to string.

func ToTime added in v0.15.0

func ToTime(input any) (time.Time, error)

ToTime is the proxy of ToTimeFunc to convert an input to time.Time.

func ToUint64 added in v0.15.0

func ToUint64(input any) (uint64, error)

ToUint64 is the proxy of ToUint64Func to convert an input to uint64.

func Today added in v0.19.0

func Today() time.Time

Today returns the today time starting with 00:00:00.

func Unix added in v0.19.0

func Unix(sec, nsec int64) time.Time

Unix is the same as time.Unix, but set the location with TimeLocation.

func ValidateStruct

func ValidateStruct(value any) (err error)

ValidateStruct uses Validator to validate the struct value if StructValidator is not nil.

func ValidateWithRule

func ValidateWithRule(value any, rule string) (err error)

ValidateWithRule uses RuleValidator to validate a value conforms with the rule if RuleValidator is not nil.

Types

type Value

type Value[T any] struct {
	// contains filtered or unexported fields
}

Value represents a common value.

func NewValue

func NewValue[T any](initial T) *Value[T]

NewValue returns a new Value with the initial value.

func NewValueWithValidation

func NewValueWithValidation[T any](initial T, validate func(T) error) *Value[T]

NewValueWithValidation returns a new Value with the initial value and the validation.

validate may be nil, which is equal to always return nil.

func (*Value[T]) Get

func (v *Value[T]) Get() T

Get returns the inner value.

func (*Value[T]) Set

func (v *Value[T]) Set(new T)

Set sets the value to new.

It will panic if failing to validate the new value.

func (*Value[T]) Swap added in v0.4.0

func (v *Value[T]) Swap(new T) (old T)

Swap sets the value to new and returns the old value.

It will panic if failing to validate the new value.

func (*Value[T]) Validate

func (v *Value[T]) Validate(value T) error

Validate validate whether the input value is valid.

Directories

Path Synopsis
Package assists provides some assisted functions.
Package assists provides some assisted functions.

Jump to

Keyboard shortcuts

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