Home > Backend Development > Golang > How to Include a Local JavaScript File (e.g., jquery.min.js) in a Go Template?

How to Include a Local JavaScript File (e.g., jquery.min.js) in a Go Template?

Susan Sarandon
Release: 2024-12-25 15:13:18
Original
773 people have browsed it

How to Include a Local JavaScript File (e.g., jquery.min.js) in a Go Template?

Including a Local JS File in Go Template

Your question pertains to including a local JavaScript file, specifically jquery.min.js, in your Go template. The reason your attempt to load it using a local path failed may be due to the lack of a handler or handler function to serve the file.

Solution 1: Manually Handle the File

  • This involves reading the file's content, setting the appropriate content type ("application/javascript"), and sending the content to the response.
  • Ensure you specify the absolute path to the file or place it in the current working directory.
func SendJqueryJs(w http.ResponseWriter, r *http.Request) {
    data, err := ioutil.ReadFile("jquery.min.js")
    if err != nil {
        http.Error(w, "Couldn't read file", http.StatusInternalServerError)
        return
    }
    w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
    w.Write(data)
}
Copy after login

Solution 2: Using http.ServeFile()

  • This function allows you to easily send the content of a file to a response.
func SendJqueryJs(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "jquery.min.js")
}
Copy after login

Solution 3: Using http.FileServer()

  • This is particularly suitable for serving multiple static files.
  • You can create a handler to serve files from a specific folder.
http.Handle("/tmpfiles/",
    http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
Copy after login

This will serve files from the "/tmp" directory to URLs starting with "/tmpfiles/."

By implementing one of these solutions, you should be able to include your local jquery.min.js file in your Go template.

The above is the detailed content of How to Include a Local JavaScript File (e.g., jquery.min.js) in a Go Template?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template