Home >Backend Development >Golang >How to Include Local JavaScript Files in Go Templates?
You're encountering issues including a local JavaScript file in your Go template. Let's explore how to address this with ease:
Option 1: Manual File Handling
Write your own handler function to read the file content, set the appropriate content type, and send it as a response:
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) }
Option 2: Using http.ServeFile()
This function simplifies file serving by handling file reading and content type setting:
func SendJqueryJs(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "jquery.min.js") }
Option 3: Leveraging http.FileServer()
For serving multiple static files:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
This registers a handler at /tmpfiles/ that serves files from your local /tmp directory.
For example, this script tag will load jquery.min.js from /tmp:
<script type="text/javascript" src="/tmpfiles/jquery.min.js">
The above is the detailed content of How to Include Local JavaScript Files in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!