dsdioa9545 2018-07-03 03:07
浏览 303

Golang HTML模板无法调用HTML文件中的JavaScript文件

I bundle React app with Webpack after I call it in HTML file. However, it error when I using Golang and html/template to view HTML file.

My HTML file: 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>



My Golang file: 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)
}
  • 写回答

2条回答 默认 最新

  • doubao6464 2018-07-03 03:34
    关注

    The issue seems to be that you are spinning up a server that only serves the HTML template - not the script. When a browser attempts to load your scripts, the server returns your index page.

    Take a look at https://www.alexedwards.net/blog/serving-static-sites-with-go; this post discusses how you can serve static files.

    For your purposes, you may be able to get by just by adding the following lines to the beginning of your main method:

    fs := http.FileServer(http.Dir("public"))
    http.Handle("/public/", http.StripPrefix("/static/", fs))
    

    This will load any files in your directory, "public" (relative to your compiled executable), and serve them at url/public/path/to/file

    As a word of caution: by default, this will enable directory listings for your public directory (users will be able to see a list of files in that directory and all subdirectories). Take a look at the answer for this question for info on how to disable directory listings: https://stackoverflow.com/a/40718195/6346483

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!