javascript - Golang html模板无法在html文件中调用javascript文件
问题描述
在 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>
我的 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)
}
解决方案
问题似乎是您正在启动仅提供 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))
这将加载您目录中的任何文件,“public”(相对于您编译的可执行文件),并在 url/public/path/to/file
请注意:默认情况下,这将为您的公共目录启用目录列表(用户将能够看到该目录和所有子目录中的文件列表)。查看此问题的答案以获取有关如何禁用目录列表的信息:https ://stackoverflow.com/a/40718195/6346483
推荐阅读
- scala - 使用scala在Spark sql Dataframe中读取不明确的列名
- javascript - @types/core-js 用于动态导入“core-js/stable”
- javascript - 为每个用户随机分配至少一个唯一项,不重复
- java - 在 Java 中,如何根据其他对象的值更改使对象更新其值?
- c - 2D OpenGL 渲染,FBO 完全黑色/无法正确渲染
- python - Numpy 无法将输入数组从形状 (2,4) 广播到形状 (2,3)
- python - 查找字符串中的特定数字并赋值
- java - 如果在 Android 对话框中选择了相同的选项,如何什么都不做?
- java - Selenium:准备就绪时等待和获取元素
- android - 尽管 ArrayList 引用没有丢失,但 notifyDataSetChanged 没有更新 RecyclerView