Home > Backend Development > Golang > How to Include Local JavaScript Files in Go Templates?

How to Include Local JavaScript Files in Go Templates?

Patricia Arquette
Release: 2024-12-21 21:13:38
Original
896 people have browsed it

How to Include Local JavaScript Files in Go Templates?

Include 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)
}
Copy after login

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")
}
Copy after login

Option 3: Leveraging http.FileServer()

For serving multiple static files:

http.Handle("/tmpfiles/",
    http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
Copy after login

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">
Copy after login

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!

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