猿问

在 HTTP 服务器中提供静态文件

我正在使用 golang 作为中型 Web 应用程序的后端,该应用程序在不同的文件夹中有几个页面和大量 CSS 和 javascript,我正在尝试使用 golang 为网站提供服务,但只加载索引文件,另一个页面、javascript、CSS 不加载。因为我的 HTML 文件彼此不同,所以我没有使用模板


这是文件结构


-static 

    -assets

        -css(folder with subfolders)

        -js(folder with subfolders)

    -pages (folder with differnt html pages)

         -signup.html

         -dashboard.html

    -index.html

    -register_bundle.js

-main.go

func handlerequests (){

 myRouter := mux.NewRouter().StrictSlash(true)

 myRouter.Handle("/", http.FileServer(http.Dir("./static")))

 myRouter.HandleFunc("/transaction", transactionHandler)

 log.Fatal(http.ListenAndServe(":8080",myRouter))

}


我的 HTML 文件有这样的链接,(显示 index.html)


<!-- CSS Files -->

  <link href="./assets/css/bootstrap.min.css" rel="stylesheet" />

  <link href="./assets/css/paper-dashboard.css?v=2.1.1" rel="stylesheet" />

<!--JS files -->

  <script src="./assets/demo/demo.js"></script>

  <!--Main Script file for the page  -->

  <script src="./register_bundle.js"></script>

此处显示的错误

http://img2.mukewang.com/62a6e3430001ae6e19151081.jpg

慕容森
浏览 227回答 3
3回答

守候你守候我

问题是浏览器找不到那些 JS 和 CSS 文件。&nbsp;&nbsp;&nbsp;&nbsp;fs&nbsp;:=&nbsp;http.FileServer(http.Dir("./static")) &nbsp;&nbsp;&nbsp;&nbsp;MUXRouter.Handle("/",&nbsp;fs) &nbsp;&nbsp;&nbsp;&nbsp;MUXRouter.PathPrefix("/assets/").Handler(fs) &nbsp;&nbsp;&nbsp;&nbsp;MUXRouter.PathPrefix("/pages/").Handler(fs) &nbsp;&nbsp;&nbsp;&nbsp;MUXRouter.Handle("/register_bundle.js",&nbsp;fs)这样一个 GET 请求http://[host]:[port]/css/style.css将从相关./static/css/目录返回 style.css。上面的代码在我的示例程序中运行。

幕布斯7119047

尝试gor:= mux.NewRouter().StrictSlash(true)fs := http.FileServer(http.Dir("./static"))gor.PathPrefix("/transaction").Handler(fs)如果它不只是尝试阅读 http.FileServer 的文档,它可能应该工作

慕仙森

您是否尝试为您的资源文件夹提供处理程序?sdir := "/resources/"myRouter.PathPrefix(sdir).Handler(http.StripPrefix(sdir, http.FileServer(http.Dir("."+sdir))))这允许您将文件夹作为子域访问。
随时随地看视频慕课网APP

相关分类

Go
我要回答