♻️ Refactor Timestamp Generator to single function with options
This commit is contained in:
parent
72791d4fac
commit
61a5199699
5 changed files with 113 additions and 67 deletions
59
gen_ts.go
Normal file
59
gen_ts.go
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
package nomino
|
||||
|
||||
import "time"
|
||||
|
||||
// FileTimestamp is the default format for WithTimestamp and WithTime
|
||||
const FileTimestamp string = "2006-01-02T15-04-05-0700"
|
||||
|
||||
// FileTimestampNoTZ is the default format for WithTimestampUTC and WithTimeUTC
|
||||
const FileTimestampNoTZ string = "2006-01-02T15-04-05"
|
||||
|
||||
type timestampConf struct {
|
||||
format string
|
||||
ts time.Time
|
||||
utc bool
|
||||
}
|
||||
|
||||
// TimestampOption provides options for the Timestamp Generator
|
||||
type TimestampOption func(c *timestampConf)
|
||||
|
||||
// Timestamp generates a a date and time. By default, it uses the current time, and will.
|
||||
// be formatted accourding to FileTimestamp
|
||||
func Timestamp(opts ...TimestampOption) Generator {
|
||||
c := timestampConf{format: FileTimestamp, ts: time.Now()}
|
||||
for _, opt := range opts {
|
||||
opt(&c)
|
||||
}
|
||||
|
||||
if c.utc {
|
||||
c.ts = c.ts.UTC()
|
||||
}
|
||||
|
||||
return func(*Config) (string, error) {
|
||||
return c.ts.Format(c.format), nil
|
||||
}
|
||||
}
|
||||
|
||||
// TSFormat sets the format for the generated name.
|
||||
// Consult time.Time.Format for details on the format.
|
||||
func TSFormat(format string) TimestampOption {
|
||||
return func(c *timestampConf) {
|
||||
c.format = format
|
||||
}
|
||||
}
|
||||
|
||||
// TSTime sets the time for the generated name.
|
||||
// By default, it uses the current time.
|
||||
func TSTime(t time.Time) TimestampOption {
|
||||
return func(c *timestampConf) {
|
||||
c.ts = t
|
||||
}
|
||||
}
|
||||
|
||||
// TSUTC uses the time in UTC, while also stripping the timezone from the format.
|
||||
func TSUTC() TimestampOption {
|
||||
return func(c *timestampConf) {
|
||||
c.utc = true
|
||||
c.format = FileTimestampNoTZ
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue