dongtuwu8548 2016-03-09 10:21
浏览 190
已采纳

在Golang中加载图片和CSS

I setup a route in server.js in package main in root directory of project

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

The IndexHandler is implemented in package route like this:

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

The RenderTemplate function is implemented in package util like this:

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)
    }
}

Directory structure in project like this:

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

index.html view is located in folder view, router is in folder route

In index.html I include resources like these:

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

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

When request the appropriate path, index.html is still rendered, but images and stylesheet are not loaded. How can I do to include them in Golang html template engine?

  • 写回答

2条回答 默认 最新

  • doutuo3575 2016-03-09 11:20
    关注

    You need to explicitly ask your server to serve static files.

    See http.FileServer

    In your case register another handler.

    http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog