File Embedding in Go

Talk at Golang Leipzig November Meetup

What is File Embedding?

├── assets
│   ├── base.css
│   ├── base.js
│   ├── ...
│   └── favicon.svg
├── migrations
│   ├── 01_initial_setup.down.sql
│   └── ...
├── notes.go
├── storage.go
├── storage_test.go
└── views
    ├── index.gohtml
    ├── ...
    └── layouts
        └── base.gohtml

Advantages 👍

Disadvantages 👎

If the resources are compressable—e.g. most plain text files are—then a binary packer like upx can reduce the file size dramatically:

$ upx -o notes.upx notes
$ du -sh notes notes.upx 
24M     notes
9.7M    notes.upx

Available Implementations

It’s Time for Yet Another File Embedding Tool

Design

Usage

NAME:
   embed - A new cli application

USAGE:
   embed [global options] command [command options] [arguments...]

VERSION:
   unset

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --package value, -p value                    name of the package the generated Go file is associated to (default: "main")
   --destination value, --dest value, -d value  where to store the generated Go file (default: "embeds.go")
   --include value, -i value                    paths to embed, directories are stored recursively (can be used multiple times)
   --help, -h                                   show help (default: false)
   --version, -v                                print the version (default: false)

Draft for Embedded Static Files

The draft—published by Russ Cox and Brad Fitzpatrick in July—identified the following problems with the current situation:

Adding support for file embedding to the go command will eliminate those problems.

Proposed changes:

Here’s an example for the embed directive:

// content holds our static web server content.
//go:embed image/* template/*
//go:embed html/index.html
var content embed.Files

The draft also contains various considerations regarding:

Still curious?