forked from emad-elsaid/xlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
88 lines (76 loc) · 2.23 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package xlog
import (
"fmt"
"log"
"strings"
"time"
)
func init() {
RegisterHelper("ago", ago)
RegisterHelper("isFontAwesome", func(i string) bool {
return len(i) > 3 && i[0:3] == "fa-"
})
}
// RegisterHelper registers a new helper function. all helpers are used when compiling
// templates. so registering helpers function must happen before the server
// starts as compiling templates happened right before starting the http server.
func RegisterHelper(name string, f any) {
if _, ok := helpers[name]; ok {
log.Fatalf("Helper: %s already registered", name)
}
helpers[name] = f
}
// A function that takes time.duration and return a string representation of the
// duration in human readable way such as "3 seconds ago". "5 hours 30 minutes
// ago". The precision of this function is 2. which means it returns the largest
// unit of time possible and the next one after it. for example days + hours, or
// Hours + minutes or Minutes + seconds...etc
func ago(t time.Time) string {
if READONLY {
return t.Format("Monday 2 January 2006")
}
d := time.Since(t)
const day = time.Hour * 24
const week = day * 7
const month = day * 30
const year = day * 365
const maxPrecision = 2
var o strings.Builder
if d.Seconds() < 1 {
o.WriteString("Less than a second ")
}
for precision := 0; d.Seconds() > 1 && precision < maxPrecision; precision++ {
switch {
case d >= year:
years := d / year
d -= years * year
o.WriteString(fmt.Sprintf("%d years ", years))
case d >= month:
months := d / month
d -= months * month
o.WriteString(fmt.Sprintf("%d months ", months))
case d >= week:
weeks := d / week
d -= weeks * week
o.WriteString(fmt.Sprintf("%d weeks ", weeks))
case d >= day:
days := d / day
d -= days * day
o.WriteString(fmt.Sprintf("%d days ", days))
case d >= time.Hour:
hours := d / time.Hour
d -= hours * time.Hour
o.WriteString(fmt.Sprintf("%d hours ", hours))
case d >= time.Minute:
minutes := d / time.Minute
d -= minutes * time.Minute
o.WriteString(fmt.Sprintf("%d minutes ", minutes))
case d >= time.Second:
seconds := d / time.Second
d -= seconds * time.Second
o.WriteString(fmt.Sprintf("%d seconds ", seconds))
}
}
o.WriteString("ago")
return o.String()
}