package main
import (
"html/template"
"log"
"net/http"
)
var x = 2
func main() {
http.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
const tpl = `
| Name |
Email |
Role |
Status |
{{range .Users}}
|
|
{{.Email}} |
{{.Role}}
|
{{.Status}}
|
{{end}}
`
t, err := template.New("default").Parse(tpl)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
type User struct {
Name string
Initials string
Email string
Role string
Status string
StatusClass string
StatusDotClass string
}
data := struct {
Users []User
}{
Users: []User{
{Name: "Sarah Chen", Initials: "SC", Email: "sarah.chen@example.com", Role: "Engineering", Status: "Active", StatusClass: "bg-green-50 text-green-600", StatusDotClass: "bg-green-600"},
{Name: "Marcus Johnson", Initials: "MJ", Email: "marcus.j@example.com", Role: "Product", Status: "Active", StatusClass: "bg-green-50 text-green-600", StatusDotClass: "bg-green-600"},
{Name: "Emma Rodriguez", Initials: "ER", Email: "emma.r@example.com", Role: "Design", Status: "Away", StatusClass: "bg-yellow-50 text-yellow-600", StatusDotClass: "bg-yellow-600"},
{Name: "James Wilson", Initials: "JW", Email: "james.w@example.com", Role: "Marketing", Status: "Active", StatusClass: "bg-green-50 text-green-600", StatusDotClass: "bg-green-600"},
{Name: "Priya Patel", Initials: "PP", Email: "priya.p@example.com", Role: "Sales", Status: "Inactive", StatusClass: "bg-gray-50 text-gray-600", StatusDotClass: "bg-gray-400"},
{Name: "Alex Kim", Initials: "AK", Email: "alex.kim@example.com", Role: "Engineering", Status: "Active", StatusClass: "bg-green-50 text-green-600", StatusDotClass: "bg-green-600"},
},
}
err = t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
// fmt.Fprintf(w, "Welcome to the home page!")
const tpl = `
{{.Title}}
{{range .Items}}{{ . }}
{{else}}no rows
{{end}}
`
t, err := template.New("default").Parse(tpl)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := struct {
Title string
Items []string
}{
Title: "Hello",
Items: []string{"yo", "what's up"}, // template automatically escapes it
}
err = t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
log.Printf("listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}