To generate and serve static HTML pages in a Go web application, you can follow these steps:
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.
Place your HTML files or templates inside the "static" folder.
In your main Go file, import the required packages:
import (
"net/http"
"html/template"
)
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.
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.
func main() {
// ...
// Register the handler function to a specific route
http.HandleFunc("/", renderHTML)
// ...
}
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.