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
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) }
http.HandleFunc("/jquery.min.js", SendJqueryJs) // Register the handler http.ListenAndServe(":8081", nil) // Start the server
Option 2: Using http.ServeFile
func SendJqueryJs(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "jquery.min.js") }
Option 3: Using http.FileServer
staticServer := http.FileServer(http.Dir("./static"))
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!