Golang html模板无法在html文件中调用javascript文件

Phu*_*ang 3 javascript go

在HTML文件中调用它后,我将React应用程序与Webpack捆绑在一起.但是,当我使用Golang和html/template查看HTML文件时,它会出错.

我的HTML文件:index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Note App</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="public/bundle.js"></script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)



我的Golang文件:index.go

package main

import (
    "net/http"
    "html/template"
    "path/filepath"
)

func handle(w http.ResponseWriter, r *http.Request) {
    fp := filepath.Join("views", "index.html")
    t := template.Must(template.ParseFiles(fp))
    t.Execute(w, nil)
}

func main() {
    http.HandleFunc("/", handle)
    http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*yal 6

问题似乎是你正在启动一个只提供HTML模板的服务器 - 而不是脚本.当浏览器尝试加载脚本时,服务器将返回索引页.

看看https://www.alexedwards.net/blog/serving-static-sites-with-go ; 这篇文章讨论了如何提供静态文件.

为了您的目的,您可以通过将以下行添加到main方法的开头来获得:

fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/static/", fs))
Run Code Online (Sandbox Code Playgroud)

这将加载目录中的任何文件,"public"(相对于已编译的可执行文件),并在url/public/path/to/file中提供它们

请注意:默认情况下,这将启用公共目录的目录列表(用户将能够看到该目录和所有子目录中的文件列表).有关如何禁用目录列表的信息,请查看此问题的答案:https://stackoverflow.com/a/40718195/6346483