defaults

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: May 13, 2024 License: Apache-2.0 Imports: 14 Imported by: 24

README

Defaults Build Status GoDoc License

Provide some global default values, supporting Go 1.21+.

By default, the value is not atomic, however, which can be enabled by setting the tags atomic when compiling it, such as go build -tags atomic.

Documentation

Overview

Package defaults provides some global default values.

Index

Examples

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: os.Exit
	ExitFunc = NewValueWithValidation(os.Exit, fA1Validation[int]("Exit"))

	// OnExitFunc is used to register the exit function.
	OnExitFunc = NewValueWithValidation(onexit, fA1Validation[func()]("OnExit"))
)
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 (
	// TrimPkgFileFunc is used to trim the prefix of the package file path.
	TrimPkgFileFunc = NewValueWithValidation(trimPkgFile, fA1R1Validation[string, string]("TrimPkgFile"))

	// GetStacksFunc is used to get the stacks of the function calling.
	GetStacksFunc = NewValueWithValidation(getStacks, fA1R1Validation[int, []string]("GetStacks"))
)
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 (
	// 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 (
	// OnInitFunc is used to register the init function.
	OnInitFunc = NewValueWithValidation(oninit, fA1Validation[func()]("OnInit"))
)
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 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 GetStacks added in v0.8.0

func GetStacks(skip int) []string

GetStacks is the proxy of GetStacksFunc to call the funciton.

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 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 is the proxy of OnExitFunc to register the exit function f.

NOTICE: OnExitFunc must be set before calling this function.

func OnInit added in v0.15.0

func OnInit(f func())

OnInit is the proxy of OnInitFunc to register the init function f.

NOTICE: OnInitFunc must be set before calling this function.

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 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 TrimPkgFile added in v0.8.0

func TrimPkgFile(file string) string

TrimPkgFile is the proxy of TrimPkgFileFunc to call the funciton.

Example
srcfile := TrimPkgFile("/path/to/src/github.com/xgfone/go-defaults/srcfile.go")
modfile := TrimPkgFile("/path/to/pkg/mod/github.com/xgfone/go-defaults/modfile.go")
origfile := TrimPkgFile("/path/to/github.com/xgfone/go-defaults/modfile.go")

fmt.Println(srcfile)
fmt.Println(modfile)
fmt.Println(origfile)
Output:

github.com/xgfone/go-defaults/srcfile.go
github.com/xgfone/go-defaults/modfile.go
/path/to/github.com/xgfone/go-defaults/modfile.go

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