types

package
v14.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 14 Imported by: 0

README

Iris REST Types Sub-Package Documentation

Overview

The rest/types sub-package provides various Go types that are ready to be used when dealing with JSON APIs and SQL drivers in Go. These types are particularly useful as field types for API request and response structures. This documentation covers the following types, and the Parse function of each type that has one:

  • DayTime
  • Duration
  • ISO8601
  • KitchenTime
  • Number
  • SimpleDate
  • Season
  • StringOrArray
  • TimeNotationDuration
  • Weekday

The helpers that are not field types (Merge, GetSimpleDateRange, RegisterFixedLocation and the rest) are listed at the end, under Other exports.

import "github.com/kataras/iris/v14/rest/types"
SQL Compatibility

These types can be used to read and write to SQL columns. They implement the sql.Scanner and driver.Valuer interfaces, making them compatible with SQL databases like PostgreSQL.

DayTime

The DayTime type represents a time compatible with the "hour:minute:second" format. It is useful for representing times of day without a date component, such as opening hours or event times.

Parse Method
ParseDayTime

Parses a string into a DayTime.

func ParseDayTime(s string) (DayTime, error)
Example
dt, err := types.ParseDayTime("15:04:05")
if err != nil {
    log.Fatal(err)
}
Handler Example
Input
type Request struct {
    Time types.DayTime `json:"time"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Time types.DayTime `json:"time"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Time: types.DayTime{Hour: 15, Minute: 4, Second: 5}}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "time": "15:04:05"
}

Duration

The Duration type is a JSON representation of the standard time.Duration type. It is useful for representing time intervals, such as durations of events or timeouts.

Parse Method
ParseDuration

Parses a string into a Duration just like the standard time.ParseDuration function.

func ParseDuration(s string) (Duration, error)
Example
d, err := types.ParseDuration("1h30m")
if err != nil {
    log.Fatal(err)
}
Handler Example
Input
type Request struct {
    Duration types.Duration `json:"duration"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Duration types.Duration `json:"duration"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Duration: types.Duration{Duration: time.Hour + 30*time.Minute}}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "duration": "1h30m0s"
}

ISO8601

The ISO8601 type represents a time compatible with the JavaScript ISO time format. It is useful for representing timestamps in a format that is widely used in web APIs and JavaScript applications.

Parse Method
ParseISO8601

Parses a string into an ISO8601 time.

func ParseISO8601(s string) (types.ISO8601, error)
Example
iso, err := types.ParseISO8601("2024-01-02T15:04:05Z")
if err != nil {
    log.Fatal(err)
}
Handler Example
Input
type Request struct {
    Time types.ISO8601 `json:"time"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Time types.ISO8601 `json:"time"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Time: types.ISO8601{Time: time.Now()}}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "time": "2024-01-02T15:04:05Z"
}

KitchenTime

The KitchenTime type represents a time compatible with the "3:04 PM" format. It is useful for representing times in a 12-hour clock format, commonly used in user interfaces and reports.

Parse Method
ParseKitchenTime

Parses a string into a KitchenTime.

func ParseKitchenTime(s string) (KitchenTime, error)
Example
kt, err := types.ParseKitchenTime("3:04 PM")
if err != nil {
    log.Fatal(err)
}
Handler Example
Input
type Request struct {
    Time types.KitchenTime `json:"time"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Time types.KitchenTime `json:"time"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Time: types.KitchenTime{Hour: 15, Minute: 4, Period: "PM"}}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "time": "3:04 PM"
}

Number

The Number type is a float64 with a JSON null. NaN and the two infinities marshal as null and a JSON null unmarshals back to NaN; a plain float64 fails to marshal instead, which takes the whole document with it when an average or a ratio comes out undefined. On the SQL side the same rule holds: a NULL column scans to NaN and a NaN value is written as NULL, so a nullable float8 column needs no sql.NullFloat64 wrapper.

The zero value is the number zero, not null. NullNumber() returns the null one and IsNull() reports it.

func NullNumber() Number
func (n Number) IsNull() bool
func (n Number) Float64() float64

Number has no Parse: types.Number(f) is the conversion, and a text value goes through Scan.

Example
type Response struct {
    Ratio types.Number `json:"ratio"`
}

func handleResponse(ctx iris.Context) {
    ctx.JSON(Response{Ratio: types.Number(math.NaN())})
}
Raw JSON Output
{
    "ratio": null
}

SimpleDate

The SimpleDate type represents a date in the "year-month-day" format. It is useful for representing dates without a time component, such as birthdates or event dates.

Parse Method
ParseSimpleDate

Parses a string into a SimpleDate.

func ParseSimpleDate(s string) (SimpleDate, error)
Example
sd, err := types.ParseSimpleDate("2024-01-01")
if err != nil {
    log.Fatal(err)
}
Handler Example
Input
type Request struct {
    Date types.SimpleDate `json:"date"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Date types.SimpleDate `json:"date"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Date: types.SimpleDateFromTime(time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC))}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "date": "2024-01-01"
}
URL Parameter Input Example
func handleRequest(ctx iris.Context) {
    dateStr := ctx.Query().Get("date")
    date, err := types.ParseSimpleDate(dateStr)
    if err != nil {
        errors.InvalidArgument.Err(ctx, err)
        return
    }
    ctx.JSON(iris.Map{"date": date})
}
URL Example
GET /api/date?date=2024-10-30

As a struct field it needs no parsing of your own. SimpleDate implements encoding.TextUnmarshaler, so ctx.ReadQuery, ctx.ReadParams, ctx.ReadURL, ctx.ReadForm and ctx.ReadHeader fill a SimpleDate field from a YYYY-MM-DD value, and an absent key leaves it zero:

type ReportQuery struct {
    From  types.SimpleDate `url:"from"`
    To    types.SimpleDate `url:"to"`
    Limit int              `url:"limit"`
}

func listReports(ctx iris.Context) {
    var q ReportQuery
    if err := ctx.ReadQuery(&q); err != nil {
        errors.InvalidArgument.Err(ctx, err)
        return
    }
    ctx.JSON(q)
}
GET /api/reports?from=2024-09-01&to=2024-09-30&limit=3

A time.Time field in the same readers expects RFC 3339 (2024-09-01T00:00:00Z). The matching MarshalText is what the YAML, XML and MsgPack encoders write for a SimpleDate, the same 2024-09-01 text. JSON keeps going through MarshalJSON and UnmarshalJSON.

Season

The Season type is a bitmask of seasons (Winter, Spring, Summer, Autumn). It is useful for representing multiple seasons in a single value, such as seasonal availability or preferences.

Handler Example
Input
type Request struct {
    Season types.Season `json:"season"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Season types.Season `json:"season"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Season: types.Winter}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "season": 1
}
Multiple Seasons Example
type Request struct {
    Seasons types.Season `json:"seasons"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Seasons types.Season `json:"seasons"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Seasons: types.Winter | types.Spring}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "seasons": 3
}
String Method

The String method returns the string representation of the season(s).

Example
season := Winter | Spring
fmt.Println(season.String()) // Output: "Winter, Spring"

StringOrArray

The StringOrArray type can be a single string or an array of strings. It marshals and unmarshals as a single string joined by commas. This is useful for handling flexible input formats in APIs.

UnmarshalJSON Method
UnmarshalJSON

Parses JSON data into a StringOrArray.

func (soa *StringOrArray) UnmarshalJSON(data []byte) error
Example
var soa types.StringOrArray
err := json.Unmarshal([]byte(`["value1", "value2"]`), &soa)
if err != nil {
    log.Fatal(err)
}
Handler Example
Input
type Request struct {
    Values types.StringOrArray `json:"values"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Values types.StringOrArray `json:"values"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Values: types.StringOrArray(`["value1","value2"]`)}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "values": "value1,value2"
}

TimeNotationDuration

The TimeNotationDuration type represents a duration in a human-readable format, such as "hours:minutes:seconds". It is useful for representing durations or fixed times in a format that is easy for users to understand.

Parse Method
ParseTimeNotationDuration

Parses a string into a TimeNotationDuration.

func ParseTimeNotationDuration(s string) (TimeNotationDuration, error)
Example
tnd, err := types.ParseTimeNotationDuration("01:30:00")
if err != nil {
    log.Fatal(err)
}
Handler Example
Input
type Request struct {
    Duration types.TimeNotationDuration `json:"duration"`
}

func handleRequest(ctx iris.Context) {
    req, ok := ctx.BindJSON[Request]()
    if !ok {
        return // 400 already written.
    }
    ctx.OK(req, nil)
}
Output
type Response struct {
    Duration types.TimeNotationDuration `json:"duration"`
}

func handleResponse(ctx iris.Context) {
    resp := Response{Duration: types.TimeNotationDuration(time.Hour + 30*time.Minute)}
    ctx.JSON(resp)
}
Raw JSON Output
{
    "duration": "01:30:00"
}

Weekday

The Weekday type is a time.Weekday which travels as a lowercase name, so a client reading a schedule gets a word it can print instead of a number whose base it has to guess. The numbering is time.Weekday's, Sunday being zero, which means the zero value marshals as "sunday".

Parse Method
ParseWeekday

Parses a string into a Weekday, in any case and in the long or the three letter form: "Monday", "monday", "MON" and "mon" are the same day.

func ParseWeekday(s string) (Weekday, error)
Example
d, err := types.ParseWeekday("MON")
if err != nil {
    log.Fatal(err)
}

d.String() // "monday"
d.Std()    // time.Monday

The seven days are exported as constants (types.Sunday .. types.Saturday), Std() converts out to time.Weekday and WeekdayOf(time.Weekday) converts in.

Output
type Response struct {
    Day types.Weekday `json:"day"`
}

func handleResponse(ctx iris.Context) {
    ctx.JSON(Response{Day: types.Weekday(time.Monday)})
}
Raw JSON Output
{
    "day": "monday"
}

The SQL column is text: Value writes the lowercase name and Scan reads a text column by name or an integer one by time.Weekday's numbering.

Other exports

The package also carries a few helpers that are not field types.

  • Merge(values ...any) json.Marshaler and MergeJSON(values ...any) ([]byte, error) combine several values into one JSON object. Each non-nil value must marshal to an object; a string or []byte is taken as raw JSON; nil values and {} contribute nothing. Overlapping keys keep the first position and the last value. The parts marshal with the framework's json/v2 policy, so a struct renders the same inside Merge as through ctx.JSON. Merged is the type Merge returns; its Values field holds the parts.
ctx.JSON(types.Merge(user, iris.Map{"role": "admin"}))
  • SimpleDates is a []SimpleDate with Contains(date) and DateStrings(). GetSimpleDateRange(date, typ, startWeekday, endWeekday) returns the dates of the week or the month around date: typ is a DateRangeType (DayRange, WeekRange, MonthRange, YearRange), but only WeekRange and MonthRange are implemented; the other two panic. The two weekdays are used by WeekRange only.
day := types.SimpleDateFromTime(time.Date(2024, time.January, 10, 0, 0, 0, 0, time.UTC))
week := types.GetSimpleDateRange(day, types.WeekRange, time.Monday, time.Sunday)
week.Contains(day.AddDate(0, 0, 4)) // true: 2024-01-14 is the Sunday of that week
  • RegisterFixedLocation(name, secondsFromUTC) teaches the time parsers a zone abbreviation, for input such as 2023-02-04T09:48:14+03:00 that should print as EEST. Call it once at program start: types.RegisterFixedLocation("EEST", 3*60*60).

  • Exampler is the interface (ListExamples() any) the package's tests use to generate sample values for each type. Implement it on your own types only if you reuse that test helper.

Documentation

Index

Constants

View Source
const (
	// ISO8601Layout holds the time layout for the the javascript iso time.
	// Read more at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString.
	ISO8601Layout = "2006-01-02T15:04:05"
	// ISO8601LayoutWithTimezone same as ISO8601Layout but with the timezone suffix.
	ISO8601LayoutWithTimezone = "2006-01-02T15:04:05Z"

	// To match Go’s standard time layout that pads zeroes for microseconds, you can use the format 2006-01-02T15:04:05.000000Z07:00.
	// This layout uses 0s instead of 9s for the fractional second part, which ensures that the microseconds are
	// always represented with six digits, padding with leading zeroes if necessary.
	// ISO8601ZUTCOffsetLayoutWithMicroseconds = "2006-01-02T15:04:05.000000Z07:00"
	// ISO8601ZUTCOffsetLayoutWithMicroseconds ISO 8601 format, with full time and zone with UTC offset.
	// Example: 2022-08-10T03:21:00.000000+03:00, 2023-02-04T09:48:14+00:00, 2022-08-09T00:00:00.000000.
	ISO8601ZUTCOffsetLayoutWithMicroseconds = "2006-01-02T15:04:05.999999Z07:00"
	// ISO8601ZUTCOffsetLayoutWithoutMicroseconds ISO 8601 format, with full time and zone with UTC offset without microsecond precision.
	ISO8601ZUTCOffsetLayoutWithoutMicroseconds = "2006-01-02T15:04:05Z07:00"

	// ISO8601UnconventionalOffsetLayout is the layout for the unconventional offset.
	// Custom offset layout, e.g., 2024-05-21T18:06:07.000000-04:01:19.
	ISO8601UnconventionalOffsetLayout = "2006-01-02T15:04:05.000000"
)
View Source
const (
	Sunday    = Weekday(time.Sunday)
	Monday    = Weekday(time.Monday)
	Tuesday   = Weekday(time.Tuesday)
	Wednesday = Weekday(time.Wednesday)
	Thursday  = Weekday(time.Thursday)
	Friday    = Weekday(time.Friday)
	Saturday  = Weekday(time.Saturday)
)

The seven days, so a call site reads types.Monday rather than types.Weekday(time.Monday). The values are time.Weekday's.

View Source
const (
	// DayTimeLayout holds the time layout for the the format of "hour:minute:second", hour can be 15, meaning 3 PM.
	DayTimeLayout = "15:04:05"
)
View Source
const KitchenTimeLayout = "3:04 PM"

KitchenTimeLayout represents the "3:04 PM" Go time format, similar to time.Kitchen.

View Source
const (
	// SimpleDateLayout represents the "year-month-day" Go time format.
	SimpleDateLayout = "2006-01-02"
)

Variables

View Source
var (

	// ErrInvalid is returned when the value is invalid.
	ErrInvalid = errors.New("invalid")
)
View Source
var ErrParseKitchenTimeColon = fmt.Errorf("parse kitchen time: missing ':' character")

Functions

func Merge

func Merge(values ...any) json.Marshaler

Merge takes any number of JSON-serializable objects and returns a json.Marshaler that combines the objects.

Usage:

ctx.JSON(types.Merge(obj1, obj2, obj3))

func MergeJSON

func MergeJSON(values ...any) ([]byte, error)

MergeJSON merges a variadic number of values into a single JSON object. Each non-nil value must marshal to a JSON object; a string or []byte value is taken as raw JSON. Nil values and empty objects ("{}") contribute nothing. Values marshal with the framework's JSON policy (see core/pkg/jsonutil), so a struct renders the same here as through ctx.JSON.

A member name present in more than one value appears once in the result, in the position of its first occurrence, with the value of its last occurrence: the later object wins. The output never carries duplicate names, so any strict decoder (the framework's own client included) can read it.

Returns an error if any non-nil value does not marshal to a JSON object.

func RegisterFixedLocation

func RegisterFixedLocation(name string, secondsFromUTC int)

RegisterFixedLocation should be called on initialization of the program. It registers a fixed location to the time parser.

E.g. for input of 2023-02-04T09:48:14+03:00 to result a time string of 2023-02-04 09:48:14 +0300 EEST you have to RegisterFixedLocation("EEST", 10800) otherwise it will result to: 2023-02-04 09:48:14 +0300 +0300.

Types

type DateRangeType

type DateRangeType string

DateRangeType is the type of the date range.

const (
	// DayRange is the date range type of a day.
	DayRange DateRangeType = "day"
	// MonthRange is the date range type of a month.
	MonthRange DateRangeType = "month"
	// WeekRange is the date range type of a week.
	WeekRange DateRangeType = "week"
	// YearRange is the date range type of a year.
	YearRange DateRangeType = "year"
)

type DayTime

type DayTime time.Time

DayTime describes a time compatible with DayTimeLayout.

func ParseDayTime

func ParseDayTime(s string) (DayTime, error)

ParseDayTime reads from "s" and returns the DayTime time.

func (DayTime) IsZero

func (t DayTime) IsZero() bool

IsZero reports whether "t" is zero time.

func (DayTime) MarshalJSON

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

MarshalJSON writes a quoted string in the DayTime time format.

func (*DayTime) Scan

func (t *DayTime) Scan(src any) error

Scan completes the sql driver.Scanner interface.

func (DayTime) String

func (t DayTime) String() string

String returns the text representation of the "t" using the DayTime time layout.

func (*DayTime) ToTime

func (t *DayTime) ToTime() time.Time

ToTime returns the unwrapped *t to time.Time.

func (*DayTime) UnmarshalJSON

func (t *DayTime) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the "b" into DayTime time.

type Duration

type Duration time.Duration

Duration is a JSON representation of the standard Duration type, until Go version 2 supports it under the hood.

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration parses a string to a duration. It is a wrapper around time.ParseDuration.

func (Duration) MarshalJSON

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

func (*Duration) Set

func (d *Duration) Set(v float64)

Set sets the value of duration in nanoseconds.

func (Duration) ToDuration

func (d Duration) ToDuration() time.Duration

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

func (Duration) Value

func (d Duration) Value() (driver.Value, error)

type Exampler

type Exampler interface {
	ListExamples() any
}

Exampler is an interface used by testing to generate examples.

type ISO8601

type ISO8601 time.Time

ISO8601 describes a time compatible with javascript time format.

func ParseISO8601

func ParseISO8601(s string) (ISO8601, error)

ParseISO8601 reads from "s" and returns the ISO8601 time.

The function supports the following formats:

  • 2024-01-02T15:04:05.999999Z
  • 2024-01-02T15:04:05+07:00
  • 2024-04-08T08:05:04.830140+00:00
  • 2024-01-02T15:04:05Z
  • 2024-04-08T08:05:04.830140
  • 2024-01-02T15:04:05
  • 2024-05-21T18:06:07.000000-04:01:19

func (ISO8601) Add

func (t ISO8601) Add(d time.Duration) ISO8601

Add returns the time "t" with the duration added.

func (ISO8601) After

func (t ISO8601) After(u ISO8601) bool

After reports whether the time instant "t" is after "u".

func (ISO8601) Before

func (t ISO8601) Before(u ISO8601) bool

Before reports whether the time instant "t" is before "u".

func (ISO8601) Equal

func (t ISO8601) Equal(u ISO8601) bool

Equal reports whether the time instant "t" is equal to "u".

func (ISO8601) In

func (t ISO8601) In(loc *time.Location) ISO8601

In returns a new ISO8601 time in the specified location.

func (ISO8601) IsZero

func (t ISO8601) IsZero() bool

IsZero reports whether "t" is zero time. It completes the pg.Zeroer interface.

func (ISO8601) ListExamples

func (t ISO8601) ListExamples() any

ListExamples returns a list of example values. It completes the Exampler interface.

func (ISO8601) MarshalJSON

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

MarshalJSON writes a quoted string in the ISO8601 time format.

func (*ISO8601) Scan

func (t *ISO8601) Scan(src any) error

Scan completes the sql driver.Scanner interface.

func (ISO8601) String

func (t ISO8601) String() string

String returns the text representation of the "t" using the ISO8601 time layout.

func (ISO8601) Sub

func (t ISO8601) Sub(u ISO8601) time.Duration

Sub returns the duration between "t" and "u".

func (ISO8601) To24Hour

func (t ISO8601) To24Hour() string

To24Hour returns the 24-hour representation of the time.

func (ISO8601) ToDayTime

func (t ISO8601) ToDayTime() DayTime

ToDayTime converts the current ISO8601 "t" to DayTime.

func (ISO8601) ToSimpleDate

func (t ISO8601) ToSimpleDate() SimpleDate

ToSimpleDate converts the current ISO8601 "t" to SimpleDate.

func (ISO8601) ToSimpleDateIn

func (t ISO8601) ToSimpleDateIn(in *time.Location) SimpleDate

ToSimpleDateIn converts the current ISO8601 "t" to SimpleDate in specific location.

func (ISO8601) ToTime

func (t ISO8601) ToTime() time.Time

ToTime returns the unwrapped *t to time.Time.

func (*ISO8601) UnmarshalJSON

func (t *ISO8601) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the "b" into ISO8601 time.

func (ISO8601) Value

func (t ISO8601) Value() (driver.Value, error)

Value returns the database value of time.Time.

type KitchenTime

type KitchenTime time.Time

KitchenTime holds a json "3:04 PM" time.

func ParseKitchenTime

func ParseKitchenTime(s string) (KitchenTime, error)

ParseKitchenTime reads from "s" and returns the KitchenTime time.

func (KitchenTime) IsZero

func (t KitchenTime) IsZero() bool

IsZero reports whether "t" is zero time. It completes the pg.Zeroer interface.

func (KitchenTime) MarshalJSON

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

MarshalJSON returns the json representation of the "t".

func (*KitchenTime) Scan

func (t *KitchenTime) Scan(src any) error

Scan completes the pg and native sql driver.Scanner interface reading functionality of a custom type.

func (KitchenTime) String

func (t KitchenTime) String() string

String returns the text representation of the date formatted based on the `KitchenTimeLayout`. If date is zero it returns an empty string.

func (KitchenTime) To24Hour

func (t KitchenTime) To24Hour() string

To24Hour returns the 24-hour representation of the time.

func (*KitchenTime) UnmarshalJSON

func (t *KitchenTime) UnmarshalJSON(data []byte) error

UnmarshalJSON binds the json "data" to "t" with the `KitchenTimeLayout`.

func (KitchenTime) Value

func (t KitchenTime) Value() time.Time

Value returns the standard time type.

type Merged

type Merged struct {
	Values []any
}

Merged holds a slice of JSON-serializable objects to be Merged together.

func (Merged) MarshalJSON

func (m Merged) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for the merged type.

type Number

type Number float64

Number is a float64 which has a JSON null: NaN and the two infinities marshal as null and a JSON null unmarshals back to NaN. A plain float64 cannot do that, because encoding/json refuses to encode a value which JSON has no literal for, and a computed average or ratio produces those values often enough that the whole document would fail to render.

The zero value is the number zero, not null. Use NullNumber for the null one and IsNull to test for it.

On the database side the same rule holds: a NULL column scans to NaN and a NaN value is written as NULL, so a float8 column and this type agree on what "no value" means.

func NullNumber

func NullNumber() Number

NullNumber returns the null Number, the one which marshals as null and is written to the database as NULL.

func (Number) Float64

func (n Number) Float64() float64

Float64 returns the number as a float64. A null Number returns NaN, so check IsNull first when the difference matters.

func (Number) IsNull

func (n Number) IsNull() bool

IsNull reports whether the number has no value: NaN, or one of the two infinities, all of which render as null.

func (Number) MarshalJSON

func (n Number) MarshalJSON() ([]byte, error)

MarshalJSON renders the number for encoding/json (v1) interop: a downstream logger or a v1 encoder gets the same bytes MarshalJSONTo writes.

func (Number) MarshalJSONTo

func (n Number) MarshalJSONTo(enc *jsontext.Encoder) error

MarshalJSONTo writes the number straight into the encoder, which is the path ctx.JSON takes, with no intermediate byte slice.

func (*Number) Scan

func (n *Number) Scan(src any) error

Scan completes the sql.Scanner interface. A NULL column becomes NaN, so a nullable float8 needs no sql.NullFloat64 wrapper. Text-mode drivers give the value as a string or as raw bytes; both are parsed.

An empty text is an error and not a null: a number column which holds no value holds NULL, and empty text from a numeric column means the driver gave something unexpected. Weekday, whose column is text, takes the opposite view and leaves the value alone.

func (Number) String

func (n Number) String() string

String returns the JSON text of the number, and "null" when it has no value. It is the encoder's own formatter, so String, MarshalJSON and MarshalJSONTo always agree: a large value renders as 1e+21 on all three, where a plain strconv 'f' would write it out in full on one of them only.

func (*Number) UnmarshalJSON

func (n *Number) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the number for encoding/json (v1) interop. A JSON null becomes NaN.

A quoted number is rejected here as it is by UnmarshalJSONFrom: the two paths accept exactly the same documents, so a payload cannot decode under one encoder and fail under the other.

func (*Number) UnmarshalJSONFrom

func (n *Number) UnmarshalJSONFrom(dec *jsontext.Decoder) error

UnmarshalJSONFrom reads the number from the decoder. A JSON null becomes NaN, the value this type calls null.

func (Number) Value

func (n Number) Value() (driver.Value, error)

Value completes the driver.Valuer interface: a null Number is written as NULL, every other one as a float8.

type Season

type Season int

Season is a bitmask of seasons Winter, Spring, Summer, Autumn. It is used to represent the seasons of a year. It is a bitmask so that multiple seasons can be set at once. It has methods to check if a season is set, add a season, remove a season, and get a string representation of the seasons.

const (
	// December, January, February.
	Winter Season = 1 << iota // 1 << 0 = 1
	// March, April, May.
	Spring // 1 << 1 = 2
	// June, July, August.
	Summer // 1 << 2 = 4
	// September, October, November.
	Autumn // 1 << 3 = 8

	// AllSeasons is a bitmask of all seasons.
	// It's the number 15 because it's the sum of all seasons.
	AllSeasons = Winter | Spring | Summer | Autumn // 1 + 2 + 4 + 8 = 15
)

func GetSeasonByDate

func GetSeasonByDate(date SimpleDate) Season

GetSeasonByDate returns the season based on the given date.

func (*Season) Add

func (s *Season) Add(season Season)

Add adds a season to the bitmask.

func (Season) Is

func (s Season) Is(season Season) bool

Is checks if the season is set in the bitmask.

func (Season) IsValid

func (s Season) IsValid() bool

IsValid checks if the season is valid.

func (*Season) Remove

func (s *Season) Remove(season Season)

Remove removes a season from the bitmask.

func (Season) String

func (s Season) String() string

String returns the string representation of the season(s).

func (*Season) UnmarshalJSON

func (s *Season) UnmarshalJSON(data []byte) error

UnmarshalJSON parses the JSON value into a Season bitmask. The value is read as an integer, a zero value means AllSeasons. It returns ErrInvalid if the resulting bitmask is not a valid Season.

type SimpleDate

type SimpleDate time.Time

SimpleDate holds a json "year-month-day" time.

func ParseSimpleDate

func ParseSimpleDate(s string) (SimpleDate, error)

ParseSimpleDate reads from "s" and returns the SimpleDate time.

The function supports the following formats:

  • "2024-01-01"
  • "2024-1-1"

func SimpleDateFromTime

func SimpleDateFromTime(t time.Time) SimpleDate

SimpleDateFromTime accepts a "t" Time and returns a SimpleDate. If format fails, it returns the zero value of time.Time.

func (SimpleDate) Add

Add returns the date of "t" plus "d".

func (SimpleDate) AddDate

func (t SimpleDate) AddDate(years, months, days int) SimpleDate

AddDate returns the date of "t" plus "years", "months" and "days".

func (SimpleDate) After

func (t SimpleDate) After(d2 SimpleDate) bool

After reports whether the time instant t is after u.

func (SimpleDate) Before

func (t SimpleDate) Before(d2 SimpleDate) bool

Before reports whether the time instant t is before u.

func (SimpleDate) CountPastDays

func (t SimpleDate) CountPastDays(pastDate SimpleDate) int

CountPastDays returns the count of days between "t" and "pastDate".

func (SimpleDate) Equal

func (t SimpleDate) Equal(d SimpleDate) bool

Equal reports back if "t" and "d" equals to the same date.

func (SimpleDate) IsZero

func (t SimpleDate) IsZero() bool

IsZero reports whether "t" is zero time. It completes the pg.Zeroer interface.

func (SimpleDate) ListExamples

func (t SimpleDate) ListExamples() any

ListExamples returns a list of example values. It completes the Exampler interface.

func (SimpleDate) MarshalJSON

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

MarshalJSON returns the json representation of the "t".

func (SimpleDate) MarshalText added in v14.0.1

func (t SimpleDate) MarshalText() ([]byte, error)

MarshalText returns the "2006-01-02" text of "t", empty for the zero date.

It completes the encoding.TextMarshaler interface. An encoder that reads through UnmarshalText, such as msgpack, has to write through this one: without it the date is written as an empty map that it cannot read back.

func (*SimpleDate) Scan

func (t *SimpleDate) Scan(src any) error

Scan completes the pg and native sql driver.Scanner interface reading functionality of a custom type.

func (SimpleDate) String

func (t SimpleDate) String() string

String returns the text representation of the date formatted based on the `SimpleDateLayout`. If date is zero it returns an empty string.

func (SimpleDate) ToTime

func (t SimpleDate) ToTime() time.Time

ToTime returns the standard time type.

func (*SimpleDate) UnmarshalJSON

func (t *SimpleDate) UnmarshalJSON(data []byte) error

UnmarshalJSON binds the json "data" to "t" with the `SimpleDateLayout`.

func (*SimpleDate) UnmarshalText added in v14.0.1

func (t *SimpleDate) UnmarshalText(text []byte) error

UnmarshalText parses a "2006-01-02" text into "t", with the same `SimpleDateLayout` the json decoding uses. An empty text leaves "t" as it is.

It completes the encoding.TextUnmarshaler interface, which is how the Context's ReadQuery, ReadParams, ReadURL, ReadForm and ReadHeader fill a SimpleDate struct field.

func (SimpleDate) Value

func (t SimpleDate) Value() (driver.Value, error)

Value completes the pg and native sql driver.Valuer interface.

func (SimpleDate) Weekday

func (t SimpleDate) Weekday() time.Weekday

Weekday returns the day of the week for the date.

type SimpleDates

type SimpleDates []SimpleDate

SimpleDates is a slice of SimpleDate.

func GetSimpleDateRange

func GetSimpleDateRange(date SimpleDate, typ DateRangeType, startWeekday, endWeekday time.Weekday) SimpleDates

GetSimpleDateRange returns a slice of SimpleDate between the "start" and "end" of "date" based on given "typ". Only WeekRange and MonthRange are supported, any other value, including DayRange and YearRange, panics. The "startWeekday" and "endWeekday" arguments are used by WeekRange only.

Example Code: date := types.SimpleDateFromTime(time.Now()) dates := types.GetSimpleDateRange(date, types.WeekRange, time.Monday, time.Sunday)

func (SimpleDates) Contains

func (t SimpleDates) Contains(date SimpleDate) bool

Contains reports if the "date" exists inside "t".

func (SimpleDates) DateStrings

func (t SimpleDates) DateStrings() []string

DateStrings returns a slice of string representation of the dates.

func (SimpleDates) First

func (t SimpleDates) First() SimpleDate

First returns the first element of the date slice.

func (SimpleDates) Last

func (t SimpleDates) Last() SimpleDate

Last returns the last element of the date slice.

func (*SimpleDates) Scan

func (t *SimpleDates) Scan(src any) error

Scan completes the pg and native sql driver.Scanner interface.

func (SimpleDates) Value

func (t SimpleDates) Value() (driver.Value, error)

Value completes the pg and native sql driver.Valuer interface.

func (SimpleDates) Weekdays

func (t SimpleDates) Weekdays() []time.Weekday

Weekdays returns a slice of unique weekdays from the dates in "t".

type StringOrArray

type StringOrArray string

StringOrArray type can be a single string or an array of strings. It marshals and unmarshals as a single string joined by commas.

func (StringOrArray) MarshalJSON

func (soa StringOrArray) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of the type.

func (StringOrArray) String

func (soa StringOrArray) String() string

String returns the string representation of the type.

func (*StringOrArray) UnmarshalJSON

func (soa *StringOrArray) UnmarshalJSON(data []byte) error

UnmarshalJSON sets the value of the type from JSON.

type TimeNotationDuration

type TimeNotationDuration time.Duration

TimeNotationDuration is a JSON representation of the standard Duration type in 00:00:00 (hour, minute seconds).

func ParseTimeNotationDuration

func ParseTimeNotationDuration(s string) (TimeNotationDuration, error)

ParseTimeNotationDuration parses a string to a time notation duration (00:00:00) hours:minutes:seconds.

func (TimeNotationDuration) MarshalJSON

func (d TimeNotationDuration) MarshalJSON() ([]byte, error)

func (*TimeNotationDuration) Set

func (d *TimeNotationDuration) Set(v float64)

Set sets the value of duration in nanoseconds.

func (*TimeNotationDuration) SetDuration

func (d *TimeNotationDuration) SetDuration(dur time.Duration)

SetDuration sets the value of duration in time.Duration.

func (TimeNotationDuration) ToDuration

func (d TimeNotationDuration) ToDuration() time.Duration

func (*TimeNotationDuration) UnmarshalJSON

func (d *TimeNotationDuration) UnmarshalJSON(b []byte) error

func (TimeNotationDuration) Value

func (d TimeNotationDuration) Value() (driver.Value, error)

type Weekday

type Weekday time.Weekday

Weekday is a time.Weekday which travels as a lowercase name: "monday". A client reading a schedule gets a word it can print, not a number whose base it has to guess, and the JSON stays readable in a log.

The numbering is time.Weekday's, Sunday being zero, so a Weekday converts to and from the standard type for free:

d := types.WeekdayOf(t.Weekday())
t.Weekday() == d.Std()

Because Sunday is the zero value, the zero Weekday marshals as "sunday".

func ParseWeekday

func ParseWeekday(s string) (Weekday, error)

ParseWeekday reads a weekday from its name, in any case and in the long or the three letter form: "Monday", "monday", "MON" and "mon" are the same day. Surrounding space is ignored.

func WeekdayOf

func WeekdayOf(d time.Weekday) Weekday

WeekdayOf converts a standard time.Weekday into this type. It is the opposite direction of the Std method.

func (Weekday) IsValid

func (d Weekday) IsValid() bool

IsValid reports whether the weekday is one of the seven days.

func (Weekday) MarshalJSON

func (d Weekday) MarshalJSON() ([]byte, error)

MarshalJSON renders the day name for encoding/json (v1) interop.

func (Weekday) MarshalJSONTo

func (d Weekday) MarshalJSONTo(enc *jsontext.Encoder) error

MarshalJSONTo writes the day name straight into the encoder, which is the path ctx.JSON takes, with no intermediate byte slice.

func (*Weekday) Scan

func (d *Weekday) Scan(src any) error

Scan completes the sql.Scanner interface. A text column is parsed by name, an integer one by time.Weekday's numbering and a NULL leaves the value as it is, as an empty text does: an absent value is not a wrong one. Number, whose column is numeric, takes the opposite view and makes an empty text an error.

func (Weekday) Std

func (d Weekday) Std() time.Weekday

Std returns the standard library type. It is named Std and not ToWeekday because a "ToWeekday" in the wild converts into a weekday type rather than out of one, and having both directions under one name during a migration is how the wrong one gets called. WeekdayOf is the other direction.

func (Weekday) String

func (d Weekday) String() string

String returns the lowercase English name of the day ("monday"). An out of range value renders like the standard library's, so a bad value is visible in a log instead of silently reading as a Sunday.

func (*Weekday) UnmarshalJSON

func (d *Weekday) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the day name for encoding/json (v1) interop.

func (*Weekday) UnmarshalJSONFrom

func (d *Weekday) UnmarshalJSONFrom(dec *jsontext.Decoder) error

UnmarshalJSONFrom reads the day name from the decoder. A JSON null and an empty text leave the value as it is, matching the rest of this package.

func (Weekday) Value

func (d Weekday) Value() (driver.Value, error)

Value completes the driver.Valuer interface: the day is stored as its lowercase name, so the column reads the same as the JSON.

Jump to

Keyboard shortcuts

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