-
Notifications
You must be signed in to change notification settings - Fork 13
/
public.go
70 lines (61 loc) · 1.5 KB
/
public.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
package public
import (
"encoding/json"
"io/ioutil"
"mime"
"net/http"
"path"
"path/filepath"
"strings"
"gopkg.in/labstack/echo.v1"
)
// Assets is the variable that stores assets
var Assets AssetsWrapper
// AssetsWrapper is a wrapper for static assets
type AssetsWrapper struct {
Hash string
}
// Stats is the json object for webpack stats
type Stats struct {
BuildDir string
Hash string `json:"hash"`
}
var stats Stats
var buildDir string
// LoadStats loads the Assets variable
func LoadStats(d string) error {
buildDir = d
statsBytes, err := ioutil.ReadFile(path.Join(d, "stats.json"))
if err != nil {
return err
}
json.Unmarshal(statsBytes, &stats)
stats.BuildDir = buildDir
return nil
}
// GetHash returns the hash of the built assets
func GetHash(reload bool) string {
if reload {
LoadStats(buildDir)
}
return stats.Hash
}
// StaticHandler serves static files
func StaticHandler(c *echo.Context) error {
name := c.Param("name")
if strings.HasPrefix(name, ".") {
return c.String(http.StatusNotFound, "Not Found")
}
// var contentType string
// if strings.HasSuffix(name, ".js") {
// contentType = "application/javascript"
// } else if strings.HasSuffix(name, ".js.map") {
// contentType = "application/json"
// } else {
// return c.String(http.StatusNotFound, "Not Found")
// } // TODO
mimetype := mime.TypeByExtension(filepath.Ext(name))
c.Response().Header().Set("Content-Type", mimetype)
http.ServeFile(c.Response(), c.Request(), path.Join(stats.BuildDir, name))
return nil
}