tswap

package module
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2023 License: MIT Imports: 5 Imported by: 0

README

tswap

Package tswap automatically updates an html/template.Template when files in the directory where the template definitions are stored are updated. This can be useful if you want to work on changes to a website's UI without recompiling your application every time minor updates to a template definition file are made. tswap is dependent on github.com/fsnotify/fsnotify, which works for most, but not all, commonly used OS's.

Example

package main

import (
	"fmt"
	"html/template"
	"net/http"
	"sync"

	"github.com/cdillond/tswap"
)

type App struct {
	Mux *http.ServeMux
    	Rwm sync.RWMutex
	T   *template.Template
}

func main() {
	a := App{
		Mux: http.NewServeMux(),
        	Rwm: sync.RWMutex{},
	}
	dir := `templates/`
	t, err := template.ParseGlob(dir + `*`)
	if err != nil {
		panic(err)
	}
	a.T = t

	errChan := tswap.AutoUpdate(a.T, dir, &a.Rwm)
	go func() {
		for {
			err = <-errChan
			fmt.Println(err)
		}
	}()

	a.Mux.HandleFunc("/", a.Index)

	http.ListenAndServe(":1234", a.Mux)
}

func (a *App) Index(w http.ResponseWriter, r *http.Request) {
	a.Rwm.RLock()
	t, err := a.T.Lookup(`index.html`).Clone()
    	a.Rwm.RUnlock()
	if err != nil {
		return
	}
	t.Execute(w, struct{}{})
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoUpdate

func AutoUpdate(t *template.Template, dir string, rwm *sync.RWMutex) chan error

AutoUpdate takes a pointer to the template.Template that should be updated, the path to the directory where the template definition files are stored, and a pointer to a read-write mutex. The mutex should be used when accessing the template.Template from your web app to avoid race conditions resulting from updates made by AutoUpdate. Make sure errors can be received from the (buffered) chan error returned by AutoUpdate. Otherwise, AutoUpdate will pause if the channel is full. Calls to AutoUpdate must be followed by a blocking operation.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL