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
|
package main
import (
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"time"
)
func randomToken(length int) string {
b := make([]byte, length)
rand.Read(b)
return hex.EncodeToString(b)
}
func genKey(length int) []byte {
b := make([]byte, length)
rand.Read(b)
return b
}
func md5hex(s string) string {
hash := md5.Sum([]byte(s))
return hex.EncodeToString(hash[:])
}
func (app *App) GetCookie(r *http.Request, name string, dst interface{}) error {
cookie, err := r.Cookie(name)
if err != nil {
return err
}
return app.CookieHandler.Decode(name, cookie.Value, dst)
}
func (app *App) SetCookie(w http.ResponseWriter, name string, v interface{}, exp int) error {
if encoded, err := app.CookieHandler.Encode(name, v); err != nil {
return err
} else {
cookie := &http.Cookie{
Name: name,
Value: encoded,
Path: "/",
HttpOnly: true,
MaxAge: exp,
}
http.SetCookie(w, cookie)
return nil
}
}
func ago(t time.Time) string {
delta := time.Since(t)
if delta < time.Minute {
return fmt.Sprintf("%ds ago", int(delta/time.Second))
} else if delta < time.Hour {
return fmt.Sprintf("%dm ago", int(delta/time.Minute))
} else if delta < 24*time.Hour {
return fmt.Sprintf("%dh ago", int(delta/time.Hour))
} else if delta < 5*24*time.Hour {
return fmt.Sprintf("%dd ago", int(delta/(24*time.Hour)))
} else {
return t.Format("Jan 2")
}
}
|