WEB AND APIS · IN THE APP NOW
Static website
Two pages, a stylesheet and a click counter in web/, with a Go program beside them that renders a list of posts through html/template.
Offline: standard library only
What it is
The project opens on web/index.html. Open the preview from the Output pane: the pages in web/ are served on the device, and the preview follows your edits.
main.go shows the server half of a Go site. html/template escapes whatever it inserts, so a post title containing <script> is printed as text rather than markup.
Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.
Files
static-site/
├── web/
│ ├── about.html
│ ├── app.js
│ ├── index.html
│ └── styles.css
├── go.mod
└── main.goThe code
main.go
package main
import (
"html/template"
"os"
)
// The pages in web/ are served on this device while you edit them: open the
// preview from the Output pane. This program shows the other half of a Go
// site, rendering HTML from data with html/template, which escapes whatever
// it inserts. On a server, serve the folder with
// http.ListenAndServe(":8080", http.FileServer(http.Dir("web"))).
type post struct {
Title, Slug string
Minutes int
}
var page = template.Must(template.New("posts").Parse(`<ul>
{{range .}} <li><a href="/posts/{{.Slug}}.html">{{.Title}}</a> · {{.Minutes}} min</li>
{{end}}</ul>
`))
func main() {
posts := []post{
{Title: "Hello, site", Slug: "hello", Minutes: 2},
{Title: "Why <script> tags are escaped", Slug: "escaping", Minutes: 4},
}
if err := page.Execute(os.Stdout, posts); err != nil {
panic(err)
}
}web/app.js
const button = document.getElementById("count");
let clicks = 0;
button.addEventListener("click", () => {
clicks += 1;
button.textContent = `Clicked ${clicks} time${clicks === 1 ? "" : "s"}`;
});What you learn
- Lay out a small site in web/ with a shared stylesheet and a script.
- Parse a template once with template.Must and execute it with data.
- Loop over a slice with {{range}} and print fields with {{.Title}}.
- See how html/template escapes inserted text.
- Serve a folder with http.FileServer on a server.
Run it on a server
Serve the folder with the standard file server, as the comment in main.go says. Replace main, import log and net/http, then open http://localhost:8080.
func main() {
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("web"))))
}go run .Related: html/template escapes by context · Security course