-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbundle.go
80 lines (65 loc) · 1.42 KB
/
bundle.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
// Copyright 2012 by sdm. All rights reserved.
// license that can be found in the LICENSE file.
package wk
import (
"bytes"
"errors"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"time"
)
// BundleResult is bundle of Files
type BundleResult struct {
Files []string
}
// Execute write content of files to HttpContext.Response
func (b *BundleResult) Execute(ctx *HttpContext) error {
if len(b.Files) == 0 {
return errors.New("bundle files is invalid")
}
var modtime time.Time
for _, file := range b.Files {
info, err := os.Stat(file)
if err != nil {
return err
}
if info.IsDir() {
return errors.New("bundle file is invalid:" + file)
}
if info.ModTime().After(modtime) {
modtime = info.ModTime()
}
}
if checkLastModified(ctx.Resonse, ctx.Request, modtime) {
return nil
}
ctx.ContentType(b.Type())
buffer := &bytes.Buffer{}
for _, file := range b.Files {
err := readFromFile(file, buffer)
if err != nil {
return err
}
}
http.ServeContent(ctx.Resonse, ctx.Request, b.Files[0], modtime, bytes.NewReader(buffer.Bytes()))
return nil
}
func readFromFile(file string, w io.Writer) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(w, f)
return err
}
// ContentType return mime type of BundleResult.Files[0]
func (b *BundleResult) Type() string {
if len(b.Files) == 0 {
return ""
}
return mime.TypeByExtension(filepath.Ext(b.Files[0]))
}