douyi8315 2014-06-24 03:09
浏览 112

Golang模板中的Src属性

When executing template on golang server, I got an issue that src attribute in html file searches for importing javascript file not in the root location (server folder), but below the handled url. So, requesting src='/dir/file.js' having current location like http://localhost:8080/handled/ will make GET request for http://localhost:8080/handled/dir/file.js.

package main

import ("net/http"; "html/template")

var templates = template.Must(template.ParseFiles("././dir/file.html"))

type Page struct {
  Title string
  Body  []byte
}

func testHandler(w http.ResponseWriter, r *http.Request) {
  page := Page{"handled", nil}

  err := templates.ExecuteTemplate(w, "file.html", p)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
  }
}

func main() {
  http.HandleFunc("/handled/", testHandler)
  http.ListenAndServe(":8080", nil)
}

So, the template file.html contains the following line:

<!-- file.html
javascript placed right inside template file is working,
but I didnt managed to get to work src insertation -->
<script src="file.js"></script>

...the file.js sharing the same directory with file.html. I tried different file locations and various paths combinations. Seems like I'm doing it a wrong way.

  • 写回答

1条回答 默认 最新

  • duanlu9557 2014-06-24 03:22
    关注

    If your browser is requesting /handled/dir/file.js then your src must be missing the initial forward slash. This is not a Go specific problem.

    I see that you say your file being requested has src="/dir/file.js", but then in your example you show src="file.js", so I am not exactly sure what you really have. However, your problem is still indicative of forgetting the first slash, like src="dir/file.js"

    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害