core

package module
v0.5.10 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2024 License: MIT Imports: 15 Imported by: 36

README

go-core

My core stuff with types, code, etc that I use almost everywhere

Slice generics

Contains

You can check if a slice contains a value with Contains method:

slice := []int{1, 2, 3, 4, 5}

fmt.Println(core.Contains(slice, 4)) // true
fmt.Println(core.Contains(slice, 6)) // false

Contains works with all comparable types.

If the slice type is more complex, you can use ContainsWithFunc method:

type User struct {
  ID int
  Name string
}

slice := []User{
  {ID: 1, Name: "John"},
  {ID: 2, Name: "Jane"},
  {ID: 3, Name: "Bob"},
}

fmt.Println(core.ContainsWithFunc(slice, User{Name: "John"}, func(a, b User) bool {
  return a.Name == b.Name
})) // true

If the struct implements the core.Named interface, you can use the EqualNamed method:

fmt.Println(core.ContainsWithFunc(slice, User{Name: "John"}, core.EqualNamed)) // true

Same goes for core.Identifiable and core.StringIdentifiable interfaces.

Find

You can find a value in a slice with Find method:

slice := []int{1, 2, 3, 4, 5}
number, found := core.Find(slice, 4)

Find works with all comparable types.

If the slice type is more complex, you can use FindWithFunc method:

type User struct {
  ID int
  Name string
}

slice := []User{
  {ID: 1, Name: "John"},
  {ID: 2, Name: "Jane"},
  {ID: 3, Name: "Bob"},
}

user, found := core.FindWithFunc(slice, User{Name: "John"}, func(a, b User) bool {
  return a.Name == b.Name
})

If the struct implements the core.Named interface, you can use the MatchNamed method:

fmt.Println(core.FindWithFunc(slice, User{Name: "John"}, core.MatchNamed)) // true

Same goes for core.Identifiable and core.StringIdentifiable interfaces.

EqualSlices

You can check if two slices are equal with EqualSlices method:

slice1 := []int{1, 2, 3, 4, 5}
slice2 := []int{1, 2, 3, 4, 5}

fmt.Println(core.EqualSlices(slice1, slice2)) // true

EqualSlices works with all comparable types.

If the slice type is more complex, you can use EqualSlicesWithFunc method:

type User struct {
  ID int
  Name string
}

slice1 := []User{
  {ID: 1, Name: "John"},
  {ID: 2, Name: "Jane"},
  {ID: 3, Name: "Bob"},
}

slice2 := []User{
  {ID: 1, Name: "John"},
  {ID: 2, Name: "Jane"},
  {ID: 3, Name: "Bob"},
}

fmt.Println(core.EqualSlicesWithFunc(slice1, slice2, func(a, b User) bool {
  return a.Name == b.Name
})) // true
Filter

You can filter a slice with Filter method:

slice := []int{1, 2, 3, 4, 5}

fmt.Println(core.Filter(slice, func(element int) bool {
  return element > 3
})) // [4 5]
Join

You can join a slice with Join method:

slice := []int{1, 2, 3, 4, 5}

fmt.Println(core.Join(slice, ",")) // 1,2,3,4,5

If the slice type is more complex, you can use JoinWithFunc method:

type User struct {
  ID int
  Name string
}

slice := []User{
  {ID: 1, Name: "John"},
  {ID: 2, Name: "Jane"},
  {ID: 3, Name: "Bob"},
}

fmt.Println(core.JoinWithFunc(slice, ",", func(element User) string {
  return element.Name
})) // John,Jane,Bob
Map

You can map a slice with Map method:

slice := []int{1, 2, 3, 4, 5}

fmt.Println(core.Map(slice, func(element int) int {
  return element * 2
})) // [2 4 6 8 10]

The returned slice is a new slice, the original slice is not modified.

Reduce

You can reduce a slice with Reduce method:

slice := []int{1, 2, 3, 4, 5}

fmt.Println(core.Reduce(slice, func(accumulator, element int) int {
  return accumulator + element
})) // 15
Sort

You can sort a slice with Sort method:

slice := []int{5, 2, 3, 1, 4}

fmt.Println(core.Sort(slice, func(a, b int) {
  return a < b
})) // [1 2 3 4 5]

The Sort method uses a simple Quick Sort algorithm.

Time and Duration helpers

The core.Time mimics the time.Time and adds JSON serialization support to and from RFC 3339 time strings.

The core.Duration mimics the time.Duration and adds JSON serialization support to and from duration strings. Its core.ParseDuration also understands most of the ISO 8601 duration formats. It marshals to milliseconds. It can unmarshal from milliseconds, GO duration strings, and ISO 8601 duration strings.

Example:

type User struct {
  Name      string
  CreatedAt core.Time
  Duration  core.Duration
}

user := User{
  Name:      "John",
  CreatedAt: core.Now(),
  Duration:  core.Duration(5 * time.Second),
}

data, err := json.Marshal(user)
if err != nil {
  panic(err)
}

fmt.Println(string(data))
// {"Name":"John","CreatedAt":"2021-01-01T00:00:00Z","Duration":"5000"}

string.Replace(string(data), "5000", "PT5S", 1)

var user2 User
err = json.Unmarshal(data, &user2)
if err != nil {
  panic(err)
}
fmt.Println(user2.Duration) // 5s

The core.Timestamp type is an alias for core.Time and it is used to represent timestamps in milliseconds. It marshals into milliseconds and unmarshals from milliseconds (string or integer).

Environment Variable helpers

You can get an environment variable with GetEnvAsX method, where X is one of bool, time.Duration, string, time.Time, url.URL, uuid.UUID, if the environment variable is not set or the conversion fails, the default value is returned.

Example:

// GetEnvAsBool
v := core.GetEnvAsBool("ENV_VAR", false)
// GetEnvAsDuration
v := core.GetEnvAsDuration("ENV_VAR", 5 * time.Second)
// GetEnvAsString
v := core.GetEnvAsString("ENV_VAR", "default")
// GetEnvAsTime
v := core.GetEnvAsTime("ENV_VAR", time.Now())
// GetEnvAsURL
v := core.GetEnvAsURL("ENV_VAR", &url.URL{Scheme: "https", Host: "example.com"})
// GetEnvAsUUID
v := core.GetEnvAsUUID("ENV_VAR", uuid.New())

Notes:

  • GetEnvAsBool returns true if the environment variable is set to true, 1, on or yes, otherwise it returns false. It is also case-insensitive.
  • GetEnvAsDuration accepts any duration string that can be parsed by core.ParseDuration.
  • GetEnvAsTime accepts an RFC 3339 time string.
  • GetEnvAsURL fallback can be a url.URL, a *url.URL, or a string.

Common Interfaces

The core.Identifiable interface is used to represent an object that has an ID in the form of a uuid.UUID.

The core.Nameable interface is used to represent an object that has a name in the form of a string.

The core.IsZeroer interface is used to represent an object that can be checked if it is zero.

The core.GoString interface is used to represent an object that can be converted to a Go string.

HTTP Response helpers

core.RespondWithJSON is a helper function that marshals a payload into an http.ResponseWriter as JSON. It also sets the Content-Type header to application/json.

core.RespondWithHTMLTemplate is a helper function that executes a template on a given data and writes the result into an http.ResponseWriter. It also sets the Content-Type header to text/html.

core.RespondWithError is a helper function that marshals an error into an http.ResponseWriter as JSON. It also sets the Content-Type header to application/json.

Miscelaneous

ExecEvery executes a function every duration:

stop, ping, change := core.ExecEvery(5 * time.Second, func() {
  fmt.Println("ping")
})

time.Sleep(15 * time.Second)
change <- 10 * time.Second
time.Sleep(15 * time.Second)
stop <- true

Notes:

  • stop is a channel that can be used to stop the execution.
  • ping is a channel that can be used to force the execution of the func at any time.
  • change is a channel that can be used to change the execution duration.

FlexInt, FlexInt8, FlexInt16, FlexInt32, FlexInt64 are types that can be unmarshalled from a string or an integer:

type User struct {
  ID core.FlexInt
}

user := User{}
json.Unmarshal([]byte(`{"ID": 1}`), &user)
json.Unmarshal([]byte(`{"ID": "1"}`), &user)

core.Must is a helper function that panics if the error is not nil from a function that returns a value and an error:

func DoSomething() (string, error) {
  return "", errors.New("error")
}

func main() {
  value := core.Must(DoSomething()).(string)
}

core.URL is an alias for url.URL that marshals as a string and unmarshals from a string. When unmarshaling, if the value is nil or empty, the unmarshaled value is nil (it is not considered as an error).

core.UUID is an alias for uuid.UUID that marshals as a string and unmarshals from a string. When unmarshaling, if the value is nil or empty, the unmarshaled value is uuid.Nil (it is not considered as an error).

core.TypeRegistry is a type registry that can be used to unmarshal JSON core.TypeCarrier objects into the correct type:

type User struct {
  ID   uuid.UUID
  Name string
}

func (user User) GetType() string {
  return "user"
}

type Product struct {
  ID   uuid.UUID
  Name string
}

func (product Product) GetType() string {
  return "product"
}

registry := core.NewTypeRegistry()

registry.Add(User{}, Product{})

var user User

err := registry.UnmarshalJSON([]byte(`{"type": "user", "ID": "00000000-0000-0000-0000-000000000000", "Name": "John"}`), &user)
if err != nil {
  panic(err)
}

fmt.Println(user)

Notes:

  • The default JSON property name for the type is type, but it can be changed by adding strings to the UnmarshalJSON method.

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

Examples

Constants

This section is empty.

Variables

View Source
var VERSION = "0.5.10"

VERSION is the version of this application

Functions

func Atoi added in v0.2.0

func Atoi(value string, fallback int) int

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

func ContainsWithFunc[T any](slice []T, value T, f func(T, T) bool) bool

ContainsWithFunc checks if a slice contains a value using a custom function.

func DecodeUUID added in v0.2.0

func DecodeUUID(encoded string) (uuid.UUID, error)

DecodeUUID decodes a UUID from a 22 char long string

func EncodeUUID added in v0.2.0

func EncodeUUID(uuid uuid.UUID) string

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

func EqualNamed[T Named](a, b T) bool

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

func EqualSlicesWithFunc[T any](a, b []T, compare func(T, T) bool) bool

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

func Filter[T any](items []T, filter func(T) bool) (result []T)

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

func FindWithFunc[T any](items []T, predicate func(T) bool) (t T, found bool)

FindWithFunc is a function that finds a value in a slice

func GetEnvAsBool added in v0.0.3

func GetEnvAsBool(name string, fallback bool) bool

GetEnvAsBool returns the bool value of an environment variable by its name

if not present, the fallback value is used

func GetEnvAsDuration

func GetEnvAsDuration(name string, fallback time.Duration) time.Duration

GetEnvAsDuration returns the time value of an environment variable by its name

if not present, the fallback value is used

func GetEnvAsInt

func GetEnvAsInt(name string, fallback int) int

GetEnvAsInt returns the int value of an environment variable by its name

if not present, the fallback value is used

func GetEnvAsString

func GetEnvAsString(name, fallback string) string

GetEnvAsString returns the string value of an environment variable by its name

if not present, the fallback value is used

func GetEnvAsTime

func GetEnvAsTime(name string, fallback time.Time) time.Time

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

func GetEnvAsURL(name string, fallback interface{}) *url.URL

GetEnvAsURL returns the URL value of an environment variable by its name

if not present, the fallback value is used

func GetEnvAsUUID added in v0.5.0

func GetEnvAsUUID(name string, fallback uuid.UUID) uuid.UUID

func Join added in v0.5.3

func Join[T fmt.Stringer](items []T, separator string) string

Join joins a slice of items into a string using a separator.

func JoinWithFunc added in v0.5.3

func JoinWithFunc[T any](items []T, separator string, stringer func(item T) string) string

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

func Map[T any, R any](items []T, mapper func(T) R) (result []R)

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

func MatchNamed[T Named](search T) func(T) bool

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

func Must[T any](value T, err error) T

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

func ParseDuration(value string) (duration time.Duration, err error)

ParseDuration parses an ISO8601 duration

If the given value is not an ISO8601 duration, returns time.ParseDuration

func Reduce added in v0.5.0

func Reduce[T any, R any](items []T, initial R, reducer func(R, T) R) (result R)

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

func Sort added in v0.5.0

func Sort[T any](items []T, sorter func(T, T) bool)

Sort sorts a slice of items using the Quick Sort algorithm

Note: The items slice is modified in place.

Example:

// Sort a slice of numbers
Sort(numbers, func(a, b int) bool {
	return a < b
})

Types

type DecoratedResource added in v0.5.10

type DecoratedResource struct {
	Data    any
	SelfURI string `json:"selfURI,omitempty"`
}

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

type Duration time.Duration

Duration is a placeholder so we can add new funcs to the type

func (Duration) MarshalJSON added in v0.1.0

func (duration Duration) MarshalJSON() ([]byte, error)

MarshalJSON marshals this into JSON

The duration is serialized in milliseconds

implements json.Marshaler interface

func (Duration) String added in v0.1.0

func (duration Duration) String() string

func (*Duration) UnmarshalJSON added in v0.1.0

func (duration *Duration) UnmarshalJSON(payload []byte) (err error)

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

func (i *FlexInt) UnmarshalJSON(payload []byte) error

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

func (i *FlexInt16) UnmarshalJSON(payload []byte) error

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

func (i *FlexInt32) UnmarshalJSON(payload []byte) error

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

func (i *FlexInt64) UnmarshalJSON(payload []byte) error

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

func (i *FlexInt8) UnmarshalJSON(payload []byte) error

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

type Identifiable interface {
	GetID() uuid.UUID
}

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

type Time time.Time

Time is a placeholder so we can add new funcs to the type

func Date added in v0.4.2

func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time

Date returns a new Date

func DateUTC added in v0.5.0

func DateUTC(year int, month time.Month, day, hour, min, sec, nsec int) Time

DateUTC returns a new Date

func Now added in v0.4.2

func Now() Time

Now returns the current local time

func NowIn added in v0.4.2

func NowIn(loc *time.Location) Time

NowIn returns the current time in the given location

func NowUTC added in v0.4.2

func NowUTC() Time

NowUTC returns the current UTC time

func ParseTime added in v0.4.2

func ParseTime(value string) (Time, error)

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

func ParseTimeIn(value string, loc *time.Location) (Time, error)

ParseTimeIn parses the given string for a Time, if the Time is not UTC it is set in the given location

func (Time) After added in v0.4.2

func (t Time) After(u Time) bool

After reports whether the time instant t is after u

func (Time) AsTime added in v0.4.2

func (t Time) AsTime() time.Time

AsTime converts a core.Time into a time.Time

func (Time) Before added in v0.4.2

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u

func (Time) BeginOfDay added in v0.4.2

func (t Time) BeginOfDay() Time

BeginOfDay returns the Beginning of the Day (i.e. midnight)

func (Time) Date added in v0.4.2

func (t Time) Date() (year int, month time.Month, day int)

Date returns the year, month, and day in which t occurs

func (Time) EndOfDay added in v0.4.2

func (t Time) EndOfDay() Time

EndOfDay returns the End of the Day (i.e. 1 second before midnight)

func (Time) Equal added in v0.4.2

func (t Time) Equal(u Time) bool

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

func (t Time) Format(layout string) string

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

func (t Time) IsZero() bool

IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC

func (Time) Location added in v0.4.2

func (t Time) Location() *time.Location

Location returns the time zone information associated with t

func (Time) MarshalJSON added in v0.2.0

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON marshals this into JSON

implements json.Marshaler interface

We store time as RFC3339 UTC

func (Time) String added in v0.4.2

func (t Time) String() string

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) Tomorrow added in v0.4.2

func (t Time) Tomorrow() Time

Tomorrow returns t shifted to tomorrow

func (Time) UTC added in v0.4.2

func (t Time) UTC() Time

UTC returns t with the location set to UTC

func (*Time) UnmarshalJSON added in v0.2.0

func (t *Time) UnmarshalJSON(payload []byte) (err error)

UnmarshalJSON decodes JSON

implements json.Unmarshaler interface

We read time as RFC3339 UTC

func (Time) Yesterday added in v0.4.2

func (t Time) Yesterday() Time

Yesterday returns t shifted to yesterday

type Timestamp

type Timestamp time.Time

Timestamp converts Unix Epoch to/from time.Time

func TimestampFromJSEpoch

func TimestampFromJSEpoch(epoch int64) Timestamp

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) JSEpoch

func (t Timestamp) JSEpoch() int64

JSEpoch returns the Unix Epoch like Javascript (i.e. in ms)

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON encodes a TimeStamp to its JSON Epoch

implements json.Marshaler interface

func (Timestamp) String

func (t Timestamp) String() string

String gives the string representation of this

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(payload []byte) (err error)

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

type TypeRegistry map[string]reflect.Type

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

type URL url.URL

URL is a placeholder so we can add new funcs to the type

func (URL) AsURL added in v0.4.2

func (u URL) AsURL() url.URL

AsURL converts a core.URL into a url.URL

func (URL) MarshalJSON added in v0.2.0

func (u URL) MarshalJSON() ([]byte, error)

MarshalJSON marshals this into JSON

implements json.Marshaler interface

func (*URL) String added in v0.2.0

func (u *URL) String() string

func (*URL) UnmarshalJSON added in v0.2.0

func (u *URL) UnmarshalJSON(payload []byte) (err error)

UnmarshalJSON decodes JSON

implements json.Unmarshaler interface

type UUID added in v0.5.2

type UUID uuid.UUID

func (UUID) IsZero added in v0.5.2

func (id UUID) IsZero() bool

IsZero returns true if the UUID is uuid.Nil

func (UUID) MarshalText added in v0.5.2

func (id UUID) MarshalText() ([]byte, error)

MarshalText marshals the UUID as a string

Implements the json.Marshaler interface

func (UUID) String added in v0.5.2

func (id UUID) String() string

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

func (id *UUID) UnmarshalText(payload []byte) (err error)

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

Jump to

Keyboard shortcuts

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