1

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>
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 to this and never use r.URL.Path[1:] as the question did - you're allowing user input to directly choose a path on the filesystem.
Did I understand correctly that StaticFiles should be replaced with ScriptsDirectory ? So I can either use Templates and show html pages with javascript inside like: <script> alert('hello'); </script> OR I can use FileServer to provide files but not a templates ? Can I somehow use both ? Like templates for html and fileserver for only one directory "scripts" ?
@Illia thanks for the catch. Edited. Golang provides its own tempting engine which you can read about here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.