Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang html template cannot call javascript file in html file

Tags:

javascript

go

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)
}
like image 740
Phuc Hoang Avatar asked Mar 06 '23 21:03

Phuc Hoang


1 Answers

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

like image 140
Anish Goyal Avatar answered Mar 09 '23 06:03

Anish Goyal