builtin

package
v0.56.1 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2022 License: BSD-3-Clause Imports: 28 Imported by: 2

Documentation

Overview

Package builtin provides simple functions, types, constants and a package that can be used as globals in a Scriggo template.

For example, to use the Min and Max functions as global min and max functions

globals := native.Declarations{
    "min": builtin.Min,
    "max": builtin.Max,
}
opts := &scriggo.BuildOptions{
    Globals: globals,
}
template, err := scriggo.BuildTemplate(fsys, file, opts)

And to use them in a template

{{ min(x, y) }}
{{ max(x, y) }}

Use the regexp function and the returned Regex value in this way

{% var re = regexp(`(scrig)go`) %}
{{ re.Match("go") }}
{{ re.Match("scriggo") }}

Use this Declarations value to use all the builtin of this package in a template or choose the most appropriate

native.Declarations{
	// crypto
	"hmacSHA1":   builtin.HmacSHA1,
	"hmacSHA256": builtin.HmacSHA256,
	"sha1":       builtin.Sha1,
	"sha256":     builtin.Sha256,

	// encoding
	"base64":            builtin.Base64,
	"hex":               builtin.Hex,
	"marshalJSON":       builtin.MarshalJSON,
	"marshalJSONIndent": builtin.MarshalJSONIndent,
	"marshalYAML":       builtin.MarshalYAML,
	"md5":               builtin.Md5,
	"unmarshalJSON":     builtin.UnmarshalJSON,
	"unmarshalYAML":     builtin.UnmarshalYAML,

	// html
	"htmlEscape": builtin.HtmlEscape,

	// math
	"abs": builtin.Abs,
	"max": builtin.Max,
	"min": builtin.Min,
    "pow": builtin.Pow,

	// net
	"File":        reflect.TypeOf((*builtin.File)(nil)).Elem(),
	"FormData":    reflect.TypeOf(builtin.FormData{}),
	"form":        (*builtin.FormData)(nil),
	"queryEscape": builtin.QueryEscape,

	// regexp
	"Regexp": reflect.TypeOf(builtin.Regexp{}),
	"regexp": builtin.RegExp,

	// sort
	"reverse": builtin.Reverse,
	"sort":    builtin.Sort,

	// strconv
	"formatFloat": builtin.FormatFloat,
	"formatInt":   builtin.FormatInt,
	"parseFloat":  builtin.ParseFloat,
	"parseInt":    builtin.ParseInt,

	// strings
	"abbreviate":    builtin.Abbreviate,
	"capitalize":    builtin.Capitalize,
	"capitalizeAll": builtin.CapitalizeAll,
	"hasPrefix":     builtin.HasPrefix,
	"hasSuffix":     builtin.HasSuffix,
	"index":         builtin.Index,
	"indexAny":      builtin.IndexAny,
	"join":          builtin.Join,
	"lastIndex":     builtin.LastIndex,
	"replace":       builtin.Replace,
	"replaceAll":    builtin.ReplaceAll,
	"runeCount":     builtin.RuneCount,
	"split":         builtin.Split,
	"splitAfter":    builtin.SplitAfter,
	"splitAfterN":   builtin.SplitAfterN,
	"splitN":        builtin.SplitN,
	"sprint":        builtin.Sprint,
	"sprintf":       builtin.Sprintf,
	"toKebab":       builtin.ToKebab,
	"toLower":       builtin.ToLower,
	"toUpper":       builtin.ToUpper,
	"trim":          builtin.Trim,
	"trimLeft":      builtin.TrimLeft,
	"trimPrefix":    builtin.TrimPrefix,
	"trimRight":     builtin.TrimRight,
	"trimSuffix":    builtin.TrimSuffix,

	// time
	"Duration":      reflect.TypeOf(builtin.Duration(0)),
	"Hour":          time.Hour,
	"Microsecond":   time.Microsecond,
	"Millisecond":   time.Millisecond,
	"Minute":        time.Minute,
	"Nanosecond":    time.Nanosecond,
	"Second":        time.Second,
	"Time":          reflect.TypeOf(builtin.Time{}),
	"date":          builtin.Date,
	"now":           builtin.Now,
	"parseDuration": builtin.ParseDuration,
	"parseTime":     builtin.ParseTime,
	"unixTime":      builtin.UnixTime,

	// unsafeconv, uncomment the declaration below to allow to use unsafe conversions between string and native types
	// "unsafeconv": builtin.Unsafeconv,

}

To initialize the form builtin value, with data read from the request r, use this map as vars argument to Run

map[string]interface{}{"form": builtin.NewFormData(r, 10)}

Index

Constants

This section is empty.

Variables

View Source
var ErrBadRequest = errors.New("form: bad request")

ErrBadRequest is the error that occurs when parsing a malformed HTTP request body or query string in FormData methods.

View Source
var ErrRequestEntityTooLarge = errors.New("form: request entity too large")

ErrRequestEntityTooLarge is the error that occurs when the HTTP request's body is too large

View Source
var Unsafeconv = native.Package{
	Name: "unsafeconv",
	Declarations: map[string]native.Declaration{
		"ToHTML": func(s string) native.HTML {
			return native.HTML(s)
		},
		"ToCSS": func(s string) native.CSS {
			return native.CSS(s)
		},
		"ToJS": func(s string) native.JS {
			return native.JS(s)
		},
		"ToJSON": func(s string) native.JSON {
			return native.JSON(s)
		},
		"ToMarkdown": func(s string) native.Markdown {
			return native.Markdown(s)
		},
	},
}

Unsafeconv provides a package that implements functions to make unsafe conversions between string values and native types.

Functions

func Abbreviate

func Abbreviate(s string, n int) string

Abbreviate abbreviates s to almost n runes. If s is longer than n runes, the abbreviated string terminates with "...".

func Abs

func Abs(x int) int

Abs returns the absolute value of x. As a special case, if x is the smallest negative integer, Abs returns x.

func Base64

func Base64(s string) string

Base64 returns the base64 encoding of s.

func Capitalize

func Capitalize(s string) string

Capitalize returns a copy of the string s with the first non-separator in upper case.

func CapitalizeAll

func CapitalizeAll(s string) string

CapitalizeAll returns a copy of the string s with the first letter of each word in upper case.

func FormatFloat

func FormatFloat(f float64, format string, precision int) string

FormatFloat converts the floating-point number f to a string, according to the given format and precision. It can round the result.

The format is one of "e", "f" or "g"

"e": -d.dddde±dd, a decimal exponent
"f": -ddd.dddd, no exponent
"g": "e" for large exponents, "f" otherwise

The precision, for -1 <= precision <= 1000, controls the number of digits (excluding the exponent). The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. For "e" and "f" it is the number of digits after the decimal point. For "g" it is the maximum number of significant digits (trailing zeros are removed).

If the format or the precision is not valid, FormatFloat panics.

func FormatInt

func FormatInt(i int, base int) string

FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.

It panics if base is not in the range.

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix tests whether the string s begins with prefix.

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix tests whether the string s ends with suffix.

func Hex

func Hex(s string) string

Hex returns the hexadecimal encoding of s.

func HmacSHA1

func HmacSHA1(message, key string) string

HmacSHA1 returns the HMAC-SHA1 tag for the given message and key, as a base64 encoded string.

func HmacSHA256

func HmacSHA256(message, key string) string

HmacSHA256 returns the HMAC-SHA256 tag for the given message and key, as a base64 encoded string.

func HtmlEscape

func HtmlEscape(s string) native.HTML

HtmlEscape escapes s, replacing the characters <, >, &, " and ' and returns the escaped string as native.HTML type.

func Index

func Index(s, substr string) int

Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

The returned index refers to the bytes and not the runes of s.

func IndexAny

func IndexAny(s, chars string) int

IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

The returned index refers to the bytes and not the runes of s.

func Join

func Join(elems []string, sep string) string

Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.

func LastIndex

func LastIndex(s, substr string) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

The returned index refers to the bytes and not the runes of s.

func MarshalJSON

func MarshalJSON(v interface{}) (native.JSON, error)

MarshalJSON returns the JSON encoding of v.

See https://pkg.go.dev/encoding/json#Marshal for details.

func MarshalJSONIndent

func MarshalJSONIndent(v interface{}, prefix, indent string) (native.JSON, error)

MarshalJSONIndent is like MarshalJSON but indents the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting. prefix and indent can only contain whitespace: ' ', '\t', '\n' and '\r'.

func MarshalYAML added in v0.55.0

func MarshalYAML(v interface{}) (_ string, err error)

MarshalYAML returns the YAML encoding of v.

See https://pkg.go.dev/gopkg.in/yaml.v3#Marshal for details.

func Max

func Max(x, y int) int

Max returns the larger of x or y.

func Md5

func Md5(s string) string

Md5 returns the MD5 checksum of s as a hexadecimal encoded string.

func Min

func Min(x, y int) int

Min returns the smaller of x or y.

func ParseFloat

func ParseFloat(s string) (float64, error)

ParseFloat converts the string s to a float64 value.

If s is well-formed and near a valid floating-point number, ParseFloat returns the nearest floating-point number rounded using IEEE754 unbiased rounding.

func ParseInt

func ParseInt(s string, base int) (int, error)

ParseInt interprets a string s in the given base, for 2 <= base <= 36, and returns the corresponding value. It returns 0 and an error if s is empty, contains invalid digits or the value corresponding to s cannot be represented by an int value.

func Pow added in v0.50.0

func Pow(x, y float64) float64

Pow returns x**y. See https://pkg.go.dev/math#Pow.

func QueryEscape

func QueryEscape(s string) string

QueryEscape escapes the string, so it can be safely placed inside a URL query.

func Replace

func Replace(s, old, new string, n int) string

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If n < 0, there is no limit on the number of replacements.

func ReplaceAll

func ReplaceAll(s, old, new string) string

ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new.

func Reverse

func Reverse(slice interface{})

Reverse reverses the order of the elements of slice. If slice is not a slice, it panics.

func RuneCount

func RuneCount(s string) (n int)

RuneCount returns the number of runes in s. Erroneous and short encodings are treated as single runes of width 1 byte.

func Sha1

func Sha1(s string) string

Sha1 returns the SHA1 checksum of s as a hexadecimal encoded string.

func Sha256

func Sha256(s string) string

Sha256 returns the SHA256 checksum of s as a hexadecimal encoded string.

func Sort

func Sort(slice interface{}, less func(i, j int) bool)

Sort the elements of slice given the provided less function. If slice is not a slice, it panics.

The less function reports whether slice[i] should be ordered before slice[j]. If less is nil, the elements are sorted in a natural order based on their type.

The natural order can differ between different versions of Scriggo.

func Split

func Split(s, sep string) []string

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s. If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

It is equivalent to SplitN with a count of -1.

func SplitAfter

func SplitAfter(s, sep string) []string

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.

If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s. If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice.

It is equivalent to SplitAfterN with a count of -1.

func SplitAfterN

func SplitAfterN(s, sep string, n int) []string

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for SplitAfter.

func SplitN

func SplitN(s, sep string, n int) []string

SplitN slices s into substrings separated by sep and returns a slice of the substrings between those separators.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for Split.

func Sprint

func Sprint(a ...interface{}) string

Sprint formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.

func Sprintf

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

func ToKebab

func ToKebab(s string) string

ToKebab returns a copy of the string s in kebab case form.

func ToLower

func ToLower(s string) string

ToLower returns s with all Unicode letters mapped to their lower case.

func ToUpper

func ToUpper(s string) string

ToUpper returns s with all Unicode letters mapped to their upper case.

func Trim

func Trim(s, cutset string) string

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

func TrimLeft

func TrimLeft(s, cutset string) string

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.

To remove a prefix, use TrimPrefix instead.

func TrimPrefix

func TrimPrefix(s, prefix string) string

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

func TrimRight

func TrimRight(s, cutset string) string

TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.

To remove a suffix, use TrimSuffix instead.

func TrimSuffix

func TrimSuffix(s, suffix string) string

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

func UnmarshalJSON

func UnmarshalJSON(data string, v interface{}) error

UnmarshalJSON parses the JSON-encoded data and stores the result in a new value pointed to by v. If v is nil or not a pointer, UnmarshalJSON returns an error.

Unlike json.Unmarshal of the Go standard library, UnmarshalJSON does not change the value pointed to by v but instantiates a new value and then replaces the value pointed to by v, if no errors occur.

See https://pkg.go.dev/encoding/json#Unmarshal for details.

func UnmarshalYAML added in v0.55.0

func UnmarshalYAML(data string, v interface{}) (err error)

UnmarshalYAML parses the YAML-encoded data and stores the result in a new value pointed to by v. If v is nil or not a pointer, UnmarshalYAML returns an error.

Unlike yaml.Unmarshal of the yaml package, UnmarshalYAML does not accept a map value, use a pointer to a map value instead. UnmarshalYAM does not change the value pointed to by v but instantiates a new value and then replaces the value pointed to by v, if no errors occur.

See https://pkg.go.dev/gopkg.in/yaml.v3#Unmarshal for details.

Types

type Duration

type Duration = time.Duration

A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

type File

type File interface {
	Name() string // name.
	Type() string // type, as mime type.
	Size() int    // size, in bytes.
}

File represents a file. Files that can be opened also implement Opener.

type FormData

type FormData struct {
	// contains filtered or unexported fields
}

FormData contains the form data from the query string and body of an HTTP request. Values and files passed as multipart/form-data are only available after ParseMultipart method is called.

func NewFormData

func NewFormData(r *http.Request, maxMemory int64) FormData

NewFormData returns a new FormData value. maxMemory is passed as is to the r.ParseMultipartForm method.

func (FormData) File

func (form FormData) File(field string) File

File returns the first file associated with the given field. It returns nil if there are no values associated with the field.

Call File only after ParseMultipart is called.

func (FormData) Files

func (form FormData) Files() map[string][]File

Files returns the parsed files of a multipart form. It returns a non nil map, if ParseMultipart has been called.

Call Files only after ParseMultipart is called.

func (FormData) ParseMultipart

func (form FormData) ParseMultipart()

ParseMultipart parses a request body as multipart/form-data. If the body is not multipart/form-data, it does nothing. It should be called before calling the File and Files methods and can be called multiple times.

It panics with ErrBadRequest if the request is not valid, ErrRequestEntityTooLarge if the length of the body is too large or another error if another error occurs.

func (FormData) Value

func (form FormData) Value(field string) string

Value returns the first form data value associated with the given field. If there are no files associated with the field, it returns an empty string.

It panics with ErrBadRequest if the request is not valid, ErrRequestEntityTooLarge if the length of the body is too large or another error if another error occurs.

func (FormData) Values

func (form FormData) Values() map[string][]string

Values returns the parsed form data, including both the URL field's query parameters and the POST form data.

It panics with ErrBadRequest if the request is not valid, ErrRequestEntityTooLarge if the length of the body is too large or another error if another error occurs.

type Opener

type Opener interface {
	// Open opens the file.
	Open() (io.ReadSeekCloser, error)
}

Opener is implemented by a File that can be opened. Opener is not intended to be used as a builtin type but it can be used by builtins to open a file.

type Regexp

type Regexp struct {
	// contains filtered or unexported fields
}

Regexp represents a regular expression.

func RegExp

func RegExp(expr string) Regexp

RegExp parses a regular expression and returns a Regexp value that can be used to match against text. It panics if the expression cannot be parsed.

For the syntax of regular expressions see https://pkg.go.dev/regexp/syntax.

func (Regexp) Find

func (re Regexp) Find(s string) string

Find returns a string holding the text of the leftmost match in s of the regular expression. If there is no match, the return value is an empty string, but it will also be empty if the regular expression successfully matches an empty string. Use FindSubmatch if it is necessary to distinguish these cases.

func (Regexp) FindAll

func (re Regexp) FindAll(s string, n int) []string

FindAll is the 'All' version of Find; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the Go regexp package comment. A return value of nil indicates no match.

func (Regexp) FindAllSubmatch

func (re Regexp) FindAllSubmatch(s string, n int) [][]string

FindAllSubmatch is the 'All' version of FindSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the Go regexp package comment. A return value of nil indicates no match.

func (Regexp) FindSubmatch

func (re Regexp) FindSubmatch(s string) []string

FindSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the Go regexp package comment. A return value of nil indicates no match.

func (Regexp) Match

func (re Regexp) Match(s string) bool

Match reports whether the string s contains any match of the regular expression.

func (Regexp) ReplaceAll

func (re Regexp) ReplaceAll(s, repl string) string

ReplaceAll returns a copy of s, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Expand method of the Go regexp package, so for instance $1 represents the text of the first submatch.

func (Regexp) ReplaceAllFunc

func (re Regexp) ReplaceAllFunc(s string, repl func(string) string) string

ReplaceAllFunc returns a copy of s in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched substring. The replacement returned by repl is substituted directly, without expanding.

func (Regexp) Split

func (re Regexp) Split(s string, n int) []string

Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches.

The slice returned by this method consists of all the substrings of s not contained in the slice returned by FindAllString. When called on an expression that contains no metacharacters, it is equivalent to SplitN.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

type Time

type Time struct {
	// contains filtered or unexported fields
}

A Time represents an instant in time.

It is a stripped down version of the Go time.Time type, with additional methods to show time values in JavaScript and JSON contexts.

func Date

func Date(year, month, day, hour, min, sec, nsec int, location string) (Time, error)

Date returns the time corresponding to the given date with time zone determined by location. If location does not exist, it returns an error.

For example, the following call returns March 27, 2021 11:21:14.964553705 CET.

Date(2021, 3, 27, 11, 21, 14, 964553705, "Europe/Rome")

For UTC use "" or "UTC" as location. For the system's local time zone use "Local" as location.

The month, day, hour, min, sec and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

func NewTime

func NewTime(t time.Time) Time

NewTime returns a Time value at the time of t. It is not intended to be used as a builtin but it can be used to implement builtins that return time values.

For example, a builtin that returns the current local time rounded to milliseconds and with location "America/New_York" can be implemented as

func now() builtin.Time {
    l := time.LoadLocation("America/New_York")
    t := time.Now().Rounded(time.Millisecond).In(l)
    return builtin.NewTime(t)
}

and once added to the declarations

native.Declarations{
    ...
    "now" : now,
    ...
}

it can be used in a template

Current time: {{ now() }}

func Now

func Now() Time

Now returns the current local time.

func ParseTime

func ParseTime(layout, value string) (Time, error)

ParseTime parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time

Mon Jan 2 15:04:05 -0700 MST 2006

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

See https://pkg.go.dev/time#Parse for more details.

As a special case, if layout is an empty string, ParseTime parses a time representation using a predefined list of layouts.

It returns an error if value cannot be parsed.

func UnixTime

func UnixTime(sec int64, nsec int64) Time

UnixTime returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

func (Time) Add

func (t Time) Add(d Duration) Time

Add returns the time t+d.

func (Time) AddDate

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

AddDate returns the time corresponding to adding the given number of years, months and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

AddDate normalizes its result in the same way that the Date function does.

func (Time) After

func (t Time) After(u Time) bool

After reports whether the time instant t is after u.

func (Time) Before

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.

func (Time) Clock

func (t Time) Clock() (hour, minute, second int)

Clock returns the hour, minute and second within the day specified by t. hour is in the range [0, 23], minute and second are in the range [0, 59].

func (Time) Date

func (t Time) Date() (year, month, day int)

Date returns the year, month and day in which t occurs. month is in the range [1, 12] and day is in the range [1, 31].

func (Time) Day

func (t Time) Day() int

Day returns the day of the month specified by t, in the range [1, 31].

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant.

func (Time) Format

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

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.

func (Time) Hour

func (t Time) Hour() int

Hour returns the hour within the day specified by t, in the range [0, 23].

func (Time) IsZero

func (t Time) IsZero() bool

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

func (Time) JS

func (t Time) JS() native.JS

JS returns the time as a JavaScript date. The result is undefined if the year of t is not in the range [-999999, 999999].

func (Time) JSON

func (t Time) JSON() native.JSON

JSON returns a time in a format suitable for use in JSON.

func (Time) Minute

func (t Time) Minute() int

Minute returns the minute offset within the hour specified by t, in the range [0, 59].

func (Time) Month

func (t Time) Month() int

Month returns the month of the year specified by t, in the range [1, 12] where 1 is January and 12 is December.

func (Time) Nanosecond

func (t Time) Nanosecond() int

Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].

func (Time) Round

func (t Time) Round(d Duration) Time

Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.

Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time's Location.

func (Time) Second

func (t Time) Second() int

Second returns the second offset within the minute specified by t, in the range [0, 59].

func (Time) String

func (t Time) String() string

String returns the time formatted.

func (Time) Sub

func (t Time) Sub(u Time) Duration

Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

func (Time) Truncate

func (t Time) Truncate(d Duration) Time

Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.

Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time's Location.

func (Time) UTC

func (t Time) UTC() Time

UTC returns t with the location set to UTC.

func (Time) Unix

func (t Time) Unix() int64

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined. The result does not depend on the location associated with t.

func (Time) Weekday

func (t Time) Weekday() int

Weekday returns the day of the week specified by t.

func (Time) Year

func (t Time) Year() int

Year returns the year in which t occurs.

func (Time) YearDay

func (t Time) YearDay() int

YearDay returns the day of the year specified by t, in the range [1, 365] for non-leap years, and [1, 366] in leap years.

Jump to

Keyboard shortcuts

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