How to generate and serve static HTML pages in a Go web application?

To generate and serve static HTML pages in a Go web application, you can follow these steps:

  1. Create a directory within your project to store your static HTML files. For example, you can create a folder named "static" in the root of your project.

  2. Place your HTML files or templates inside the "static" folder.

  3. In your main Go file, import the required packages:

import ( "net/http" "html/template" )
  1. Set the file server to serve the static files. After initializing your router, add the following code:
func main() { // ... // Create a file server to serve static files fs := http.FileServer(http.Dir("static")) http.Handle("/static/", http.StripPrefix("/static/", fs)) // ... }

This code creates a file server using the http.FileServer function to serve files from the "static" directory. The http.StripPrefix function is used to remove the "/static/" prefix from the URL.

Note: The path provided to http.Dir should be relative to the location of your Go file.

  1. Create a handler function to render the HTML files and serve them:
func renderHTML(w http.ResponseWriter, r *http.Request) { tmpl, err := template.ParseFiles("static/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = tmpl.Execute(w, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }

This code uses the template.ParseFiles function to parse the HTML file, and template.Execute to render the HTML template. You can adjust the file name and path according to your needs.

  1. Register the handler function to a specific route:
func main() { // ... // Register the handler function to a specific route http.HandleFunc("/", renderHTML) // ... }
  1. Finally, start the server by calling http.ListenAndServe:
func main() { // ... // Start the server http.ListenAndServe(":8000", nil) // ... }

Replace :8000 with the desired port number where you want to run your Go web application.

That's it! Now, when you visit the specified route (e.g., http://localhost:8000/), the static HTML file will be rendered and served by your Go web application.