【问题标题】:Load image and css in Golang在 Golang 中加载图像和 css
【发布时间】:2016-03-09 10:21:43
【问题描述】:

我在项目根目录的main包中的server.js中设置了一个路由

http.HandleFunc("/",route.IndexHandler)

IndexHandler 在包route 中实现如下:

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    data:=struct{
        Name string
    }{
        "My name",
    }
    util.RenderTemplate(w, "index", data)
}

RenderTemplate 函数在包util 中实现如下:

func RenderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
    cwd, _ := os.Getwd()
    t, err := template.ParseFiles(filepath.Join(cwd, "./view/" + tmpl + ".html"))
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    err = t.Execute(w, data)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

项目中的目录结构如下:

/
/public/css
/public/images
/public/js
/route
/view

index.html视图位于文件夹view,路由器位于文件夹route

index.html 中,我包含以下资源:

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

<img src="../public/images/img_landing_page_mac.png">

当请求适当的路径时,index.html 仍然会被渲染,但不会加载图像和样式表。如何将它们包含在 Golang html 模板引擎中?

【问题讨论】:

    标签: html css image go template-engine


    【解决方案1】:

    您需要明确要求您的服务器提供静态文件。

    http.FileServer

    在你的情况下注册另一个处理程序。

    http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
    

    【讨论】:

      【解决方案2】:

      就像Aruna说的,注册一个静态文件服务器句柄

      http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
      

      要使用 HTML 中的文件,只需

      <img src="/public/images/img_landing_page_mac.png">
      

      【讨论】:

        猜你喜欢
        • 2011-10-22
        • 1970-01-01
        • 2012-12-11
        • 1970-01-01
        • 2012-06-19
        • 2016-03-03
        • 2022-01-18
        • 2011-01-26
        • 1970-01-01
        相关资源
        最近更新 更多