Home >Backend Development >Golang >How Can I Embed Local JavaScript Files in Go Templates?
Embedding JavaScript Files in Go Templates
In Go templates, it's common to include JavaScript files to enhance the functionality of web pages. While you can include remote JavaScript files using URLs, it's often desirable to serve local JavaScript files for better performance and control.
1. Creating a File Server
One approach is to create a file server to handle the serving of static files, including JavaScript. To do this, you can use the http.FileServer to create a handler that serves files from a specific directory:
func main() { http.Handle("/js/", http.FileServer(http.Dir("js"))) }
This handler will serve files from the "js" directory.
2. Registering the Handler
Next, register the handler with the HTTP server using http.Handle:
func main() { http.Handle("/js/", http.FileServer(http.Dir("js"))) http.HandleFunc("/", handler) http.ListenAndServe(":9999", nil) }
3. Including the JavaScript File in the Template
In your Go template, you can now include the local JavaScript file using the following syntax:
<script src="/js/jquery.min.js"></script>
This will load the "jquery.min.js" file from the "js" directory.
Alternative Approaches:
The above is the detailed content of How Can I Embed Local JavaScript Files in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!