How to include external JavaScript libraries (e.g., jQuery) in HTML pages served by Go?

To include external JavaScript libraries like jQuery in HTML pages served by Go, you need to follow these steps:

  1. Download the library: Firstly, download the jQuery library (or any other library you want to include) from the official website. Save the library file to a directory in your project.

  2. Serve the library file: Go uses a built-in HTTP server to serve static files. You need to configure the server to serve the library file along with your HTML pages. Here is an example:

package main import ( "net/http" ) func main() { // Serve static files from the "static" directory fs := http.FileServer(http.Dir("static")) http.Handle("/static/", http.StripPrefix("/static/", fs)) // Handle HTML pages http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") }) // Start the server http.ListenAndServe(":8080", nil) }

In this example, the Go server is configured to serve static files from the "static" directory. You should place your library file (e.g., "jquery.js") inside the "static" directory.

  1. Include the library in HTML: In your HTML page (e.g., "index.html"), you can now include the library using a <script> tag. Here is an example:
<!DOCTYPE html> <html> <head> <title>My Page</title> <script src="/static/jquery.js"></script> </head> <body> <!-- Your page content here --> </body> </html>

Make sure to specify the correct path to the library file in the src attribute of the <script> tag. In this example, the library file is located at "/static/jquery.js".

  1. Start the Go server: Compile and run your Go program using the command go run <filename>.go. This will start the Go server and serve your HTML pages including the external library.

Now your HTML pages served by Go will include the external JavaScript library, and you can utilize its functionality within your web application.