To generate and serve HTML files with dynamically generated content in Go, you can use the "html/template" package to define templates and populate them with data.
Here's a step-by-step guide:
import (
"html/template"
"net/http"
)
const htmlTemplate = `
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
<h1>{{.Heading}}</h1>
{{range .Items}}
<div>{{.}}</div>
{{end}}
</body>
</html>
`
In this example, the template contains placeholders like {{.Title}}
, {{.Heading}}
, and {{.Items}}
which will be replaced with actual data.
func handler(w http.ResponseWriter, r *http.Request) {
data := struct {
Title string
Heading string
Items []string
}{
Title: "Dynamic Content",
Heading: "List of Items",
Items: []string{"Item 1", "Item 2", "Item 3"},
}
t := template.Must(template.New("html").Parse(htmlTemplate))
// You can check for errors in template parsing here
err := t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
In this example, we create a struct data
to hold the data needed by the template. We populate the struct with the required values. Then, we create a new template using template.New("html")
and parse the HTML template using t.Parse(htmlTemplate)
. Finally, we use t.Execute(w, data)
to render the template with the provided data and write the result to the response writer w
.
func main() {
http.HandleFunc("/dynamic", handler) // Register the handler to the "/dynamic" route
// Start the server
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}
Now, when you access http://localhost:8080/dynamic
in your browser, it will serve the dynamically generated HTML file with the provided content.
Note: Remember to replace the values and structure of the template and data according to your specific needs.