fir

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2022 License: MIT Imports: 39 Imported by: 1

README

Fir

Go Reference npm version

A Go toolkit to build reactive web interfaces using: Go, html/template and alpinejs.

Status: This is a work in progress. Checkout examples to see what works today: examples

Fir is a toolkit for building server-rendered HTML applications and progressively enhancing them to enable real-time user experiences. It is intended for developers who want to build real-time web apps using Go, server-rendered HTML (html/template), CSS, and sprinkles of declarative javascript (Alpine.js). The toolkit can be used to build a completely server-rendered web application with zero javascript, and the same app can then be progressively enhanced on the client to a real-time dynamic app with little bits of javascript while still using Go's html/template engine on the server. Fir can be used to build various types of web applications, including static websites like landing pages or blogs, interactive CRUD apps like ticket helpdesks, and real-time apps like metrics dashboards or social media streams.

Fir enhances a standard html/template web page with alpine.js allowing predefined parts of the page updatable on user interaction. A html/template page is decomposed into updatable parts using the block action. This allows Fir to re-compile the targeted block on the server and update the web page over the wire(http & websocket) and without page reloads. The HTML itself is largely quite standard i.e. its free of magics or special attributes except what’s exposed by the alpinejs plugin. The plugin exposes a small API and is designed to be unobtrusive and easy to remove incase one wants to migrate the HTML to another framework.

Example

Using fir's alpinejs plugin, the page below has been progressively enhanced to a real-time single page app. Open two tabs to see the count update in both. Disable javascript in your browser to see it still work without the enhancements.

package main

import (
	"net/http"
	"sync/atomic"

	"github.com/livefir/fir"
)

func index() fir.RouteOptions {
	var count int32
	return fir.RouteOptions{
		fir.ID("counter"),
		fir.Content("count.html"),
		fir.OnLoad(func(ctx fir.RouteContext) error {
			return ctx.KV("count", atomic.LoadInt32(&count))
		}),
		fir.OnEvent("inc", func(ctx fir.RouteContext) error {
			return ctx.KV("count", atomic.AddInt32(&count, 1))
		}),
		fir.OnEvent("dec", func(ctx fir.RouteContext) error {
			return ctx.KV("count", atomic.AddInt32(&count, -1))
		}),
	}
}

func main() {
	controller := fir.NewController("counter_app", fir.DevelopmentMode(true))
	http.Handle("/", controller.RouteFunc(index))
	http.ListenAndServe(":9867", nil)
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <script
            defer
            src="https://unpkg.com/@livefir/fir@latest/dist/fir.min.js"></script>

        <script
            defer
            src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
    </head>

    <body>
        <div x-data>
            <div
                id="count"
                @fir:inc.window="$fir.replace()"
                @fir:dec.window="$fir.replace()">
                {{ block "count" . }}
                    <div>Count: {{ .count }}</div>
                {{ end }}
            </div>
            <form method="post" @submit.prevent="$fir.submit()">
                <button formaction="/?event=inc" type="submit">+</button>
                <button formaction="/?event=dec" type="submit">-</button>
            </form>
        </div>
    </body>
</html>

In the above example, @inc.window="$fir.replaceEl()" marks <div id="count"> to be replaced by the content of a block which matches the element's div id count which in this case is {{ block "count" . }} ... {{ end }}. The matching is done on the server and block action names can contain a wildcard, for e.g. block "count* would match count or count-1.

$fir.submit is a helper which prevents the form submission and dispatches browser events inc and dec which is then captured by @inc.window, @dec.window listeners registered on <div id="count">. It also captures any form data and attaches it to the event before its sent to the server by $fir.replaceEl. In this example we don't have any form data.

Documentation

Index

Constants

View Source
const UserIDKey = "key_user_id"

UserIDKey is the key for the user id in the request context. It is used in the default channel function.

Variables

This section is empty.

Functions

This section is empty.

Types

type Controller

type Controller interface {
	Route(route Route) http.HandlerFunc
	RouteFunc(options RouteFunc) http.HandlerFunc
}

Controller is an interface which encapsulates a group of views. It routes requests to the appropriate view. It routes events to the appropriate view. It also provides a way to register views.

func NewController

func NewController(name string, options ...ControllerOption) Controller

NewController creates a new controller.

type ControllerOption

type ControllerOption func(*opt)

ControllerOption is an option for the controller.

func DevelopmentMode

func DevelopmentMode(enable bool) ControllerOption

DevelopmentMode is an option to enable development mode. It enables debug logging, template watching, and disables template caching.

func DisableTemplateCache

func DisableTemplateCache() ControllerOption

DisableTemplateCache is an option to disable template caching. This is useful for development.

func EnableDebugLog

func EnableDebugLog() ControllerOption

EnableDebugLog is an option to enable debug logging.

func EnableWatch

func EnableWatch(rootDir string, extensions ...string) ControllerOption

EnableWatch is an option to enable watching template files for changes.

func WithChannel

func WithChannel(f func(r *http.Request, viewID string) *string) ControllerOption

WithChannelFunc is an option to set a function to construct the channel name for the controller's views.

func WithEmbedFS

func WithEmbedFS(fs embed.FS) ControllerOption

WithEmbedFS is an option to set the embed.FS for the controller.

func WithFormDecoder

func WithFormDecoder(decoder *schema.Decoder) ControllerOption

WithFormDecoder is an option to set the form decoder(gorilla/schema) for the controller.

func WithPublicDir

func WithPublicDir(path string) ControllerOption

WithPublicDir is the path to directory containing the public html template files.

func WithPubsubAdapter

func WithPubsubAdapter(pubsub pubsub.Adapter) ControllerOption

WithPubsubAdapter is an option to set a pubsub adapter for the controller's views.

func WithValidator

func WithValidator(validator *validator.Validate) ControllerOption

WithValidator is an option to set the validator(go-playground/validator) for the controller.

func WithWebsocketUpgrader

func WithWebsocketUpgrader(upgrader websocket.Upgrader) ControllerOption

WithWebsocketUpgrader is an option to set the websocket upgrader for the controller

type Event

type Event struct {
	// Name is the name of the event
	ID string `json:"event_id"`
	// Params is the json rawmessage to be passed to the event
	Params   json.RawMessage `json:"params"`
	FormID   *string         `json:"form_id,omitempty"`
	SourceID *string         `json:"source_id,omitempty"`
}

Event is a struct that holds the data for an event

func NewEvent

func NewEvent(id string, params any) Event

NewEvent creates a new event

func (Event) String

func (e Event) String() string

String returns the string representation of the event

type OnEventFunc

type OnEventFunc func(ctx RouteContext) error

OnEventFunc is a function that handles an http event request

type Route

type Route interface{ Options() RouteOptions }

Route is an interface that represents a route

type RouteContext

type RouteContext struct {
	// contains filtered or unexported fields
}

RouteContext is the context for a route handler. Its methods are used to return data or patch operations to the client.

func (RouteContext) Bind

func (c RouteContext) Bind(v any) error

Bind decodes the event params into the given struct

func (RouteContext) BindEventParams

func (c RouteContext) BindEventParams(v any) error

func (RouteContext) BindPathParams

func (c RouteContext) BindPathParams(v any) error

func (RouteContext) BindQueryParams

func (c RouteContext) BindQueryParams(v any) error

func (RouteContext) Data

func (c RouteContext) Data(data any) error

Data sets the data to be hydrated into the route's template or an event's associated template/block action It accepts either a map or struct type so that fir can inject utility functions: .fir.Error, .fir.ActiveRoute etc.

func (RouteContext) Event

func (c RouteContext) Event() Event

func (RouteContext) FieldError

func (c RouteContext) FieldError(field string, err error) error

FieldError sets the error message for the given field and can be looked up by {{.fir.Error "myevent.field"}}

func (RouteContext) FieldErrors

func (c RouteContext) FieldErrors(fields map[string]error) error

FieldErrors sets the error messages for the given fields and can be looked up by {{.fir.Error "myevent.field"}}

func (RouteContext) KV

func (c RouteContext) KV(key string, data any) error

KV is a wrapper for ctx.Data(map[string]any{key: data})

func (RouteContext) Redirect

func (c RouteContext) Redirect(url string, status int) error

Redirect redirects the client to the given url

func (RouteContext) Request

func (c RouteContext) Request() *http.Request

Request returns the http.Request for the current context

func (RouteContext) Response

func (c RouteContext) Response() http.ResponseWriter

Response returns the http.ResponseWriter for the current context

type RouteDOMContext

type RouteDOMContext struct {
	Name    string
	URLPath string
	// contains filtered or unexported fields
}

RouteDOMContext is a struct that holds route context data and is passed to the template

func (*RouteDOMContext) ActiveRoute

func (rc *RouteDOMContext) ActiveRoute(path, class string) string

ActiveRoute returns the class if the route is active

func (*RouteDOMContext) Error

func (rc *RouteDOMContext) Error(paths ...string) any

Error can be used to lookup an error by name Example: {{.fir.Error "myevent.field"}} will return the error for the field myevent.field Example: {{.fir.Error "myevent" "field"}} will return the error for the event myevent.field It can be used in conjunction with ctx.FieldError to get the error for a field

func (*RouteDOMContext) NotActiveRoute

func (rc *RouteDOMContext) NotActiveRoute(path, class string) string

NotActive returns the class if the route is not active

type RouteFunc

type RouteFunc func() RouteOptions

RouteFunc is a function that handles a route

type RouteOption

type RouteOption func(*routeOpt)

RouteOption is a function that sets route options

func Content

func Content(content string) RouteOption

Content sets the content for the route

func EventSender

func EventSender(eventSender chan Event) RouteOption

EventSender sets the event sender for the route. It can be used to send events for the route without a corresponding user event. This is useful for sending events to the route event handler for use cases like: sending notifications, sending emails, etc.

func Extensions

func Extensions(extensions ...string) RouteOption

Extensions sets the template file extensions read for the route's template engine

func FuncMap

func FuncMap(funcMap template.FuncMap) RouteOption

FuncMap appends to the default template function map for the route's template engine

func ID

func ID(id string) RouteOption

ID sets the route unique identifier. This is used to identify the route in pubsub.

func Layout

func Layout(layout string) RouteOption

Layout sets the layout for the route's template engine

func LayoutContentName

func LayoutContentName(name string) RouteOption

LayoutContentName sets the name of the template which contains the content.

{{define "layout"}}
{{ define "content" }}
{{ end }}
{{end}}

Here "content" is the default layout content name

func OnEvent

func OnEvent(name string, onEventFunc OnEventFunc) RouteOption

OnEvent registers an event handler for the route per unique event name. It can be called multiple times to register multiple event handlers for the route.

func OnLoad

func OnLoad(f OnEventFunc) RouteOption

OnLoad sets the route's onload event handler

func Partials

func Partials(partials ...string) RouteOption

Partials sets the template partials for the route's template engine

type RouteOptions

type RouteOptions []RouteOption

RouteOptions is a slice of RouteOption

Jump to

Keyboard shortcuts

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