首页 > 解决方案 > 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)
}

标签: javascriptgo

解决方案


问题似乎是您正在启动仅提供 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


推荐阅读