-
Notifications
You must be signed in to change notification settings - Fork 574
/
Copy pathfile.go
42 lines (34 loc) · 1 KB
/
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
package response
import (
"fmt"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-shiori/shiori/internal/model"
)
// SendFile sends file to client with caching header
func SendFile(c *gin.Context, storageDomain model.StorageDomain, path string) {
c.Header("Cache-Control", "public, max-age=86400")
if !storageDomain.FileExists(path) {
c.AbortWithStatus(http.StatusNotFound)
return
}
info, err := storageDomain.Stat(path)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.Header("ETag", fmt.Sprintf("W/%x-%x", info.ModTime().Unix(), info.Size()))
// TODO: Find a better way to send the file to the client from the FS, probably making a
// conversion between afero.Fs and http.FileSystem to use c.FileFromFS.
fileContent, err := storageDomain.FS().Open(path)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
_, err = io.Copy(c.Writer, fileContent)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
}