【问题标题】:Serving a Dynamic HTML File by `html/template` while also Serving a File Server for Hosting CSS, JS and Images Files in the Same Directory通过 `html/template` 提供动态 HTML 文件,同时提供用于在同一目录中托管 CSS、JS 和图像文件的文件服务器
【发布时间】:2016-11-27 16:48:33
【问题描述】:

现在我在同一个目录中有 3 个文件和一个文件夹,如下所示。 index.html 将请求 .css.js(ReactJS) 和文件夹 /img 中的图像。

经过大量搜索和尝试,我知道我可以使用以下内容创建一个文件服务器来为/client/index 中的文件的url 请求提供服务。

http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("client/index"))))

效果很好。但它只提供静态文件,我想在转出之前对 html 文件进行一些更改,例如修改标签 <input id='projectId' type='hidden' value={{.projectId}}/> 中的值。因此,我需要注册一个HandleFunc('/', handler) 来执行html 模板但url / 已经用于实现文件服务器。

在为文件(.css.js 和文件夹内的图像img)提供文件系统请求的同时,动态修改 html 的正确方法是什么?

服务器/pghndler/index/index.go

package index

func RegisterHandlers() {
    http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("client/index"))))
    http.HandleFunc("/login", loginHandler)
}

【问题讨论】:

    标签: go webserver fileserver


    【解决方案1】:

    在我看来,最简单的方法(更少的代码)是假装你的静态文件在不同的目录中,比如“静态”。这意味着您必须更改引用它们的 html 文件中的路径,即您拥有的位置

    <link rel="stylesheet" href="clent.css" type="text/css">
    

    你用

    <link rel="stylesheet" href="static/clent.css" type="text/css">
    

    然后在您的服务器代码中,您可以拥有路径 static 的处理程序,并且仍将 / 用于动态内容,即

    func main() {
        http.HandleFunc("/", hh_root)
        http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/home/Casper/public/client/index/"))))
        http.ListenAndServe(":8080", nil)
    }
    
    func hh_root(w http.ResponseWriter, r *http.Request) {
        // generate response from template
    }
    

    将网络资源组织到“css”和“js”之类的目录中是很常见的,因此将它们用于虚假路径可能是有意义的 - 当您的应用程序增长并且您希望更好地组织它时,这样做会更容易.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 2013-03-25
      • 2018-04-26
      • 2018-04-17
      相关资源
      最近更新 更多