htmx-playground/http-serve.go

67 lines
1.4 KiB
Go
Raw Normal View History

2024-09-10 02:07:53 +02:00
package main
import (
"html/template"
"net/http"
_ "embed"
)
// Struct to hold data to be passed to the template
type PageData struct {
Title string
Name string
}
//go:embed views/index.html
var tmpl string
//go:embed views/style.css
var style string
//go:embed htmx.min.js
var htmx string
2024-11-01 16:25:34 +01:00
//go:embed van.min.js
var van string
2024-09-10 02:07:53 +02:00
func main() {
// Parse the template from the string literal
t := template.Must(template.New("webpage").Parse(tmpl))
// Handler for the root URL
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := PageData{
Title: "Hello Page",
}
// Check if a name is provided via the form
if r.Method == http.MethodPost {
data.Name = r.FormValue("name")
}
// Execute the template, passing in the data
t.Execute(w, data)
})
http.HandleFunc("/style.css", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css")
w.Write([]byte(style))
})
http.HandleFunc("/htmx.min.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
w.Write([]byte(htmx))
})
2024-11-01 16:25:34 +01:00
http.HandleFunc("/van.min.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
w.Write([]byte(van))
})
2024-09-10 02:07:53 +02:00
// Start the server on port 8080
println("Listening on http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}