-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviewer_file.go
110 lines (91 loc) · 2.23 KB
/
viewer_file.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package xun
import (
"crypto/sha256"
"encoding/hex"
"io"
"io/fs"
"net/http"
"strings"
)
// NewFileViewer creates a new FileViewer instance.
func NewFileViewer(fsys fs.FS, path string, isEmbed bool) *FileViewer {
v := &FileViewer{
fsys: fsys,
path: path,
}
if isEmbed {
f, err := fsys.Open(path)
if err != nil {
return v
}
defer f.Close()
hash := sha256.New() // skipcq: GSC-G401, GO-S1023
if _, err := io.Copy(hash, f); err != nil {
return v
}
v.isEmbed = true
v.etag = `"` + hex.EncodeToString(hash.Sum(nil)) + `"`
}
return v
}
// FileViewer is a viewer that serves a file from a file system.
//
// You can use it to serve a file from a file system, or to serve a file from
// a zip file.
//
// The file system is specified by the `fsys` field, and the path is specified
// by the `path` field.
//
// For example, to serve a file from the current working directory, you can
// use the following code:
//
// viewer := &FileViewer{
// fsys: os.DirFS("."),
// path: "example.txt",
// }
//
// app.HandleFile("example.txt", viewer)
type FileViewer struct {
fsys fs.FS
path string
isEmbed bool
etag string
}
var fileViewerMime = &MimeType{Type: "*", SubType: "*"}
// MimeType returns the MIME type of the file.
//
// The MIME type is determined by the file extension of the file.
func (*FileViewer) MimeType() *MimeType {
return fileViewerMime
}
// Render serves a file from the file system using the FileViewer.
// It writes the file to the http.ResponseWriter.
func (v *FileViewer) Render(w http.ResponseWriter, r *http.Request, data any) error {
if !v.isEmbed {
return v.serveContent(w, r)
}
w.Header().Set("ETag", v.etag)
if match := r.Header.Get("If-None-Match"); match != "" {
for _, it := range strings.Split(match, ",") {
if strings.TrimSpace(it) == v.etag {
w.WriteHeader(http.StatusNotModified)
return nil
}
}
}
return v.serveContent(w, r)
}
func (v *FileViewer) serveContent(w http.ResponseWriter, r *http.Request) error {
f, err := v.fsys.Open(v.path)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return nil
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
http.ServeContent(w, r, v.path, fi.ModTime(), f.(io.ReadSeeker))
return nil
}