Illia
Illia

Reputation: 45

Go How can I use JavaScript code on my html page

Problem: I have script src tag in my index.html page but on browser this script doesn't load ( actually it loads but looks like index.html file 0_0 see pictures below ). The question is: How can I use JavaScript code which is in different file ( myscripts.js ) on my html page ?

js file looks like html ( index.html ) file

During googling I found "solution" but I does not work completely like it should. I just added this line to viewHandler method :

http.ServeFile(w, r, r.URL.Path[1:])

After this, project started look like this:

index.html after adding line above

To sum up:

My goal is to show html page and use javascript function which are in scripts/ folder.

Project Structure :

-scripts 
 --myscripts.js
-templates
 --index.html
server.go

Server.go :

func viewHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("listening . . .")
            tpl.ExecuteTemplate(w, "index.html", nil)
        }

func main() {

    http.HandleFunc("/", viewHandler)
        http.ListenAndServe(":8080", nil)
}

myscripts.js:

function clickFunc(){
console.log("clicked")
}

index.html:

<head>
<script type="text/javascript" src="scripts/myscripts.js"></script>
</head>
<body>

<button onclick="clickFunc()">Click me</button>

</body>
</html>

Upvotes: 1

Views: 92

Answers (1)

weqlix
weqlix

Reputation: 44

You should be able to serve static files from a specific directory using the http package.

For example:

func main() {
  ScriptsDirectory := http.FileServer(http.Dir("scripts"))
  http.Handle("/scripts", ScriptsDirectory)

  log.Println("Listening at port 3000")
  http.ListenAndServe(":3000", nil)
}

Will let you server the file directly from that directory.

From there you can reference the /scripts directory in your index.html page as is.

Here is also a tutorial where this technique is used.

Upvotes: 2

Related Questions