render html in default route
This commit is contained in:
+24
-27
@@ -1,51 +1,48 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"html/template"
|
"html/template"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var x = 2
|
var x = 2
|
||||||
|
|
||||||
func testTemplate() {
|
func main() {
|
||||||
const tpl = `
|
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
|
||||||
|
w.WriteHeader(200)
|
||||||
|
// fmt.Fprintf(w, "Welcome to the home page!")
|
||||||
|
const tpl = `
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<title>{{.Title}}</title>
|
<title>{{.Title}}</title>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
{{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
|
{{range .Items}}<div class="bg-red-200">{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
|
||||||
</body>
|
</body>
|
||||||
</html>`
|
</html>`
|
||||||
|
|
||||||
t, err := template.New("default").Parse(tpl)
|
t, err := template.New("default").Parse(tpl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("%v", err)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
}
|
return
|
||||||
|
}
|
||||||
|
|
||||||
data := struct {
|
data := struct {
|
||||||
Title string
|
Title string
|
||||||
Items []string
|
Items []string
|
||||||
}{
|
}{
|
||||||
Title: "Hello",
|
Title: "Hello",
|
||||||
Items: []string{"yo", template.HTMLEscapeString("what's up")},
|
Items: []string{"yo", "what's up"}, // template automatically escapes it
|
||||||
}
|
}
|
||||||
err = t.Execute(os.Stdout, data)
|
err = t.Execute(w, data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("%v", err)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
}
|
return
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
|
|
||||||
w.WriteHeader(200)
|
|
||||||
fmt.Fprintf(w, "Welcome to the home page!")
|
|
||||||
})
|
})
|
||||||
log.Printf("listening on port 8080")
|
log.Printf("listening on port 8080")
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
|
|||||||
Reference in New Issue
Block a user