Update server.go: Replace plugins in INITIAL_DATA

Since recently the /config/server/info data is not requested later,
but already inlined in the host page. So the proxy script has to be
adapted to that.

Change-Id: Iba60afbfc0adb1ec6a574219601b64a059153bad
This commit is contained in:
Ben Rohlfs
2019-08-06 21:15:50 +02:00
parent 4f06d74558
commit 8950c7e153

View File

@@ -103,7 +103,7 @@ func resourceBasePath() (string, error) {
func handleIndex(writer http.ResponseWriter, originalRequest *http.Request) {
fakeRequest := &http.Request{
URL: &url.URL{
Path: "/",
Path: "/",
RawQuery: originalRequest.URL.RawQuery,
},
}
@@ -170,7 +170,7 @@ func setJsonPropByPath(json map[string]interface{}, path []string, value interfa
func patchResponse(req *http.Request, res *http.Response) io.Reader {
switch req.URL.EscapedPath() {
case "/":
return replaceCdn(res.Body)
return rewriteHostPage(res.Body)
case "/config/server/info":
return injectLocalPlugins(res.Body)
default:
@@ -178,13 +178,39 @@ func patchResponse(req *http.Request, res *http.Response) io.Reader {
}
}
func replaceCdn(reader io.Reader) io.Reader {
func rewriteHostPage(reader io.Reader) io.Reader {
buf := new(bytes.Buffer)
buf.ReadFrom(reader)
original := buf.String()
// Simply remove all CDN references, so files are loaded from the local file system or the proxy
// server instead.
replaced := cdnPattern.ReplaceAllString(original, "")
// Modify window.INITIAL_DATA so that it has the same effect as injectLocalPlugins. To achieve
// this let's add JavaScript lines at the end of the <script>...</script> snippet that also
// contains window.INITIAL_DATA=...
// Here we rely on the fact that the <script> snippet that we want to append to is the first one.
if len(*plugins) > 0 {
insertionPoint := strings.Index(replaced, "</script>")
builder := new(strings.Builder)
builder.WriteString(
"window.INITIAL_DATA['/config/server/info'].plugin.html_resource_paths = []; ")
builder.WriteString(
"window.INITIAL_DATA['/config/server/info'].plugin.js_resource_paths = []; ")
for _, p := range strings.Split(*plugins, ",") {
if filepath.Ext(p) == ".html" {
builder.WriteString(
"window.INITIAL_DATA['/config/server/info'].plugin.html_resource_paths.push('" + p + "'); ")
}
if filepath.Ext(p) == ".js" {
builder.WriteString(
"window.INITIAL_DATA['/config/server/info'].plugin.js_resource_paths.push('" + p + "'); ")
}
}
replaced = replaced[:insertionPoint] + builder.String() + replaced[insertionPoint:]
}
return strings.NewReader(replaced)
}
@@ -209,11 +235,11 @@ func injectLocalPlugins(reader io.Reader) io.Reader {
jsResources := getJsonPropByPath(response, jsPluginsPath).([]interface{})
for _, p := range strings.Split(*plugins, ",") {
if strings.HasSuffix(p, ".html") {
if filepath.Ext(p) == ".html" {
htmlResources = append(htmlResources, p)
}
if strings.HasSuffix(p, ".js") {
if filepath.Ext(p) == ".js" {
jsResources = append(jsResources, p)
}
}