~fmac/pasticcio

ref: dcd4deae5f567c3074b6f309955c4e6a4f72123a pasticcio/web/utils/utils.go -rw-r--r-- 1.8 KiB
dcd4deae — Francesco Camuffo Config: include info URLs 3 months ago
                                                                                
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package utils

import (
	"crypto/sha256"
	"fmt"
	"html/template"
	"io"
	"log"
	"os"
	"path"
	"strings"
	"sync"
	"time"

	"fmac.dev/pasticcio/config"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
)

var Funcs template.FuncMap

var (
	cache = map[string]string{}

	h   = gin.H{}
	hMx sync.RWMutex
)

func Init(conf *config.Config) {
	hMx.Lock()
	h = gin.H{
		"AppTitle": conf.AppTitle,
		"Info":     conf.Info,
	}
	hMx.Unlock()

	// TODO: rethink this? I don't like what I'm doing here
	cache["webRootPath"] = conf.WebRootPath

	Funcs = template.FuncMap{
		"byteaToString":   byteaToString,
		"formatCreatedAt": formatCreatedAt,
		"resHashedPath":   resHashedPath,
		"trimString":      trimString,
		"truncRandId":     truncRandId,
	}
}

func NewH(vals gin.H) gin.H {
	ret := gin.H{}
	for k, v := range vals {
		ret[k] = v
	}
	hMx.RLock()
	// XXX: I hate so much that you can't deepcopy in Go that I rage-imported
	// copier. fuck it
	copier.CopyWithOption(&ret, &h, copier.Option{IgnoreEmpty: false, DeepCopy: true})
	hMx.RUnlock()
	return ret
}

func byteaToString(b []byte) string {
	return string(b)
}

func formatCreatedAt(t time.Time) string {
	return t.Format(time.RFC3339)
}

func resHashedPath(res string) string {
	if v, ok := cache[res]; ok {
		return v
	}
	f, err := os.Open(path.Join(cache["webRootPath"], res))
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		log.Fatal(err)
	}

	hashed := fmt.Sprintf("%s.%x%s",
		strings.TrimSuffix(res, path.Ext(res)),
		h.Sum(nil)[:8],
		path.Ext(res),
	)
	cache[res] = hashed
	return hashed
}

func trimString(n int, s string) string {
	if n == 0 || len(s) <= n {
		return s
	}
	return s[:n] + "..."
}

func truncRandId(s string) string {
	if len(s) <= 8 {
		return s
	}
	return s[:8]
}