• Stars
    star
    162
  • Rank 224,175 (Top 5 %)
  • Language
    Go
  • License
    Other
  • Created over 5 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Compress and embed static files and assets into Go binaries and access them with a virtual file system in production

stuffbin

stuffbin is a utility + package to compress and embed static files and assets into Go binaries for distribution. It supports falling back to the local file system when no embedded assets are available, for instance, in development mode. stuffbin is inspired by zgok but is simpler and has better abstractions.

stuffbin vs. Go 1.16 embed

Go 1.16 introduced the //go:embed directive that allows embedding of files into Go binaries without any external utilities. stuffbin offers a few key advantages over native embedding in its current form.

  • All files are ZIP compressed.
  • Custom path aliases (eg: embed /home/local/path/file.txt as /app/file.txt).
  • Dynamically embed files instead of static //go:embed directives.
  • Embed parent directories, sub-directories, and arbitrary paths (eg: ../../path). Go embed does not permit embedding of files outside of a .go file's directory. This makes it difficult for programs structured in a cmd directory to embed files outside it.
  • Better filesystem abstraction for virtual filesystem manipulation, including merging.

How does it work?

stuffbin

stuffbin compresses and embeds arbitrary files to the end of Go binaries. This does not affect the normal execution of the binary as the compressed data that is appended beyond the binary's original size is simply ignored by the operating system. When a stuffed application is executed, stuffbin reads the compressed bytes from self (the executable), uncompresses the files on the fly into an in-memory filesystem, and provides a FileSystem interface to access them. This enables Go applications that have external file dependencies to be shipped a single fat binary, commonly, web applications that have static file and template dependencies.

  • Built in ZIP compression
  • A virtual filesystem abstraction to access embedded files
  • Add static assets from nested directories recursively
  • Re-path files and whole directories with the :suffix format, eg: ../my/original/file.txt:/my/virtual/file.txt and /my/nested/dir:/virtual/dir
  • Template parsing helper similar to template.ParseGlob() to parse templates from the virtual filesystem
  • Launch an http.FileServer for serving static files
  • Gracefully failover to the local file system in the absence of embedded assets
  • CLI to stuff, unstuff and extract, and list stuffed files in binaries

Installation

go get -u github.com/knadh/stuffbin/...

Homebrew

For macOS/Linux users, you can install via brew

$ brew install stuffbin

Usage

Stuffing and embedding

# -a, -in, and -out params followed by the paths of files to embed.
# To normalize paths, aliases can be suffixed with a colon.
stuffbin -a stuff -in /path/to/exe -out /path/to/new.exe \
    static/file1.css static/file2.pdf /somewhere/else/file3.txt:/static/file3.txt

List files in a stuffed binary

stuffbin -a id -in /path/to/new/exe

Extract stuffed files from a binary

stuffbin -a unstuff -in /path/to/new/exe -out assets.zip

In the application

To test this, cd into ./mock and run go run mock.go

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/knadh/stuffbin"
)

func main() {
	// Get self executable path.
	path, err := os.Executable()
	if err != nil {
		log.Fatalf("error getting executable path: %v", err)
	}
	// Read stuffed data from self.
	fs, err := stuffbin.UnStuff(path)
	if err != nil {
		// Binary is unstuffed or is running in dev mode.
		// Can halt here or fall back to the local filesystem.
		if err == stuffbin.ErrNoID {
			// First argument is to the root to mount the files in the FileSystem
			// and the rest of the arguments are paths to embed.
			fs, err = stuffbin.NewLocalFS("/",
				"./", "bar.txt:/virtual/path/bar.txt")
			if err != nil {
				log.Fatalf("error falling back to local filesystem: %v", err)
			}
		} else {
			log.Fatalf("error reading stuffed binary: %v", err)
		}
	}

	fmt.Println("loaded files", fs.List())
	// Read the file 'foo'.
	f, err := fs.Get("foo.txt")
	if err != nil {
		log.Fatalf("error reading foo.txt: %v", err)
	}
	log.Println("foo.txt =", string(f.ReadBytes()))

	// Read the file 'bar'.
	f, err = fs.Get("/virtual/path/bar.txt")
	if err != nil {
		log.Fatalf("error reading /virtual/path/bar.txt: %v", err)
	}
	log.Println("/virtual/path/bar.txt =", string(f.ReadBytes()))

	fmt.Println("stuffed files:")
	for _, f := range fs.List() {
		fmt.Println("\t", f)
	}

	// Compile templates with the helpers:
	// err, tpl := stuffbin.ParseTemplatesGlob(nil, fs, "/templates/*.html")
	//
	// Template func map.
	// mp := map[string]interface{}{
	// 	"Foo": func() string {
	// 		return "func"
	// 	},
	// }
	// err, tpl := stuffbin.ParseTemplates(mp, fs, "/templates/index.html", "/templates/hello.html")

	// Expose an HTTP file server.
	// Try http://localhost:8000/static/foo.txt
	// Try http://localhost:8000/static/virtual/path/bar.txt
	// Try http://localhost:8000/static/subdir/baz.txt
	http.Handle("/static/", http.StripPrefix("/static/", fs.FileServer()))
	log.Println("listening on :8000")
	http.ListenAndServe(":8000", nil)
}

License

Licensed under the MIT License.

More Repositories

1

listmonk

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
Go
13,387
star
2

dns.toys

A DNS server that offers useful utilities and services over the DNS protocol. Weather, world time, unit conversion etc.
Go
2,423
star
3

koanf

Simple, extremely lightweight, extensible, configuration management library for Go. Support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
Go
2,278
star
4

niltalk

Instant, disposable, single-binary web based live chat server. Go + VueJS.
Go
926
star
5

dragmove.js

A super tiny Javascript library to make DOM elements draggable and movable. ~500 bytes and no dependencies.
JavaScript
822
star
6

localStorageDB

A simple database layer for localStorage and sessionStorage for creating structured data in the form of databases and tables
JavaScript
802
star
7

tg-archive

A tool for exporting Telegram group chats into static websites like mailing list archives.
Python
710
star
8

otpgateway

Standalone server for user address and OTP verification flows with pluggable providers (e-mail, SMS, bank penny drops etc.)
Go
401
star
9

hugo-ink

Crisp, minimal personal website and blog theme for Hugo
HTML
393
star
10

dictpress

A stand-alone web server application for building and publishing full fledged dictionary websites and APIs for any language.
Go
347
star
11

autocomp.js

A super tiny Javascript autocomplete / autosuggestions library. Zero dependencies, ~800 bytes min+gzip.
JavaScript
288
star
12

xmlutils.py

Python scripts for processing XML documents and converting to SQL, CSV, and JSON [UNMAINTAINED]
Python
239
star
13

dont.build

A simple, opinionated decision system to help decide whether to build a software feature or not.
HTML
203
star
14

go-get-youtube

A tiny Go library + client for downloading Youtube videos. The library is capable of fetching Youtube video metadata, in addition to downloading videos.
Go
155
star
15

smtppool

High throughput Go SMTP pool library with graceful handling of idle timeouts, errors, and retries.
Go
119
star
16

git-bars

A utility for visualising git commit activity as bars on the terminal
Python
83
star
17

ml2en

An algorithm that transliterates Malayalam script to Roman / Latin characters (commonly 'Manglish') with reasonable phonetic fairness. Available in Python, PHP, Javascript
Python
82
star
18

simplemysql

An ultra simple wrapper for Python MySQLdb with very basic functionality
Python
77
star
19

indexed-cache

A tiny Javsacript library for sideloading static assets on pages and caching them in the browser's IndexedDB for longer-term storage.
JavaScript
76
star
20

go-pop3

A simple Go POP3 client library for connecting and reading mails from POP3 servers.
Go
71
star
21

pfxsigner

A CLI utility and web server for digitally signing PDFs with docsign loaded from PFX (PKCS#12) files
Go
69
star
22

floatype.js

A tiny, zero-dependency, floating autocomplete / autosuggestion widget for textareas.
JavaScript
67
star
23

indic.page

A directory of Indic (Indian) language computing resources.
HTML
55
star
24

dirmaker

dirmaker is a simple, opinionated static site generator for quickly publishing directory websites.
Python
48
star
25

goyesql

Parse SQL files with multiple named queries and automatically prepare and scan them into structs.
Go
45
star
26

knphone

KNphone is a phonetic algorithm for indexing Kannada words by their pronunciation, like Metaphone for English.
Go
44
star
27

tinytabs

A tiny (1.3 KB minified) Javascript tabbing library for rendering tabbed UIs. Zero dependencies.
HTML
44
star
28

wordpluck

A browser based typing game in Javascript. Revived from a 2012 project.
JavaScript
42
star
29

datuk

"Datuk", the Unicode Malayalam - Malayalam dictionary dataset
38
star
30

csv2json

csv2json is a fast utility that converts CSV files into JSON line files. An experiment in Zig lang.
Zig
36
star
31

profiler

A simple wrapper over Go runtime/pprof for running multiple concurrent profiles and dumping results to files.
Go
30
star
32

mlphone

MLphone (Python, PHP) is a phonetic algorithm for indexing Malayalam words by their pronounciation, like Metaphone for English. The algorithm generates three Romanized phonetic keys (hashes) of varying phonetic proximities for a given Malayalam word.
PHP
28
star
33

gtbump

git tag bump: A simple utility to bump and manage git semantic version tags and generate Markdown changelogs.
Python
20
star
34

paginator

Tiny Go package for pagination queries and generating page numbers
Go
19
star
35

listmonk-heroku-deploy

Official listmonk install button for Heroku.
Shell
16
star
36

listmonk-site

Static website + docs for listmonk
HTML
16
star
37

bigreddy

BigReddy is a small utility that generates pseudo-philosophical and pseudo-poetic ramblings.
Python
15
star
38

otpgateway-solsms

SMS provider for otpgateway (SolutionsInfini, India)
Go
15
star
39

tinyprogressbar

tinyProgressbar is an extremely tiny (640 bytes minified+gzipped) Javascript progressbar library
JavaScript
15
star
40

go-i18n

Tiny i18n library for loading and using simple JSON language translation files in Go programs.
Go
14
star
41

tinyauth

Tiny, opinionated authentication library for Go. Work in progress and not usable right now.
Go
14
star
42

simpleplanner

Simple planner
JavaScript
13
star
43

querytostruct

An extremely tiny utility for unmarshalling and scanning querystrings into structs
Go
13
star
44

jsonconfig

Super tiny JSON configuration file parser with comments support for Go programs
Go
12
star
45

scylladb-metrics

A script for generating docs for Promethus metrics exported by ScyllaDB
HTML
10
star
46

zig-releaser

A simple hack to use GoReleaser to build, release, and publish Zig projects.
Shell
10
star
47

tinytooltip

An extremely tiny tooltip plugin for jQuery
JavaScript
10
star
48

stringvalidator.py

Aa simple string validator class in Python for basic data validation such as checking if a string is alpha, alphanumeric, e-mail etc.
Python
8
star
49

jqdialog

A jQuery plugin with smooth and peristent dialog boxes meant as a replacement for alert(), confirm(), and prompt()
JavaScript
8
star
50

boastmachine

boastMachine (legacy), a full fledged blogging package. One of the earliest on the web, first released in 2002.
PHP
7
star
51

ctunes

A prototype music list manager. C programming exercise I did a very long time ago.
C
6
star
52

CANT24

A neural network framework (primarily, a fLIF neuron simulator)
4
star
53

chunkedreader

chunkedreader is a light weight wrapper for Go's `bufio` that enables reading of byte streams in fixed size chunks
Go
4
star
54

rofi-vscode-projects

A vscode project launcher menu for the rofi app launcher
3
star
55

omeka-total-pages

An Omeka-S plugin for computing the total number of pages across items in an item set or collection.
PHP
2
star
56

viper

Go configuration with fangs
Go
1
star
57

csssprite

A simple utility for merging images into a sprite with accompanying CSS
Python
1
star