golang http template example
Here is an example of using the Go (golang) http template in a step-by-step explanation:
Step 1: Import the necessary packages:
import (
"html/template"
"log"
"net/http"
)
Step 2: Create a struct to hold the data for the template:
type User struct {
Name string
Email string
}
Step 3: Define the HTML template:
const templateStr = `
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h1>User Profile</h1>
<p>Name: {{ .Name }}</p>
<p>Email: {{ .Email }}</p>
</body>
</html>
`
Step 4: Create an HTTP handler function:
func userProfileHandler(w http.ResponseWriter, r *http.Request) {
// Create a new User instance with sample data
user := User{Name: "John Doe", Email: "[email protected]"}
// Parse the template
tmpl, err := template.New("userProfile").Parse(templateStr)
if err != nil {
log.Fatal(err)
}
// Execute the template with the user data and write the output to the response writer
err = tmpl.Execute(w, user)
if err != nil {
log.Fatal(err)
}
}
Step 5: Register the HTTP handler function and start the server:
func main() {
// Register the HTTP handler function
http.HandleFunc("/profile", userProfileHandler)
// Start the server on port 8080
log.Fatal(http.ListenAndServe(":8080", nil))
}
With these steps, you have an example of using the Go (golang) http template. It starts by importing the necessary packages, creating a struct to hold the data for the template, defining the HTML template, creating an HTTP handler function, and finally registering the handler and starting the server.