~mariusor/go-assets

Go package for handling static asset files.

ac139c3 Use errors.Join for multi errors

3 days ago

f411b90 Added example 006 for using esbuild

1 year, 8 months ago

#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.