-
Notifications
You must be signed in to change notification settings - Fork 1
/
favicon.go
69 lines (63 loc) · 1.55 KB
/
favicon.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
package frontend
import (
"os"
"path/filepath"
"strings"
godl "github.com/admpub/go-download/v2"
"github.com/admpub/log"
"github.com/admpub/nging/v5/application/cmd/bootconfig"
"github.com/admpub/nging/v5/application/library/config"
"github.com/webx-top/com"
"github.com/webx-top/echo"
)
var faviconCacheDir = filepath.Join(echo.Wd(), `data`, `cache`)
var faviconCacheFile = filepath.Join(faviconCacheDir, `favicon.ico`)
func init() {
config.OnKeySetSettings(`base.siteFavicon`, func(diff config.Diff) error {
siteFavicon := diff.String()
n := len(siteFavicon)
if !diff.IsDiff {
if com.IsFile(faviconCacheFile) {
if n == 0 {
os.Remove(faviconCacheFile)
}
return nil
}
}
if n > 7 {
switch siteFavicon[0:7] {
case `https:/`, `http://`:
return faviconCache(siteFavicon)
default:
if siteFavicon[0:2] == `//` {
return faviconCache(`http:` + siteFavicon)
}
}
}
if n > 0 {
siteFavicon = strings.TrimPrefix(siteFavicon, `/`)
if com.IsFile(siteFavicon) {
com.MkdirAll(faviconCacheDir, os.ModePerm)
return com.Copy(siteFavicon, faviconCacheFile)
}
}
err := os.Remove(faviconCacheFile)
if err != nil {
if os.IsNotExist(err) {
return nil
}
}
return err
})
}
func faviconCache(url string) (err error) {
log.Debugf(`download favicon: %s => %s`, url, faviconCacheFile)
_, err = godl.Download(url, faviconCacheFile, nil)
return
}
func faviconHandler(c echo.Context) error {
if com.IsFile(faviconCacheFile) {
return c.File(faviconCacheFile)
}
return bootconfig.FaviconHandler(c)
}