DOCUMENTATION
gohtmlbinder is a lightweight Go package that makes it easy to bind HTML templates to HTTP routes using Gorilla Mux.
It provides a simple and reusable way to serve web pages without having to manually handle html/template, routes, and servers in every project.
How to use
go get github.com/Masterpat48/gohtmlbinder
- Initialize the binder with:
b := binder.New("file.html")
- Make a route with static data:
b.NewRoute("/route", "file.html")
- Make a route with dynamic data:
b.NewRouteData("/route", "file.hmtl", func(r *http.Request) any{dynamic data})
- Print all the registred routes:
b.PrintRoutes()
b.serve(":port")
Example
package main
import (
"github.com/Masterpat48/gohtmlbinder"
)
func main() {
//initialize the binder W the index file (need to have the index file created)
b := binder.New("index.html")
//create the main route
b.NewRoute("/", "index.html")
//print in console all the registred routes
b.PrintRoutes()
//start the server on port 1000
b.Serve(":1000")
}
package main
import (
"net/http"
"sync"
"github.com/Masterpat48/gohtmlbinder"
)
func main() {
b := binder.New("index.html")
var mu sync.Mutex
count := 0
// Main route to show the number
b.NewRouteData("/", "index.html", func(r *http.Request) any {
mu.Lock()
defer mu.Unlock()
return map[string]any{"Count": count}
})
// Route to increment the number
b.NewRouteData("/increment", "index.html", func(r *http.Request) any {
if r.Method == http.MethodPost {
mu.Lock()
count++
mu.Unlock()
}
mu.Lock()
defer mu.Unlock()
return map[string]any{"Count": count}
})
b.PrintRoutes()
b.Serve(":1000")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Counter Example</title>
</head>
<body>
<h1>Counter: {{ .Count }}</h1>
<form action="/increment" method="POST">
<button type="submit">Increment</button>
</form>
</body>
</html>