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
Susan SarandonOriginal
2024-12-22 06:10:14506browse

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>...`

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)
}
  • Register the handler and start the HTTP server:
http.HandleFunc("/jquery.min.js", SendJqueryJs) // Register the handler
http.ListenAndServe(":8081", nil)               // Start the server

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")
}
  • 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"))
  • Register the FileServer handler and start the HTTP server:
http.Handle("/static/", http.StripPrefix("/static/", staticServer))
http.ListenAndServe(":8081", nil)

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!

Statement:
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