To include external JavaScript libraries like jQuery in HTML pages served by Go, you need to follow these steps:
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.
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.
<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".
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.