update and add func

This commit is contained in:
xing 2024-06-22 11:32:48 +08:00
parent 9c60d10568
commit 7cbfdf8601
2 changed files with 20 additions and 15 deletions

View File

@ -2,6 +2,7 @@ package helper
import ( import (
"context" "context"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
str "github.com/fthvgb1/wp-go/helper/strings" str "github.com/fthvgb1/wp-go/helper/strings"
@ -51,13 +52,15 @@ func CutUrlHost(u string) string {
return ur.String() return ur.String()
} }
func Defaults[T comparable](v, defaults T) T { func Defaults[T comparable](vals ...T) T {
var zero T var val T
if v == zero { for _, v := range vals {
return defaults if v != val {
}
return v return v
} }
}
return val
}
func DefaultVal[T any](v, defaults T) T { func DefaultVal[T any](v, defaults T) T {
var zero T var zero T
if reflect.DeepEqual(zero, v) { if reflect.DeepEqual(zero, v) {
@ -134,16 +137,6 @@ func IsFile(file string) bool {
return err == nil && !info.IsDir() return err == nil && !info.IsDir()
} }
func ZeroDefault[T comparable](vals ...T) T {
var val T
for _, v := range vals {
if v != val {
return v
}
}
return val
}
func GetAnyVal[T any](v any, defaults T) T { func GetAnyVal[T any](v any, defaults T) T {
vv, ok := v.(T) vv, ok := v.(T)
if !ok { if !ok {
@ -203,3 +196,15 @@ func RunFnWithTimeouts[A, V any](ctx context.Context, t time.Duration, ar A, cal
} }
return v, err return v, err
} }
func JsonDecode[T any](byts []byte) (T, error) {
var v T
err := json.Unmarshal(byts, &v)
return v, err
}
func AsError[T any](err error) (T, bool) {
var v T
ok := errors.As(err, &v)
return v, ok
}