/
packr_handler.go
73 lines (64 loc) · 1.53 KB
/
packr_handler.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
package happening
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/gobuffalo/packr"
"github.com/labstack/echo/v4"
)
type env struct {
HAPPENING_SERVER_URL string `json:"HAPPENING_SERVER_URL"`
}
func createEnv(config ServerConfig) {
vars := env{
HAPPENING_SERVER_URL: config.HAPPENING_SERVER_URL,
}
bytes, err := json.MarshalIndent(&vars, "", " ")
if err != nil {
log.Panic(err)
}
outputPath := filepath.Join(config.WEBUI_DIR, "build", "Env.js")
file, err := os.Create(outputPath)
if err != nil {
log.Panic(err)
}
log.Printf("Env = %s", bytes)
_, err = fmt.Fprintf(file, "window.Env = %s;", bytes)
if err != nil {
log.Panic(err)
}
}
func redirectURL(path string, oldURL *url.URL) string {
query := oldURL.Query()
path = path + "?" + query.Encode()
oldURL.Path = "/"
newQuery := url.Values{}
newQuery.Set("p", path)
oldURL.RawQuery = newQuery.Encode()
return oldURL.String()
}
func PackrHandler(config ServerConfig) echo.HandlerFunc {
createEnv(config)
box := packr.NewBox(filepath.Join(config.WEBUI_DIR, "build"))
fileServer := http.FileServer(box)
wrapHandler := func(h http.Handler) echo.HandlerFunc {
return func(c echo.Context) error {
oldURL := c.Request().URL
path := oldURL.Path
if path != "" && box.Has(path) {
h.ServeHTTP(c.Response(), c.Request())
return nil
} else {
if path == "" {
path = "/search"
}
return c.Redirect(http.StatusTemporaryRedirect, redirectURL(path, oldURL))
}
}
}
return wrapHandler(fileServer)
}