bricks

package module
v0.0.0-...-fce4ca1 Latest Latest
Warning

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

Go to latest
Published: May 18, 2024 License: MIT Imports: 23 Imported by: 4

README

bricks web framework

bricks is a Go-based, SSR-focused web framework.

Basics

You can define rich components with a set source file and unique behavior on render through bricks' component system and Go templates.

counter.go

var root = bricks.ComponentMust("Counter",
	bricks.Source("counter.html", "components/counter.html"),
	bricks.OnLoad(func(r *http.Request, args ...any) (data any, err error) {
		var iv int
		if len(args) > 0 {
			if v, ok := args[0].(int); ok {
				iv = v
			}
		}
		data = counterData{
			InitialValue: iv,
		}
		return
	}),
)

counter.html

<div class="counter" id="{{.ID}}">
    <button class="counter-btn">Add 1</button>
    <p class="counter-count">Value: 0</p>
</div>
<script>
{
    const counter = document.getElementById("{{.ID}}");
    let count = '{{.Data.InitialValue}}';
    const button = counter.getElementsByClassName("counter-btn")[0];
    const output = counter.getElementsByClassName("counter-count")[0];

    const update = () => {
        output.innerHTML = `Value: ${count}`
    }
    button.addEventListener('click', () => {
        count++
        update()
    })
    update()
}
</script>

index.html

...
<div>
    {{ call .Render "Counter" }}
    {{ call .Render "Counter" 5 }}
</div>
...

Getting Started

go get git.jnichols.info/bricks

Licensing

Bricks is licensed under the MIT license, which provides unconditional permission to use the software without restriction, as long as you include the copyright notice. The full text can be found in LICENSE.txt.

Documentation

Overview

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Copyright 2024 Jake Nichols (MIT License)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func App

func App(conf ...AppConfig) (a *app, err error)

func CoreLogger

func CoreLogger() *slog.Logger

func FileServer

func FileServer(fsRoot string) (handler http.Handler)

FileServer provides an http.Handler that responds to requests to httpRoot with files at fsRoot, starting at the working directory. example:

h := bricks.FileServer("", "/public")

if a request is made to /public/some/file, the response will be the file at ./some/file.

func Kwarg

func Kwarg[T any](key string, dest *T, defaultValue T, args ...any) (err error)

Kwarg gets the item immediately after a value of type string with value "key" cast as T. Returns nil if not found, and an error if the value is found but is not of type T.

func ListRange

func ListRange[T any](s []T) (out []listItem[T])

func Log

func Log(level slog.Level, msg string, attrs ...any)

Log aliases slog.Logger.Log for bricks' current logger. Currently, bricks always uses rfc3164 format.

func Run

func Run(a *app) error

Types

type AppConfig

type AppConfig func(a *app) (err error)

func Handle

func Handle(path string, handler http.Handler) AppConfig

Handle sets the app to handle requests to path with handler. If you're just handling a Component (as a page), you may want to use Page instead.

func LogRequestFormat

func LogRequestFormat(rfmt func(*http.Request) (slog.Level, string)) AppConfig

func Page

func Page(path string, page *Component, onPost http.Handler) AppConfig

Page sets the app to handle GET path with page and POST path with onPost, if onPost is not nil. Page is a specialization of Handle. If you need more complex behavior, use Handle instead.

func Public

func Public(httpRoot, fsRoot string) AppConfig

Public sets up a public directory for the application at httpRoot. Requests to a subresource of httpRoot will map to the same resource in a directory located at fsRoot. For example:

 app, err := bricks.App(
 	bricks.Handle("/", netkit.Methods{
			http.MethodGet: pages.Index,
		}),
		bricks.Handle("/features", netkit.Methods{
			http.MethodGet: pages.Features,
		}),
		bricks.Public("/public", "public"),
	)

creates an app where a request to /public/style.css maps to the file ./public/style.css *relative to the working directory*. Public will eliminate relative file requests, so it can't serve anything lower than the working directory of the application.

If DEBUG=true, Public will set Cache-Control=no-cache for all public files, which requires revalidation on each request (so things will reload).

type Arg

type Arg struct {
	Key   string
	Value any
}

func Kwargs

func Kwargs(args ...any) (kwargs []Arg, err error)

type Compiler

type Compiler interface {
	Compile() (t *template.Template, err error)
}

type Component

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

func ComponentMust

func ComponentMust(name string, conf ...componentConfig) (c *Component)

func NewComponent

func NewComponent(name string, conf ...componentConfig) (c *Component, err error)

func (*Component) ServeHTTP

func (c *Component) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ComponentConfig

type ComponentConfig func(c *Component) (err error)

func Funcs

func Funcs(funcs template.FuncMap) ComponentConfig

Funcs adds functions to the template. You may call this any number of times, but it must be called *before* any Source* function.

func Inherit

func Inherit(base *Component) ComponentConfig

func OnInit

func OnInit(f func() error) ComponentConfig

func OnLoad

func OnLoad(f func(r *http.Request, args ...any) (data any, err error)) ComponentConfig

func Struct

func Struct(s any) ComponentConfig

func Uses

func Uses(cs ...*Component) ComponentConfig

type Initer

type Initer interface {
	OnInit() error
}

type Loader

type Loader interface {
	OnLoad(r *http.Request, args ...any) (data any, err error)
}

type SourceConfig

type SourceConfig func(c *Component) (t TemplateFunc, err error)

SourceConfig is a specialized implementation of ComponentConfig whose role is to determine behavior for fetching and compiling source files.

func Language

func Language(defaultLang string, sources ...any) SourceConfig

func Source

func Source(filepath string) SourceConfig

Source configures a component to derive its template from the given filepath relative to where the component is defined. If the Source call comes from the current module, the file is loaded from the working directory. Otherwise, it is loaded from the go module cache, or the location specified by the GO_MOD_DIR environment variable.

If DEBUG=true, the source file will be reloaded on each page load.

func SourceRaw

func SourceRaw(name string, source string) SourceConfig

SourceRaw configures a component to derive its template from a raw string.

SourceRaw will NOT reload if DEBUG=true.

func SwitchSource

func SwitchSource(param func(r *http.Request) []string, def string, sources ...any) SourceConfig

SwitchSource allows modifying the source file based on a parameter derived from requests. Takes in a function to get parameter(s) from a request, a default value if the param func returns an empty or nil slice, and a set of ordered arguments. Arguments are a series of 1 or more string param values followed by a SourceConfig (Source, SourceRaw, SwitchSource). If the paramater value result from param matches one of these arguments, it will use the following source.

type TemplateFunc

type TemplateFunc func(r *http.Request) *template.Template

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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