Include js file in Go template

You need a Handler or a HandlerFunc which will send the file content (jquery.min.js) to the web browser when requested.

You have 3 options:

Doing It Manually

This is the more complex solution. It would look like in your handler function you read the content of the file, set proper response content type (application/javascript) and send the content (which is a []byte) to the response.

Things to look out for: When reading the file, you have to specify an absolute path. If you specify a relative path, be sure the file is in the current folder (working directory) you start your app from.

Example:

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)
}

func main() {
    http.HandleFunc("/jquery.min.js", SendJqueryJs)
    panic(http.ListenAndServe(":8081", nil))
}

The above example is capable of serving only 1 file: jquery.min.js for the request:

http://localhost:8081/jquery.min.js

Utilizing http.ServeFile()

This is much easier: The function http.ServeFile() is capable of sending the content of one file to the specified response. You still need to create a function or handler to use it, but it does the rest for you:

func SendJqueryJs(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "jquery.min.js")
}

Utilizing http.FileServer()

If you need to serve multiple static files, this is where FileServer() function comes handy which returns you a Handler which automatically serves files from your local file system that are descendants of the root folder you specify.

This solution is much more flexible: it can send many files of multiple types, detects and sets content type automatically. The handler is also capable of rendering HTML pages for listing directory content with links to the files and to parent/child folders.

Example:

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

This will register a Handler at the URL /tmpfiles/ which serves files found in your local filesystem in the /tmp folder. So for example the following <script> link:

<script type="text/javascript" src="https://stackoverflow.com/tmpfiles/jquery.min.js">

Will get the /tmp/jsquery.min.js file from the server.

Check out this answer which details how to use/fire up a Static File Server.

Leave a Comment