/
fs_handling.go
111 lines (87 loc) · 2.19 KB
/
fs_handling.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
111
package main
import (
"bufio"
"bytes"
"compress/gzip"
"github.com/dustin/go-humanize"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
func readFileEmbedded(filename string) (wholecontent string, size int64) {
file, err := Assets.Open("/" + filename)
checkErr(err)
stats, err2 := file.Stat()
checkErr(err2)
defer file.Close()
size = stats.Size()
var filecontent []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
filecontent = append(filecontent, scanner.Text())
}
wholecontent = strings.Join(filecontent, NEW_LINE)
return
}
func readFileRealRawToString(filename string) string {
content, err := ioutil.ReadFile(filename)
checkErr(err)
return string(content)
}
func readFileReal(filename string) (wholecontent string, size int64) {
wholecontent = readFileRealRawToString(filename)
stats, err := os.Stat(filename)
checkErr(err)
size = stats.Size()
if *compressHtmlFlag && isCompressableExtension(filename) {
var buf bytes.Buffer
var gz *gzip.Writer
gz, err = gzip.NewWriterLevel(&buf, gzip.BestCompression)
_, err = gz.Write([]byte(wholecontent))
checkErr(err)
err = gz.Flush()
checkErr(err)
err = gz.Close()
checkErr(err)
log.Println("Compressed file", filename, "from", humanize.Bytes(uint64(size)), "to", humanize.Bytes(uint64(buf.Len())))
wholecontent = string(buf.Bytes())
size = int64(buf.Len())
}
return
}
func makePathRecursive(path string) {
basepath := filepath.Dir(path)
os.MkdirAll(basepath, os.ModePerm)
}
func writeContentToFile(path string, content string) {
makePathRecursive(path)
err := ioutil.WriteFile(path, []byte(content), 0664)
checkErr(err)
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return err == nil
}
func fileIsRealFile(filename string) bool {
fileInfo, err := os.Stat(filename)
checkErr(err)
return !fileInfo.IsDir()
}
func isCompressableExtension(filename string) bool {
supportedExtension := map[string]bool{
"html": true,
"htm": true,
"js": true,
"css": true,
"wasm": true,
"xml": true,
"json": true,
}
ext := filepath.Ext(filename) // Get extension including the dot ".html"
return supportedExtension[ext[1:]]
}