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.

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"