How to include and execute JavaScript code in HTML pages served by Go?

To include and execute JavaScript code in HTML pages served by Go, you can follow these steps:

  1. Create a Go web server using the net/http package. This server will serve the HTML pages.
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) } func handler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") }
  1. Create an HTML file, let's say index.html, in the same directory as the Go file.
<!DOCTYPE html> <html> <head> <title>Sample HTML Page</title> </head> <body> <h1>Welcome to My Page</h1> <p id="output">JavaScript will be executed here:</p> <script src="script.js"></script> </body> </html>
  1. Create a JavaScript file, let's say script.js, in the same directory.
document.getElementById("output").innerHTML = "Hello from JavaScript!";
  1. Run the Go server by executing the Go code. This will start the server on http://localhost:8080.

  2. Open your web browser and navigate to http://localhost:8080. You should see the HTML page with the JavaScript code executed, displaying "Hello from JavaScript!" within the paragraph element.

By serving the HTML file through the Go server, the JavaScript file (script.js) is included within the HTML page using the <script> tag. The JavaScript code within the script.js file is then executed in the browser, manipulating the HTML page as desired.