Documentation
¶
Overview ¶
This package contains various helpers for the Go language
Index ¶
- Variables
- func Atoi(value string, fallback int) int
- func CappedString(s string, length int) string
- func CappedStringWith(s string, length int, suffix string) string
- func Contains[S ~[]T, T comparable](slice S, value T) bool
- func ContainsWithFunc[S ~[]T, T any](slice S, value T, predicate func(item T, value T) bool) bool
- func ConvertFromAnySlice[T any](items []any) []T
- func ConvertToAnySlice[S ~[]T, T any](items S) []any
- func DecodeUUID(encoded string) (uuid.UUID, error)
- func EncodeUUID(uuid uuid.UUID) string
- func EqualIdentifiable[T Identifiable](a, b T) bool
- func EqualNamed[T Named](a, b T) bool
- func EqualSlices[S ~[]T, T comparable](a, b S) bool
- func EqualSlicesWithFunc[S ~[]T, T any](a, b S, compare func(T, T) bool) bool
- func EqualStringIdentifiable[T StringIdentifiable](a, b T) bool
- func ExecEvery(job func(tick int64, at time.Time, changeme chan time.Duration), ...) (chan bool, chan bool, chan time.Duration)
- func ExponentialBackoff(attempt int, initialDelay time.Duration, maxDelay time.Duration, ...) time.Duration
- func Filter[S ~[]T, T any](items S, filter func(T) bool) (result []T)
- func Find[S ~[]T, T comparable](items S, value T) (t T, found bool)
- func FindWithFunc[S ~[]T, T any](items S, predicate func(T) bool) (t T, found bool)
- func GetEnvAsBool(name string, fallback bool) bool
- func GetEnvAsDuration(name string, fallback time.Duration) time.Duration
- func GetEnvAsInt(name string, fallback int) int
- func GetEnvAsString(name, fallback string) string
- func GetEnvAsTime(name string, fallback time.Time) time.Time
- func GetEnvAsURL(name string, fallback any) *url.URL
- func GetEnvAsUUID(name string, fallback uuid.UUID) uuid.UUID
- func GetReference(element any) any
- func Join[S ~[]T, T fmt.Stringer](items S, separator string) string
- func JoinWithFunc[S ~[]T, T any](items S, separator string, stringer func(item T) string) string
- func Map[S ~[]T, T any, R any](items S, mapper func(T) R) (result []R)
- func MapJoin[K comparable, T any](maps ...map[K]T) map[K]T
- func MatchIdentifiable[T Identifiable](search T) func(T) bool
- func MatchNamed[T Named](search T) func(T) bool
- func MatchStringIdentifiable[T StringIdentifiable](search T) func(T) bool
- func Must[T any](value T, err error) T
- func ParseDuration(value string) (duration time.Duration, err error)
- func Reduce[T any, R any](items []T, initial R, reducer func(R, T) R) (result R)
- func RespondWithError(w http.ResponseWriter, code int, err error)
- func RespondWithHTMLTemplate(w http.ResponseWriter, code int, template *template.Template, name string, ...)
- func RespondWithJSON(w http.ResponseWriter, code int, payload any)
- func Sort[S ~[]T, T any](items S, sorter func(T, T) bool)
- type CaseInsensitiveTypeRegistry
- type DecoratedResource
- type Duration
- type FlexInt
- type FlexInt8
- type FlexInt16
- type FlexInt32
- type FlexInt64
- type GoString
- type Identifiable
- type IsZeroer
- type Named
- type StringIdentifiable
- type Time
- func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time
- func DateUTC(year int, month time.Month, day, hour, min, sec, nsec int) Time
- func Now() Time
- func NowIn(loc *time.Location) Time
- func NowUTC() Time
- func ParseTime(value string) (Time, error)
- func ParseTimeIn(value string, loc *time.Location) (Time, error)
- func (t Time) After(u Time) bool
- func (t Time) AsTime() time.Time
- func (t Time) Before(u Time) bool
- func (t Time) BeginOfDay() Time
- func (t Time) Date() (year int, month time.Month, day int)
- func (t Time) EndOfDay() Time
- func (t Time) Equal(u Time) bool
- func (t Time) Format(layout string) string
- func (t Time) IsZero() bool
- func (t Time) Location() *time.Location
- func (t Time) MarshalJSON() ([]byte, error)
- func (t Time) String() string
- func (t Time) Tomorrow() Time
- func (t Time) UTC() Time
- func (t *Time) UnmarshalJSON(payload []byte) (err error)
- func (t Time) Yesterday() Time
- type Timestamp
- type TypeCarrier
- type TypeRegistry
- type URL
- type UUID
Examples ¶
- Contains
- ContainsWithFunc
- ConvertFromAnySlice
- ConvertToAnySlice
- Duration.MarshalJSON
- Duration.String
- Duration.ToISO8601
- Duration.UnmarshalJSON (FromFloat)
- Duration.UnmarshalJSON (FromISO)
- Duration.UnmarshalJSON (FromInt)
- Duration.UnmarshalJSON (FromString)
- EqualSlices
- EqualSlicesWithFunc
- Filter
- Find
- FindWithFunc
- Join
- JoinWithFunc
- Map
- Reduce
- Sort
- TypeRegistry.UnmarshalJSON
Constants ¶
This section is empty.
Variables ¶
var VERSION = "0.6.4"
VERSION is the version of this application
Functions ¶
func Atoi ¶ added in v0.2.0
Atoi convert a string to an int using a fallback if the conversion fails
func CappedString ¶ added in v0.6.4
CappedString returns a string capped to the given length.
If the string is longer than the given length, it is truncated and "..." is appended.
Note: the original string is not modified, a truncated copy is returned.
Example:
// Cap a string to 10 characters str := "This is a long string" cappedStr := CappedString(str, 10) // "This is a ..."
func CappedStringWith ¶ added in v0.6.4
CappedStringWith returns a string capped to the given length with a custom suffix.
If the string is longer than the given length, it is truncated and the suffix is appended.
Note: the original string is not modified, a truncated copy is returned.
Example:
// Cap a string to 10 characters with " (more)" suffix str := "This is a long string" cappedStr := CappedStringWith(str, 10, " (more)") // "Thi (more)"
func Contains ¶ added in v0.5.3
func Contains[S ~[]T, T comparable](slice S, value T) bool
Contains checks if a slice contains a value.
Example ¶
items := []string{"apple", "banana", "cherry"}
found := core.Contains(items, "banana")
fmt.Println("Found banana:", found)
notFound := core.Contains(items, "date")
fmt.Println("Found date:", notFound)
Output: Found banana: true Found date: false
func ContainsWithFunc ¶ added in v0.5.3
ContainsWithFunc checks if a slice contains a value using a custom function.
The function f should return true if the slice item matches the value.
If T implements Identifiable or StringIdentifiable or Named, consider using MatchIdentifiable, MatchStringIdentifiable or MatchNamed as the matching/equality function.
Example ¶
items := []Something1{{"apple"}, {"banana"}, {"cherry"}}
found := core.ContainsWithFunc(items, Something1{"banana"}, func(a, b Something1) bool {
return a.Data == b.Data
})
fmt.Println("Found banana:", found)
notFound := core.ContainsWithFunc(items, Something1{"date"}, func(a, b Something1) bool {
return a.Data == b.Data
})
fmt.Println("Found date:", notFound)
Output: Found banana: true Found date: false
func ConvertFromAnySlice ¶ added in v0.6.4
ConvertFromAnySlice converts a slice of any interface to a slice of specific type T.
If an item cannot be converted to type T, it is skipped.
If an item is not of type T, it attempts to marshal and unmarshal it as JSON. This allows to convert a JSON payload with an array of objects into a slice of T. Note that this requires that the item can be marshaled to JSON and that T can be unmarshaled from JSON and is slower than a direct type assertion.
Example:
// Convert a slice of any to a slice of strings
anySlice := []any{"one", "two", "three"}
stringSlice := ConvertFromAnySlice[string](anySlice)
Example ¶
anySlice := []any{"one", "two", "three"}
stringSlice := core.ConvertFromAnySlice[string](anySlice)
fmt.Println(stringSlice)
anySlice = []any{"one", 2, "three", 4.0, "five"}
stringSlice = core.ConvertFromAnySlice[string](anySlice)
fmt.Println(stringSlice)
Output: [one two three] [one three five]
func ConvertToAnySlice ¶ added in v0.6.4
ConvertToAnySlice converts a slice of specific type T to a slice of any interface.
Example:
// Convert a slice of strings to a slice of any
stringSlice := []string{"one", "two", "three"}
anySlice := ConvertToAnySlice[string](stringSlice)
Example ¶
stringSlice := []string{"one", "two", "three"}
anySlice := core.ConvertToAnySlice(stringSlice)
fmt.Println(anySlice)
intSlice := []int{1, 2, 3, 4, 5}
anySlice = core.ConvertToAnySlice(intSlice)
fmt.Println(anySlice)
Output: [one two three] [1 2 3 4 5]
func DecodeUUID ¶ added in v0.2.0
DecodeUUID decodes a UUID from a 22 char long string
func EncodeUUID ¶ added in v0.2.0
EncodeUUID encodes a UUID in a 22 char long string
func EqualIdentifiable ¶ added in v0.5.10
func EqualIdentifiable[T Identifiable](a, b T) bool
EqualIdentifiable compares two values for equality by their Identifier
func EqualNamed ¶ added in v0.5.10
EqualNamed compares two values for equality by name
func EqualSlices ¶ added in v0.5.3
func EqualSlices[S ~[]T, T comparable](a, b S) bool
EqualSlices checks if two slices are equal.
Two slices are equal if they have the same length and all elements of the first slice exist in the second slice. And vice versa.
Example ¶
slice1 := []string{"apple", "banana", "cherry"}
slice2 := []string{"cherry", "banana", "apple"}
equal := core.EqualSlices(slice1, slice2)
fmt.Println("Slices are equal:", equal)
slice3 := []string{"apple", "banana", "date"}
notEqual := core.EqualSlices(slice1, slice3)
fmt.Println("Slices are equal:", notEqual)
Output: Slices are equal: true Slices are equal: false
func EqualSlicesWithFunc ¶ added in v0.5.3
EqualSlicesWithFunc checks if two slices are equal.
Two slices are equal if they have the same length and all elements of the first slice exist in the second slice. And vice versa.
Example ¶
slice1 := []Something{Something1{"apple"}, Something1{"banana"}, Something1{"cherry"}}
slice2 := []Something{Something1{"cherry"}, Something1{"banana"}, Something1{"apple"}}
equal := core.EqualSlicesWithFunc(slice1, slice2, func(a, b Something) bool {
return a.GetData() == b.GetData()
})
fmt.Println("Slices are equal:", equal)
slice3 := []Something{Something1{"apple"}, Something1{"banana"}, Something1{"date"}}
notEqual := core.EqualSlicesWithFunc(slice1, slice3, func(a, b Something) bool {
return a.GetData() == b.GetData()
})
fmt.Println("Slices are equal:", notEqual)
Output: Slices are equal: true Slices are equal: false
func EqualStringIdentifiable ¶ added in v0.5.10
func EqualStringIdentifiable[T StringIdentifiable](a, b T) bool
EqualStringIdentifiable compares two values for equality by their Identifier
func ExecEvery ¶
func ExecEvery(job func(tick int64, at time.Time, changeme chan time.Duration), every time.Duration) (chan bool, chan bool, chan time.Duration)
ExecEvery runs a func as a go routine regularly
returns 3 chans:
- a chan to stop the time loop, pipe true
- a chan to force the job execution on demand
- a chan to change the ticker interval
the invoked func can modify the interval by piping a new Duration to its given chan
the func is executed once before the ticker starts
func ExponentialBackoff ¶ added in v0.6.3
func ExponentialBackoff(attempt int, initialDelay time.Duration, maxDelay time.Duration, jitter float64) time.Duration
ExponentialBackoff returns a duration to wait before retrying an operation, using an exponential backoff algorithm.
The delay is calculated as initialDelay * 2^(attempt-1), with a maximum of maxDelay. Attempt is 1-based (i.e. the first attempt is 1).
A jitter factor is applied to the delay to avoid thundering herd problems. The jitter is a random value between -jitter * delay and +jitter * delay.
func Filter ¶ added in v0.5.0
Filter filters a slice of items based on a filter function
Note: The result is a new slice, the original is not modified
Example:
// Filter all positive numbers in a slice
numbers := Filter(numbers, func(number int) bool {
return number > 0
})
Example ¶
// Filter all even numbers in a slice
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evens := core.Filter(numbers, func(number int) bool {
return number%2 == 0
})
fmt.Println(evens)
Output: [2 4 6 8 10]
func Find ¶ added in v0.5.9
func Find[S ~[]T, T comparable](items S, value T) (t T, found bool)
Find finds a value in a slice
Example ¶
items := []string{"apple", "banana", "cherry"}
result, found := core.Find(items, "banana")
fmt.Println("Found banana:", found)
if found {
fmt.Println("Banana is:", result)
}
_, found = core.Find(items, "date")
fmt.Println("Found date:", found)
Output: Found banana: true Banana is: banana Found date: false
func FindWithFunc ¶ added in v0.5.9
FindWithFunc is a function that finds a value in a slice
Note that the returned value is a copy of the item in the slice.
Example ¶
items := []Something1{{"apple"}, {"banana"}, {"cherry"}}
result, found := core.FindWithFunc(items, func(item Something1) bool {
return item.Data == "banana"
})
fmt.Println("Found banana:", found)
if found {
fmt.Println("Banana is:", result.Data)
}
_, found = core.FindWithFunc(items, func(item Something1) bool {
return item.Data == "date"
})
fmt.Println("Found date:", found)
Output: Found banana: true Banana is: banana Found date: false
func GetEnvAsBool ¶ added in v0.0.3
GetEnvAsBool returns the bool value of an environment variable by its name
if not present, the fallback value is used
func GetEnvAsDuration ¶
GetEnvAsDuration returns the time value of an environment variable by its name
if not present, the fallback value is used
func GetEnvAsInt ¶
GetEnvAsInt returns the int value of an environment variable by its name
if not present, the fallback value is used
func GetEnvAsString ¶
GetEnvAsString returns the string value of an environment variable by its name
if not present, the fallback value is used
func GetEnvAsTime ¶
GetEnvAsTime returns the time value of an environment variable by its name
if not present, the fallback value is used
func GetEnvAsURL ¶ added in v0.4.6
GetEnvAsURL returns the URL value of an environment variable by its name
if not present, the fallback value is used
func GetReference ¶ added in v0.6.3
GetReference gets a reference of an identifiable
If the element implements Identifiable, the reference will use the UUID ID.
If the element implements StringIdentifiable, the reference will use the string ID.
If the element implements fmt.Stringer, the reference will use the string representation.
Otherwise, the element itself is returned.
func Join ¶ added in v0.5.3
Join joins a slice of items into a string using a separator.
Example ¶
items := []Something2{{"apple"}, {"banana"}, {"cherry"}}
result := core.Join(items, "; ")
fmt.Println(result)
Output: apple; banana; cherry
func JoinWithFunc ¶ added in v0.5.3
JoinWithFunc joins a slice of items into a string using a separator.
The function is called for each item to get its string representation.
Example ¶
items := []Something1{{"apple"}, {"banana"}, {"cherry"}}
result := core.JoinWithFunc(items, "; ", func(item Something1) string {
return item.Data
})
fmt.Println(result)
Output: apple; banana; cherry
func Map ¶ added in v0.5.0
Map maps a slice of items into a new slice
Note: The result is a new slice, the original is not modified
Example:
// Map all numbers in a slice to their square
numbers := []int{1, 2, 3, 4, 5}
squares := Map(numbers, func(number int) int64 {
return int64(number * number)
})
Example ¶
// Map all Something1 in a slice to their string representation
slice := []Something1{{"apple"}, {"banana"}, {"cherry"}}
strings := core.Map(slice, func(item Something1) string {
return item.Data
})
fmt.Println(strings)
Output: [apple banana cherry]
func MapJoin ¶ added in v0.5.8
func MapJoin[K comparable, T any](maps ...map[K]T) map[K]T
MapJoin joins two or more maps of the same kind
None of the maps are modified, a new map is created.
If two maps have the same key, the latter map overwrites the value from the former map.
func MatchIdentifiable ¶ added in v0.5.10
func MatchIdentifiable[T Identifiable](search T) func(T) bool
MatchIdentifiable returns a function that matches an Identifiable value
func MatchNamed ¶ added in v0.5.10
MatchNamed returns a function that matches a Named value
func MatchStringIdentifiable ¶ added in v0.5.10
func MatchStringIdentifiable[T StringIdentifiable](search T) func(T) bool
MatchStringIdentifiable returns a function that matches a StringIdentifiable value
func Must ¶ added in v0.4.6
Must panics if there is an error, otherwise returns the given value
Example:
var myurl = core.Must[*url.URL](url.Parse("https://www.acme.com"))
func ParseDuration ¶ added in v0.1.0
ParseDuration parses an ISO8601 duration
If the given value is not an ISO8601 duration, returns time.ParseDuration
func Reduce ¶ added in v0.5.0
Reduce reduces a slice of items into a single value
Example:
// Sum all numbers in a slice
sum := Reduce(numbers, 0, func(sum, number int) int {
return sum + number
})
Example ¶
// Sum all numbers in a slice
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sum := core.Reduce(numbers, 0, func(sum, number int) int {
return sum + number
})
fmt.Println(sum)
Output: 55
func RespondWithError ¶
func RespondWithError(w http.ResponseWriter, code int, err error)
RespondWithError will send a reply with an error as JSON and a HTTP Status code
func RespondWithHTMLTemplate ¶ added in v0.5.0
func RespondWithHTMLTemplate(w http.ResponseWriter, code int, template *template.Template, name string, data any)
RespondWithHTMLTemplate will send a reply with a HTML payload generated from an HTML Template and a HTTP Status code
func RespondWithJSON ¶
func RespondWithJSON(w http.ResponseWriter, code int, payload any)
RespondWithJSON will send a reply with a JSON payload and a HTTP Status code
The payload will be marshaled using the standard json.Marshal function.
func Sort ¶ added in v0.5.0
Sort sorts a slice of items
Note: The items slice is modified in place.
calls slices.SortFunc from the golang.org/x/exp/slices package.
Example:
// Sort a slice of numbers
Sort(numbers, func(a, b int) bool {
return a < b
})
Example ¶
// Sort a slice of numbers
numbers := []int{10, 2, 8, 3, 6, 5, 5, 4, 7, 9, 1}
core.Sort(numbers, func(a, b int) bool {
return a < b
})
fmt.Println(numbers)
fruits := []string{"banana", "apple", "cherry"}
core.Sort(fruits, func(a, b string) bool {
return a < b
})
fmt.Println(fruits)
things := []Something1{{"banana"}, {"apple"}, {"cherry"}}
core.Sort(things, func(a, b Something1) bool {
return a.Data < b.Data
})
strings := core.Map(things, func(item Something1) string {
return item.Data
})
fmt.Println(strings)
Output: [1 2 3 4 5 5 6 7 8 9 10] [apple banana cherry] [apple banana cherry]
Types ¶
type CaseInsensitiveTypeRegistry ¶ added in v0.6.1
CaseInsensitiveTypeRegistry contains a map of identifier vs Type The Registry is case insensitive, so "something" and "Something" are the same
func (CaseInsensitiveTypeRegistry) Add ¶ added in v0.6.1
func (registry CaseInsensitiveTypeRegistry) Add(classes ...TypeCarrier) CaseInsensitiveTypeRegistry
Add adds one or more TypeCarriers to the CaseInsensitiveTypeRegistry
func (CaseInsensitiveTypeRegistry) SupportedTypes ¶ added in v0.6.2
func (registry CaseInsensitiveTypeRegistry) SupportedTypes() []string
SupportedTypes returns a list of supported types in the registry
func (CaseInsensitiveTypeRegistry) UnmarshalJSON ¶ added in v0.6.1
func (registry CaseInsensitiveTypeRegistry) UnmarshalJSON(payload []byte, typetag ...string) (any, error)
UnmarshalJSON unmarshal a payload into a Type Carrier
The interface that is returned contains a pointer to the TypeCarrier structure.
The default typetag is "type", but you can replace it by one or more of your own.
Examples:
object, err := registry.UnmarshalJSON(payload) object, err := registry.UnmarshalJSON(payload, "__type", "Type")
type DecoratedResource ¶ added in v0.5.10
DecoratedResource is a resource that contains a Self link
func Decorate ¶ added in v0.5.10
func Decorate(item any, rootpath string) *DecoratedResource
Decorate decorates a struct that can be identified
func DecorateAll ¶ added in v0.5.10
func DecorateAll[S ~[]T, T any](items S, rootpath string) []DecoratedResource
DecorateAll decorates all items in a slice of identifiable items
func DecorateWithURL ¶ added in v0.5.10
func DecorateWithURL(item any, root url.URL) *DecoratedResource
DecorateWithURL decorates a struct that can be identified with a URL
func (DecoratedResource) MarshalJSON ¶ added in v0.5.10
func (resource DecoratedResource) MarshalJSON() ([]byte, error)
MarshalJSON marshals the DecoratedResource to JSON
implements the json.Marshaler interface
func (DecoratedResource) ResourceName ¶ added in v0.5.10
func (resource DecoratedResource) ResourceName() string
ResourceName returns the name of a resource
If the data is a core.TypeCarrier, it will return the pluralized name of the type Otherwise, it will return the pluralized name of the type of the data, via reflection
type Duration ¶ added in v0.1.0
Duration is a placeholder so we can add new funcs to the type
func (Duration) AsDuration ¶ added in v0.6.2
AsDuration converts a core.Duration into a time.Duration
func (Duration) MarshalJSON ¶ added in v0.1.0
MarshalJSON marshals this into JSON
The duration is serialized in milliseconds ¶
implements json.Marshaler interface
Example ¶
duration := core.Duration(90 * time.Second) payload, _ := json.Marshal(duration) fmt.Println(string(payload))
Output: 90000
func (Duration) String ¶ added in v0.1.0
Example ¶
duration := core.Duration(90 * time.Second) fmt.Println(duration.String())
Output: 1m30s
func (Duration) ToISO8601 ¶ added in v0.6.2
ToISO8601 converts a Duration to an ISO 8601 duration string
This implements ISO 8601-1 (i.e. no weeks)
Example ¶
duration := core.Duration(4000 * time.Hour) fmt.Println(duration.ToISO8601())
Output: P5M16DT16H
func (*Duration) UnmarshalJSON ¶ added in v0.1.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface an int (int64) will be assumed to be milli-seconds a string will be parsed as an ISO 8601 then as a GO time.Duration
Example (FromFloat) ¶
payload := `{"duration":4500000.0}`
result := struct {
Duration core.Duration `json:"duration"`
}{}
_ = json.Unmarshal([]byte(payload), &result)
fmt.Println(time.Duration(result.Duration).String())
Output: 1h15m0s
Example (FromISO) ¶
payload := `{"duration":"P2DT3H4M5.006S"}`
result := struct {
Duration core.Duration `json:"duration"`
}{}
_ = json.Unmarshal([]byte(payload), &result)
fmt.Println(time.Duration(result.Duration).String())
Output: 51h4m5.006s
Example (FromInt) ¶
payload := `{"duration":4500000}`
result := struct {
Duration core.Duration `json:"duration"`
}{}
_ = json.Unmarshal([]byte(payload), &result)
fmt.Println(time.Duration(result.Duration).String())
Output: 1h15m0s
Example (FromString) ¶
payload := `{"duration":"1h15m30s"}`
result := struct {
Duration core.Duration `json:"duration"`
}{}
_ = json.Unmarshal([]byte(payload), &result)
fmt.Println(time.Duration(result.Duration).String())
Output: 1h15m30s
type FlexInt ¶ added in v0.2.0
type FlexInt int
FlexInt is an int that can be unmashaled from an int or a string (1234 or "1234")
func (*FlexInt) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface
type FlexInt8 ¶ added in v0.2.0
type FlexInt8 int8
FlexInt8 is an int that can be unmashaled from an int or a string (1234 or "1234")
func (*FlexInt8) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface
type FlexInt16 ¶ added in v0.2.0
type FlexInt16 int16
FlexInt16 is an int that can be unmashaled from an int or a string (1234 or "1234")
func (*FlexInt16) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface
type FlexInt32 ¶ added in v0.2.0
type FlexInt32 int32
FlexInt32 is an int that can be unmashaled from an int or a string (1234 or "1234")
func (*FlexInt32) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface
type FlexInt64 ¶ added in v0.2.0
type FlexInt64 int64
FlexInt64 is an int that can be unmashaled from an int or a string (1234 or "1234")
func (*FlexInt64) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface
type GoString ¶ added in v0.1.0
type GoString interface {
// GoString returns a GO representation of this
GoString() string
}
GoString represents object that can give their Go internals as a String
type Identifiable ¶ added in v0.4.5
Identifiable describes that can get their Identifier as a UUID
type IsZeroer ¶ added in v0.5.2
type IsZeroer interface {
IsZero() bool
}
IsZeroer is an interface that can be implemented by types that can tell if their value is zero
type Named ¶ added in v0.4.5
type Named interface {
GetName() string
}
Named describes types that can get their Name
type StringIdentifiable ¶ added in v0.5.10
type StringIdentifiable interface {
GetID() string
}
StringIdentifiable describes that can get their Identifier as a string
type Time ¶ added in v0.2.0
Time is a placeholder so we can add new funcs to the type
func ParseTime ¶ added in v0.4.2
ParseTime parses the given string for a Time, if the Time is not UTC it is set in the current location
func ParseTimeIn ¶ added in v0.4.2
ParseTimeIn parses the given string for a Time, if the Time is not UTC it is set in the given location
func (Time) BeginOfDay ¶ added in v0.4.2
BeginOfDay returns the Beginning of the Day (i.e. midnight)
func (Time) EndOfDay ¶ added in v0.4.2
EndOfDay returns the End of the Day (i.e. 1 second before midnight)
func (Time) Equal ¶ added in v0.4.2
Equal reports whether t and u represent the same time instant.
Two times can be equal even if they are in different locations.
For example, 6:00 +0200 and 4:00 UTC are Equal.
See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.
func (Time) Format ¶ added in v0.4.2
Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.
A fractional second is represented by adding a period and zeros to the end of the seconds section of layout string, as in "15:04:05.000" to format a time stamp with millisecond precision.
Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.
func (Time) IsZero ¶ added in v0.4.2
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC
func (Time) MarshalJSON ¶ added in v0.2.0
MarshalJSON marshals this into JSON
implements json.Marshaler interface We store time as RFC3339 UTC
func (Time) String ¶ added in v0.4.2
String returns the time formatted using the format string
"2006-01-02 15:04:05.999999999 -0700 MST"
If the time has a monotonic clock reading, the returned string includes a final field "m=±<value>", where value is the monotonic clock reading formatted as a decimal number of seconds.
The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string.
func (*Time) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface We read time as RFC3339 UTC
type Timestamp ¶
Timestamp converts Unix Epoch to/from time.Time
func TimestampFromJSEpoch ¶
TimestampFromJSEpoch returns a Timestamp from a JS Epoch
func TimestampNow ¶
func TimestampNow() Timestamp
TimestampNow returns a Timestamp at the time of its call
func (Timestamp) MarshalJSON ¶
MarshalJSON encodes a TimeStamp to its JSON Epoch
implements json.Marshaler interface
func (*Timestamp) UnmarshalJSON ¶
UnmarshalJSON decodes an Epoch from JSON and gives a Timestamp
implements json.Unmarshaler interface The Epoch can be "12345" or 12345
type TypeCarrier ¶
type TypeCarrier interface {
// GetType tells the type of this object
GetType() string
}
TypeCarrier represents object that carries a Type
type TypeRegistry ¶ added in v0.4.8
TypeRegistry contains a map of identifier vs Type
func (TypeRegistry) Add ¶ added in v0.4.8
func (registry TypeRegistry) Add(classes ...TypeCarrier) TypeRegistry
Add adds one or more TypeCarriers to the TypeRegistry
func (TypeRegistry) SupportedTypes ¶ added in v0.6.2
func (registry TypeRegistry) SupportedTypes() []string
SupportedTypes returns a list of supported types in the registry
func (TypeRegistry) UnmarshalJSON ¶ added in v0.4.9
func (registry TypeRegistry) UnmarshalJSON(payload []byte, typetag ...string) (any, error)
UnmarshalJSON unmarshal a payload into a Type Carrier
The interface that is returned contains a pointer to the TypeCarrier structure.
The default typetag is "type", but you can replace it by one or more of your own.
Examples:
object, err := registry.UnmarshalJSON(payload) object, err := registry.UnmarshalJSON(payload, "__type", "Type")
Example ¶
package main
import (
"fmt"
"github.com/gildas/go-core"
)
type DataHolder interface {
core.TypeCarrier
GetData() string
}
type DataSpec1 struct {
Data string `json:"data"`
}
type DataSpec2 struct {
Data string `json:"data"`
}
func (s DataSpec1) GetType() string {
return "dataspec1"
}
func (s DataSpec1) GetData() string {
return s.Data
}
func (s DataSpec2) GetType() string {
return "dataspec2"
}
func (s DataSpec2) GetData() string {
return s.Data
}
func main() {
// Typically, each struct would be declared in its own go file
// and the core.TypeRegistry.Add() func would be done in the init() func of each file
registry := core.TypeRegistry{}.Add(DataSpec1{}, DataSpec2{})
payload := []byte(`{"type": "dataspec1", "data": "Hello"}`)
object, err := registry.UnmarshalJSON(payload)
if err != nil {
fmt.Println(err)
return
}
value, ok := object.(DataHolder)
if !ok {
fmt.Println("Not a DataHolder")
return
}
fmt.Println(value.GetData())
// Here we will read the Type of the payload through a custom JSON property
payload = []byte(`{"__type": "dataspec1", "data": "Hello"}`)
object, err = registry.UnmarshalJSON(payload, "__type")
if err != nil {
fmt.Println(err)
return
}
value, ok = object.(DataHolder)
if !ok {
fmt.Println("Not a DataHolder")
return
}
fmt.Println(value.GetData())
}
Output: Hello Hello
type URL ¶ added in v0.2.0
URL is a placeholder so we can add new funcs to the type
func (URL) MarshalJSON ¶ added in v0.2.0
MarshalJSON marshals this into JSON
implements json.Marshaler interface
func (*URL) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes JSON
implements json.Unmarshaler interface
type UUID ¶ added in v0.5.2
func (UUID) GetID ¶ added in v0.6.3
GetID returns the UUID as a uuid.UUID type
implements Identifiable
func (UUID) MarshalText ¶ added in v0.5.2
MarshalText marshals the UUID as a string
Implements the json.Marshaler interface
func (UUID) String ¶ added in v0.5.2
String returns the UUID as a string
If the UUID is uuid.Nil, an empty string is returned.
Implements the fmt.Stringer interface
func (*UUID) UnmarshalText ¶ added in v0.5.2
UnmarshalText unmarshals the UUID from a string
If the string is empty or null, the UUID is set to uuid.Nil.
Implements the json.Unmarshaler interface
Source Files
¶
- atoi.go
- decorate.go
- doc.go
- duration.go
- env.go
- exec-every.go
- exponential_backoff.go
- flexint.go
- http-responders.go
- identifiable.go
- maps_join.go
- must.go
- named.go
- reference.go
- registry.go
- registry_case_insensitive.go
- slices_contains.go
- slices_convert.go
- slices_equal.go
- slices_filter.go
- slices_find.go
- slices_join.go
- slices_map.go
- slices_reduce.go
- slices_sort.go
- string_capped.go
- time.go
- timestamp.go
- type-carrier.go
- type-gostring.go
- url.go
- uuid.go
- version.go
- zero.go