forked from ungerik/go-start
/
staticfile.go
40 lines (33 loc) · 890 Bytes
/
staticfile.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
package view
import (
"github.com/ungerik/go-start/errs"
"io/ioutil"
"path"
)
///////////////////////////////////////////////////////////////////////////////
// StaticFile
type StaticFile struct {
ViewBase
Filename string // Will set file extension at ContentType
ContentTypeExt string
modifiedTime int64
fileContent []byte
}
func (self *StaticFile) Render(ctx *Context) (err error) {
filePath, found, modified := FindStaticFile(self.Filename)
if !found {
return errs.Format("Static file not found: %s", self.Filename)
}
if self.ContentTypeExt == "" {
self.ContentTypeExt = path.Ext(filePath)
}
if self.fileContent == nil || modified > self.modifiedTime {
self.fileContent, err = ioutil.ReadFile(filePath)
if err != nil {
return err
}
}
ctx.Response.SetContentTypeByExt(self.ContentTypeExt)
ctx.Response.Write(self.fileContent)
return nil
}