Documentation ¶
Overview ¶
This package contains various helpers for the Go language
TypeRegistry ¶
The TypeRegistry can be used to unmarshal JSON data into interfaces.
The interface members must implement core.TypeCarrier.
See the example in #TypeRegistry.UnmarshalJSON
Index ¶
- Variables
- func Atoi(value string, fallback int) int
- func Contains[T comparable](slice []T, value T) bool
- func ContainsWithFunc[T any](slice []T, value T, f func(T, T) bool) bool
- 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[T comparable](a, b []T) bool
- func EqualSlicesWithFunc[T any](a, b []T, 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 Filter[T any](items []T, filter func(T) bool) (result []T)
- func Find[T comparable](items []T, value T) (t T, found bool)
- func FindWithFunc[T any](items []T, 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 interface{}) *url.URL
- func GetEnvAsUUID(name string, fallback uuid.UUID) uuid.UUID
- func Join[T fmt.Stringer](items []T, separator string) string
- func JoinWithFunc[T any](items []T, separator string, stringer func(item T) string) string
- func Map[T any, R any](items []T, 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 interface{})
- func Sort[T any](items []T, sorter func(T, T) bool)
- type DecoratedResource
- type Duration
- type FlexInt
- type FlexInt16
- type FlexInt32
- type FlexInt64
- type FlexInt8
- 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 ¶
Constants ¶
This section is empty.
Variables ¶
var VERSION = "0.5.10"
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 Contains ¶ added in v0.5.3
func Contains[T comparable](slice []T, value T) bool
Contains checks if a slice contains a value.
func ContainsWithFunc ¶ added in v0.5.3
ContainsWithFunc checks if a slice contains a value using a custom function.
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
RqualNamed compares two values for equality by name
func EqualSlices ¶ added in v0.5.3
func EqualSlices[T comparable](a, b []T) 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.
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.
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 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 })
func Find ¶ added in v0.5.9
func Find[T comparable](items []T, value T) (t T, found bool)
Find finds a value in a slice
func FindWithFunc ¶ added in v0.5.9
FindWithFunc is a function that finds a value in a slice
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 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.
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 squares := Map(numbers, func(number int) int { return number * number })
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 })
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 interface{})
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 interface{})
RespondWithJSON will send a reply with a JSON payload and a HTTP Status code
Types ¶
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) MarshalJSON ¶ added in v0.1.0
MarshalJSON marshals this into JSON
The duration is serialized in milliseconds ¶
implements json.Marshaler interface
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
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 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 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 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) UnmarshalJSON ¶ added in v0.4.9
func (registry TypeRegistry) UnmarshalJSON(payload []byte, typetag ...string) (interface{}, 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) 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
- contains.go
- decorate.go
- doc.go
- duration.go
- env.go
- equal_slices.go
- exec-every.go
- filter.go
- find.go
- flexint.go
- http-responders.go
- identifiable.go
- join.go
- map.go
- must.go
- named.go
- reduce.go
- registry.go
- sort.go
- time.go
- timestamp.go
- type-carrier.go
- type-gostring.go
- url.go
- uuid.go
- version.go
- zero.go