Home > Backend Development > Golang > How Can I Include Local JavaScript Files in Go Web Templates?

How Can I Include Local JavaScript Files in Go Web Templates?

Susan Sarandon
Release: 2024-12-22 06:10:14
Original
455 people have browsed it

How Can I Include Local JavaScript Files in Go Web Templates?

Include Local JavaScript Files in Go Templates

In your Go code, you have defined a web page template that includes a JavaScript file:

var page = `...<script src="http://localhost:8081/jquery.min.js"></script>...`
Copy after login

However, you are having trouble loading the local jquery.min.js file. Here's how you can fix this:

Option 1: Manual File Reading and Serving

  • Create a http.HandlerFunc to handle requests for the JavaScript file:
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")
    w.Write(data)
}
Copy after login
  • Register the handler and start the HTTP server:
http.HandleFunc("/jquery.min.js", SendJqueryJs) // Register the handler
http.ListenAndServe(":8081", nil)               // Start the server
Copy after login

Option 2: Using http.ServeFile

  • Create a http.HandlerFunc that uses http.ServeFile to serve the JavaScript file:
func SendJqueryJs(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "jquery.min.js")
}
Copy after login
  • Register the handler and start the HTTP server as shown in Option 1.

Option 3: Using http.FileServer

  • Create a http.FileServer to serve static files from a directory:
staticServer := http.FileServer(http.Dir("./static"))
Copy after login
  • Register the FileServer handler and start the HTTP server:
http.Handle("/static/", http.StripPrefix("/static/", staticServer))
http.ListenAndServe(":8081", nil)
Copy after login

In this case, you would place your jquery.min.js file in the static directory and access it through the URL /static/jquery.min.js.

The above is the detailed content of How Can I Include Local JavaScript Files in Go Web Templates?. 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