英文:
Src attribute in golang templates
问题
在执行Golang服务器上的模板时,我遇到了一个问题:html文件中的src属性在搜索导入的JavaScript文件时,并不在根位置(服务器文件夹)下,而是在处理的URL下方。因此,如果请求src='/dir/file.js'
,当前位置为http://localhost:8080/handled/
,将会对http://localhost:8080/handled/dir/file.js
发起GET请求。
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", page)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/handled/", testHandler)
http.ListenAndServe(":8080", nil)
}
所以,模板文件file.html包含以下行:
<!-- 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>
...file.js与file.html位于同一目录下。我尝试了不同的文件位置和各种路径组合,似乎我做错了。
英文:
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
得分: 1
如果您的浏览器请求的是/handled/dir/file.js,那么您的src路径可能缺少了最前面的斜杠。这不是一个特定于Go的问题。
我看到您说您请求的文件的src是"/dir/file.js",但是在您的示例中,您显示的是"file.js",所以我不太确定您实际上有什么。然而,您的问题仍然表明您忘记了第一个斜杠,就像src="dir/file.js"一样。
英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论