assets

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

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

Go to latest
Published: Jan 27, 2023 License: MIT Imports: 20 Imported by: 2

README

Assets

A library to help with the management of serving static files.

It builds on top of any Go's standard fs.FS interface implementation and, it provides a method to overlay a different file structure on top of what the underlying fs exposes. We call this an "asset group".

It includes its own fs.FS implementation, which can be generated using //go:generate, and has a small advantage over the standard //go:embed mechanism by providing an API to pipeline functionality at resource compile time.

It currently supports filtering out files, and processing the remaining ones using a simple API.

See the examples folder for ways to use this.

Example 1: Simple mount of a DirFS fs

The asset group maps one to one with the files in the example's ./static folder.

Example 2: Overlaying an asset group over pieces representing files in a DirFS fs.

In this example the exposed entries of the asset group are each composed of multiple "pieces", each of them represented by a file in the ./static folder:

/main.js 
   ├─ ./static/js/hello.js
   └─ ./static/js/world.js

Example 3: using //go:embed

This is an example closer to real world usage where we embed the contents of the files in the ./static folder using //go:embed if we run/compile the example using the prod build tag, or we use the DirFS method we saw in example 1.

Example 4: using an external method for embedding the file contents

This example was born out of the need of adding some processing steps for the contents of the files, which can not be done using the standard //go:embed method.

In our case we chose to minify the CSS stylesheets, JavaScript files and the SVG document in the ./static folder.

Example 5: generating a single asset file from multiple on disk files

Instead of requiring the asset group in the consumer code, we can generate it directly containing our desired structure.

We bundle all the following files into just one that can be accessed at /main.js:

./static/
    └── js
        ├── assets.js
        ├── group.js
        └── hello.js

Example 6: using esbuild for bundling typescript

This example shows how to use the packing functionality to actually run an existing web bundler for compiling a typescript file into a desired javascript.

Documentation

Overview

Package assets represents a way to build a virtual File-system on top of an existing one.

This can largely be used as a way to expose a directory as web resource, but allowing that each individual "File" can be composed of multiple pieces, which need to exist on the underlying filesystem.

Example: Resource /main.js: {static/js/base.js, static/js/default.js}

It also provides tooling to build an embeddable instance of fs.FS.

It has a similar use to the standard library's "embed" package with the added feature of allowing filters and transformations to be pipelined for each of the files received.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidFS = fmt.Errorf("invalid FS")

Functions

func Aggregate

func Aggregate(ffs ...fs.FS) fs.FS

func Asset

func Asset(g fs.FS) func(string) template.HTML

Asset returns an asset by Fpath for display inside templates it is mainly used for rendering the svg icons File

func AssetSha

func AssetSha(g fs.FS, name string) string

func FromBytes

func FromBytes(bundle []byte, unpackFns ...processFn) fs.FS

FromBytes decompresses the bundle byte-slice and creates a virtual File system.

func GenerateCode

func GenerateCode(packageName, variableName, buildTags string, rawBytes []byte) ([]byte, error)

GenerateCode generates the code output to be written to disk. Writing the File is still left to the caller.

func HTTPFS

func HTTPFS(f *group) *httpFS

func Handler

func Handler(g fs.FS) func(w http.ResponseWriter, r *http.Request)

func Integrity

func Integrity(g fs.FS, name string) template.HTMLAttr

Integrity gives us the integrity attribute for subresource integrity checks

func New

func New(base fs.FS) (*group, error)

func Pack

func Pack(paths []string, packFns ...processFn) ([]byte, error)

Pack compresses a set of files from disk for bundled use in the generated code.

func Routes

func Routes(m *http.ServeMux, g group) error

Routes maps an asset grup to handler functions for serving the content TODO(marius) Allow for passing a prefix for the routes TODO(marius) I doubt that we need to generate a function for each asset, instead of using one for the whole group

func Script

func Script(g fs.FS, name string) template.HTML

Script returns by Fpath a script node's contents for displaying inline in a template.HTML This function assumes a <script/> node surrounds it.

func ScriptNode

func ScriptNode(g fs.FS, name string) template.HTML

ScriptNode returns a script node together with an integrity hash to be output inline in a template.HTML The href of the node points to a URL which resolves to the File's content as served by the Routes() function.

func Style

func Style(g fs.FS, name string) template.CSS

Style returns by Fpath a style node's contents for displaying inline in a template.HTML This function assumes a <style/> node surrounds it.

func StyleNode

func StyleNode(g fs.FS, name string) template.HTML

StyleNode returns a style link together with an integrity hash to be output inline in a template.HTML, The href of the node points to a URL which resolves to the File's content as served by the Routes() function.

func SubresourceIntegrityHash

func SubresourceIntegrityHash(g fs.FS, name string) (string, bool)

func Svg

func Svg(g fs.FS, name string) template.HTML

Svg returns by Fpath a svg node for displaying verbatim in a template.HTML

Types

type FS

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

func (*FS) Open

func (f *FS) Open(path string) (fs.File, error)

Open opens the named File for reading. If successful, methods on the returned File can be used for reading.

func (*FS) ReadDir

func (f *FS) ReadDir(name string) ([]fs.DirEntry, error)

ReadDir reads the named directory and returns a list of directory entries sorted by filename.

func (*FS) Stat

func (f *FS) Stat(path string) (fs.FileInfo, error)

Stat returns a FileInfo describing the named File.

type File

type File struct {
	Data  []byte
	Fpath string
	Fname string
	Fsize int64
	Ftime int64
	// contains filtered or unexported fields
}

func NewFile

func NewFile(path string, root fs.FS) (*File, error)

NewFile constructs a new bundled File from the disk.

It is only supposed to be called from the broccoli tool.

func (*File) Close

func (f *File) Close() error

Close clears the dedicated File buffer.

func (*File) Info

func (f *File) Info() (fs.FileInfo, error)

Info returns the FileInfo for the File or subdirectory described by the entry. The returned FileInfo may be from the Ftime of the original directory read or from the Ftime of the call to Info. If the File has been removed or renamed since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist). If the entry denotes a symbolic link, Info reports the information about the link itself, not the link's target.

func (*File) IsDir

func (f *File) IsDir() bool

IsDir tells whether if the File is a directory.

func (*File) ModTime

func (f *File) ModTime() time.Time

ModTime returns the Ftime File was last modified.

func (*File) Mode

func (f *File) Mode() os.FileMode

Mode returns the File mode of the File.

It's os.ModeDir for directories, 0444 otherwise.

func (*File) Name

func (f *File) Name() string

Name returns the basename of the File.

func (*File) Open

func (f *File) Open() error

Open opens the File for reading. If successful, methods on the returned File can be used for reading.

func (*File) Path

func (f *File) Path() string

Path returns the full Fpath of the file

func (*File) Read

func (f *File) Read(b []byte) (int, error)

Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read. If the buffer has no Fdata to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.

func (*File) ReadDir

func (f *File) ReadDir(n int) ([]fs.DirEntry, error)

ReadDir reads the contents of the directory associated with the File f and returns a slice of DirEntry values in directory order. Subsequent calls on the same File will yield later DirEntry records in the directory.

If n > 0, ReadDir returns at most n DirEntry records. In this case, if ReadDir returns an empty slice, it will return an error explaining why. At the end of a directory, the error is io.EOF.

If n <= 0, ReadDir returns all the DirEntry records remaining in the directory. When it succeeds, it returns a nil error (not io.EOF).

func (*File) Size

func (f *File) Size() int64

Size returns the Fsize of the File in bytes.

func (*File) Stat

func (f *File) Stat() (os.FileInfo, error)

Stat returns a FileInfo describing this File.

func (*File) Sys

func (f *File) Sys() any

Sys returns the underlying Fdata source, which in this case is nil

func (*File) Type

func (f *File) Type() fs.FileMode

Type returns the type bits for the entry. The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.

func (*File) Write

func (f *File) Write(data []byte) (int, error)

Writer is the interface that wraps the basic Write method.

Write writes len(p) bytes from p to the underlying Fdata stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p). Write must not modify the slice Fdata, even temporarily.

Implementations must not retain p.

type Generator

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

Generator collects the necessary info about the package and bundles the provided assets into a byte slice.

func Glob

func Glob(includeGlob ...string) Generator

func Mount

func Mount(fs fs.FS) Generator

func (Generator) Glob

func (g Generator) Glob(includeGlob ...string) Generator

func (Generator) Mount

func (g Generator) Mount(fs fs.FS) Generator

func (Generator) Pack

func (g Generator) Pack(packFns ...processFn) ([]byte, error)

func (Generator) WithFilters

func (g Generator) WithFilters(filterFns ...filterFn) Generator

type Map

type Map map[string]pieces

Map represents the mapping between the "virtual" filesystem that we expose and the underlying one that we map on top of.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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