Skip to content

Masterpat48/gohtmlbinder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

  • Install the module with:
  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()
  • Check the registred routes on the /status auto generated route:
  b.Status()
  • Start the server:
  b.serve(":port")

Example

  • Static data
package main

import binder "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()
	//Check the routes on the /status route
	b.Status()
	//start the server on port 1000
	b.Serve(":1000")
}
  • Dynamic data
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.Status()
	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>

About

GO module to simplify binding and routing an HTML project

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages