-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfavicon.go
66 lines (48 loc) · 1.25 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
package favicon
import (
"bytes"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/go-http-utils/headers"
)
// Version is this package's version.
const Version = "0.1.0"
// Handler wraps the http.Handler h with favicon support. `path`
// is the path to find the favicon.
func Handler(h http.Handler, path string) http.Handler {
if !os.IsPathSeparator(path[0]) {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
path = filepath.Join(wd, path)
}
stat, err := os.Stat(path)
if err != nil || stat.IsDir() {
panic("favicon: Invalid favicon path: " + path)
}
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
readSeeker := bytes.NewReader(file)
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.RequestURI != "/favicon.ico" {
h.ServeHTTP(res, req)
return
}
if req.Method != http.MethodGet && req.Method != http.MethodHead {
res.Header().Set(headers.Allow, "GET, HEAD, OPTIONS")
if req.Method == http.MethodOptions {
res.WriteHeader(http.StatusOK)
} else {
res.WriteHeader(http.StatusMethodNotAllowed)
}
return
}
res.Header().Set(headers.ContentType, "image/x-icon")
http.ServeContent(res, req, "favicon.ico", stat.ModTime(), readSeeker)
})
}