├── index.html
└── main.go
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | HTMX & Go - Demo
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
Film List
17 |
18 |
19 | {{ range .Films }}
20 | {{ block "film-list-element" .}}
21 | - {{ .Title }} - {{ .Director }}
22 | {{ end }}
23 | {{ end }}
24 |
25 |
26 |
27 |
28 |
Add Film
29 |
30 |
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "html/template"
6 | "log"
7 | "net/http"
8 | "time"
9 | )
10 |
11 | type Film struct {
12 | Title string
13 | Director string
14 | }
15 |
16 | func main() {
17 | fmt.Println("Go app...")
18 |
19 | // handler function #1 - returns the index.html template, with film data
20 | h1 := func(w http.ResponseWriter, r *http.Request) {
21 | tmpl := template.Must(template.ParseFiles("index.html"))
22 | films := map[string][]Film{
23 | "Films": {
24 | {Title: "The Godfather", Director: "Francis Ford Coppola"},
25 | {Title: "Blade Runner", Director: "Ridley Scott"},
26 | {Title: "The Thing", Director: "John Carpenter"},
27 | },
28 | }
29 | tmpl.Execute(w, films)
30 | }
31 |
32 | // handler function #2 - returns the template block with the newly added film, as an HTMX response
33 | h2 := func(w http.ResponseWriter, r *http.Request) {
34 | time.Sleep(1 * time.Second)
35 | title := r.PostFormValue("title")
36 | director := r.PostFormValue("director")
37 | // htmlStr := fmt.Sprintf("%s - %s", title, director)
38 | // tmpl, _ := template.New("t").Parse(htmlStr)
39 | tmpl := template.Must(template.ParseFiles("index.html"))
40 | tmpl.ExecuteTemplate(w, "film-list-element", Film{Title: title, Director: director})
41 | }
42 |
43 | // define handlers
44 | http.HandleFunc("/", h1)
45 | http.HandleFunc("/add-film/", h2)
46 |
47 | log.Fatal(http.ListenAndServe(":8000", nil))
48 |
49 | }
50 |
--------------------------------------------------------------------------------