duanlang1196 2017-07-25 17:07
浏览 139

使用Golang渲染模板时,无法读取其他文件夹中的CSS和图像

I am trying to render a template using the html/template module of Golang. But only CSS files and images from the same folder as the page i am rendering are executed, those located in a different folder are ignored. Here is my code:

func render(w http.ResponseWriter, filename string, data interface{}) {
    tmpl, err := template.ParseFiles(filename)
    if err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    if err := tmpl.Execute(w, data); err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
    }
  }

For this page for example:

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Start Connect</title>
  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <link href="one-page.css" rel="stylesheet">
</head>

The one-page.css is executed but not the bootstrap.

  • 写回答

1条回答 默认 最新

  • dongzi4030 2017-07-25 23:29
    关注

    Using ../css on the web should be avoided and likely is your error source. Your go server likely cannot resolve the file (because you don't have a handler for the ../css URI). So you should change the ../css part to /css and tell your server (you didn't provide details, so I cannot show you code) to handle /css URIs by serving the files.

    Assuming that you are using the default net/http mux, your code should look something like:

    mux := http.NewServeMux()
    mux.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
    http.ListenAndServe(":8080", mux)
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类