Phuc Hoang
Phuc Hoang

Reputation: 55

Golang html template cannot call javascript file in html file

I bundle React app with Webpack after I call it in HTML file. However, it error when I using Golang and html/template to view HTML file.

My HTML file: index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Note App</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="public/bundle.js"></script>
    </body>
</html>



My Golang file: index.go

package main

import (
    "net/http"
    "html/template"
    "path/filepath"
)

func handle(w http.ResponseWriter, r *http.Request) {
    fp := filepath.Join("views", "index.html")
    t := template.Must(template.ParseFiles(fp))
    t.Execute(w, nil)
}

func main() {
    http.HandleFunc("/", handle)
    http.ListenAndServe(":8080", nil)
}

Upvotes: 4

Views: 4723

Answers (2)

Krzysztof Skolimowski
Krzysztof Skolimowski

Reputation: 491

Are you serving public/bundle.js?

If not you need to serve it somehow. For example you can use net/http https://golang.org/pkg/net/http/#ServeFile

Upvotes: 0

Anish Goyal
Anish Goyal

Reputation: 2859

The issue seems to be that you are spinning up a server that only serves the HTML template - not the script. When a browser attempts to load your scripts, the server returns your index page.

Take a look at https://www.alexedwards.net/blog/serving-static-sites-with-go; this post discusses how you can serve static files.

For your purposes, you may be able to get by just by adding the following lines to the beginning of your main method:

fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/static/", fs))

This will load any files in your directory, "public" (relative to your compiled executable), and serve them at url/public/path/to/file

As a word of caution: by default, this will enable directory listings for your public directory (users will be able to see a list of files in that directory and all subdirectories). Take a look at the answer for this question for info on how to disable directory listings: https://stackoverflow.com/a/40718195/6346483

Upvotes: 8

Related Questions