jsontime

package
v0.206.0 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2021 License: Apache-2.0 Imports: 4 Imported by: 0

README

jsontime

Solve your time marshalling problems with this barebones time package wrapper.

Usage

This package provides two aliases for the basic time objects,

  • type Time time.Time
  • type Duration time.Duration

These aliases can be marshalled to and from any json and yaml document. Just use these types in your fields that you intend to marshal/unmarshal a time object.

import "github.com/anz-bank/sysl-go/jsontime"

type Response struct {
    ExpiryTime    jsontime.Time     `json:"expiry"`
    RefreshPeriod jsontime.Duration `json:"refresh"`
    // Other fields, make sure they are exported!
}

You can the set the response with a single line, instead of stringifying first

var resp := &Response{
    // Set expiry time to now + 5 mins
    ExpiryTime: jsontime.Time(time.Now().Add(5 * time.Minute))

    // Set refresh period to 1 minute
    RefreshPeriod: jsontime.Duration(time.Minute)
}

Now you can marshal the response body

// Marshal response body
body, _ := json.Marshal(resp)

Or read a response body

// Read response body
var r Response
_ := json.Unmarshal(body, &r)

// Get the underlying types
exp := r.ExpiryTime.Time()
refresh := r.RefreshPeriod.Duration()

This nice thing about this last one is that validation of the time and duration strings are done in the unmarshal function, and the returned type is already in time types.

Recommendations

Go duration strings are not standard format for REST APIs, so avoid using them for Request/Response types. There is no real difference if you use this packages time, or time.Time.

Use both freely in config (especially when reading yaml). Chances are you will use Duration much more than Time in config though.

Documentation

Overview

Package jsontime gives simple marshalling directly to and from time objects

This is a simple package that provides wrapper types for time.Time and time.Duration that can be marshalled to and from json and yaml.

time.Time already can marshal to and from json, but not yaml. Whereas time.Duration cannot marshal to and from either. These wrapper types fill in this gap.

This is extremely helpful for configuration and REST apis communicating via json. For example

Unmarshalling yaml config:

type Config struct {
	StartTime      jsontime.StartTime `yaml:"startTime"`
	RotationPeriod jsontime.Duration  `yaml:"retryPeriod"`
}
var config Config
if err := yaml.Unmarshal(responseBodybody, &config); err != nil {
	return err
}

// Get the actual time objects, not the jsontime type aliases
startTime := target.StartTime.Time()
rotationPeriod := target.RotationPeriod.Duration()

Unmarshalling a response:

type ResponseType struct {
	RetryPeriod jsontime.Duration  `json:"retryPeriod"`
}
var target ResponseType
if err := json.Unmarshal(responseBody, &target); err != nil {
	// Error captures any parse error on the retryPeriod value
	// rather than having to do that error check yourself
	return err
}

retryPeriod := target.RetryPeriod.Duration()

Marshalling a json request/response:

type RequestBody struct {
	RefreshRate jsontime.Duration `json:"refreshRate"`
}
requestBody := RequestBody{
	RefreshRate: jsontime.Duration(2 * time.Minute),
}
marshalled, _ := json.Marshal(requestBody)
resp, err := http.Do(url, method, bytes.NewBuffer(marshalled))

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DurationMapstructureDecodeHookFunc

func DurationMapstructureDecodeHookFunc(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error)

DurationMapstructureDecodeHookFunc is a DecodeHookFunc for mapstructure.

Use this if your config manager uses mapstructure (eg: viper, koanf).

Types

type Duration

type Duration time.Duration

Duration is an alias of time.Duration

Can be marshalled to and from json and yaml.

Example (Json)
package main

import (
	"encoding/json"
	"fmt"

	"github.com/anz-bank/sysl-go/jsontime"
)

func main() {
	type MyStruct struct {
		// Use the yaml tag for marshalling from yaml
		Duration *jsontime.Duration `mapstructure:"duration"`
	}

	const raw = `{"duration": "10m"}`

	var m MyStruct
	_ = json.Unmarshal([]byte(raw), &m)

	fmt.Println(m.Duration)

}
Output:

10m0s
Example (Yaml)
type MyStruct struct {
	// Use the yaml tag for marshalling from yaml
	Duration *jsontime.Duration `mapstructure:"duration"`
}

const raw = "duration: 10m"

var m MyStruct
_ = yaml.Unmarshal([]byte(raw), &m)

fmt.Println(m.Duration)
Output:

10m0s

func (Duration) Duration

func (d Duration) Duration() time.Duration

Duration returns the equivalent time.Duration object.

func (Duration) MarshalJSON

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

MarshalJSON implements json.Marshaller.

func (Duration) MarshalYAML

func (d Duration) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaller.

func (Duration) String

func (d Duration) String() string

func (*Duration) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaller.

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements yaml.Unmarshaller.

type Time

type Time time.Time

Time is an alias of time.Time.

Can marshal to and from json and yaml.

func (Time) MarshalJSON

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

MarshalJSON implements json.Marshaller.

func (Time) MarshalYAML

func (t Time) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaller.

func (Time) String

func (t Time) String() string

Time returns the equivalent time.Time struct.

func (Time) Time

func (t Time) Time() time.Time

Time returns the equivalent time.Time struct.

func (*Time) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaller.

func (*Time) UnmarshalYAML

func (t *Time) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements yaml.Unmarshaller.

Jump to

Keyboard shortcuts

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