Takes an input http.FileSystem (likely at go generate time) and generates Go code that statically implements it.



Build Status GoDoc

Package vfsgen takes an http.FileSystem (likely at go generate time) and generates Go code that statically implements the provided http.FileSystem.


  • Efficient generated code without unneccessary overhead.

  • Uses gzip compression internally (selectively, only for files that compress well).

  • Enables direct access to internal gzip compressed bytes via an optional interface.

  • Outputs gofmted Go code.


go get -u github.com/shurcooL/vfsgen


Package vfsgen is a Go code generator library. It has a Generate function that takes an input filesystem (as a http.FileSystem type), and generates a Go code file that statically implements the contents of the input filesystem.

For example, we can use http.Dir as a http.FileSystem implementation that uses the contents of the /path/to/assets directory:

var fs http.FileSystem = http.Dir("/path/to/assets")

Now, when you execute the following code:

err := vfsgen.Generate(fs, vfsgen.Options{})
if err != nil {

An assets_vfsdata.go file will be generated in the current directory:

// Code generated by vfsgen; DO NOT EDIT.

package main

import ...

// assets statically implements the virtual filesystem provided to vfsgen.Generate.
var assets http.FileSystem = ...

Then, in your program, you can use assets as any other http.FileSystem, for example:

file, err := assets.Open("/some/file.txt")
if err != nil {
	return err
defer file.Close()
http.Handle("/assets/", http.FileServer(assets))

vfsgen can be more useful when combined with build tags and go generate directives. This is described below.

go generate Usage

vfsgen is great to use with go generate directives. The code invoking vfsgen.Generate can go in an assets_generate.go file, which can then be invoked via "//go:generate go run assets_generate.go". The input virtual filesystem can read directly from disk, or it can be more involved.

By using build tags, you can create a development mode where assets are loaded directly from disk via http.Dir, but then statically implemented for final releases.

For example, suppose your source filesystem is defined in a package with import path "example.com/project/data" as:

// +build dev

package data

import "net/http"

// Assets contains project assets.
var Assets http.FileSystem = http.Dir("assets")

When built with the "dev" build tag, accessing data.Assets will read from disk directly via http.Dir.

A generate helper file assets_generate.go can be invoked via "//go:generate go run -tags=dev assets_generate.go" directive:

// +build ignore

package main

import (


func main() {
	err := vfsgen.Generate(data.Assets, vfsgen.Options{
		PackageName:  "data",
		BuildTags:    "!dev",
		VariableName: "Assets",
	if err != nil {

Note that "dev" build tag is used to access the source filesystem, and the output file will contain "!dev" build tag. That way, the statically implemented version will be used during normal builds and go get, when custom builds tags are not specified.

vfsgendev Usage

vfsgendev is a binary that can be used to replace the need for the assets_generate.go file.

Make sure it's installed and available in your PATH.

go get -u github.com/shurcooL/vfsgen/cmd/vfsgendev

Then the "//go:generate go run -tags=dev assets_generate.go" directive can be replaced with:

//go:generate vfsgendev -source="example.com/project/data".Assets

vfsgendev accesses the source variable using "dev" build tag, and generates an output file with "!dev" build tag.

Additional Embedded Information

All compressed files implement httpgzip.GzipByter interface for efficient direct access to the internal compressed bytes:

// GzipByter is implemented by compressed files for
// efficient direct access to the internal compressed bytes.
type GzipByter interface {
	// GzipBytes returns gzip compressed contents of the file.
	GzipBytes() []byte

Files that have been determined to not be worth gzip compressing (their compressed size is larger than original) implement httpgzip.NotWorthGzipCompressing interface:

// NotWorthGzipCompressing is implemented by files that were determined
// not to be worth gzip compressing (the file size did not decrease as a result).
type NotWorthGzipCompressing interface {
	// NotWorthGzipCompressing is a noop. It's implemented in order to indicate
	// the file is not worth gzip compressing.


vfsgen aims to be conceptually simple to use. The http.FileSystem abstraction is central to vfsgen. It's used as both input for code generation, and as output in the generated code.

That enables great flexibility through orthogonality, since helpers and wrappers can operate on http.FileSystem without knowing about vfsgen. If you want, you can perform pre-processing, minifying assets, merging folders, filtering out files and otherwise modifying input via generic http.FileSystem middleware.

It avoids unneccessary overhead by merging what was previously done with two distinct packages into a single package.

It strives to be the best in its class in terms of code quality and efficiency of generated code. However, if your use goals are different, there are other similar packages that may fit your needs better.


  • go-bindata - Reads from disk, generates Go code that provides access to data via a custom API.
  • go-bindata-assetfs - Takes output of go-bindata and provides a wrapper that implements http.FileSystem interface (the same as what vfsgen outputs directly).
  • becky - Embeds assets as string literals in Go source.
  • statik - Embeds a directory of static files to be accessed via http.FileSystem interface (sounds very similar to vfsgen); implementation sourced from camlistore.
  • go.rice - Makes working with resources such as HTML, JS, CSS, images and templates very easy.
  • esc - Embeds files into Go programs and provides http.FileSystem interfaces to them.
  • staticfiles - Allows you to embed a directory of files into your Go binary.
  • togo - Generates a Go source file with a []byte var containing the given file's contents.
  • fileb0x - Simple customizable tool to embed files in Go.
  • embedfiles - Simple tool for embedding files in Go code as a map.
  • packr - Simple solution for bundling static assets inside of Go binaries.
  • rsrc - Tool for embedding .ico & manifest resources in Go programs for Windows.


This package was originally based on the excellent work by @jteeuwen on go-bindata and @elazarl on go-bindata-assetfs.


  • Add a command-line version of vfsgen

    Add a command-line version of vfsgen

    • Inclusive of the change at https://github.com/shurcooL/vfsgen/pull/13 (should merge #13 before this one).
    • Also depends on the change at https://github.com/shurcooL/httpfs/pull/1
    • Fixes #2.

    See docs in main.go for usage examples / general idea of how it works.

    opened by slimsag 9
  • Add ForceAllTypes to Options

    Add ForceAllTypes to Options

    Adds a ForceAllTypes member to Options, forcing the generation of both the vfsgen۰CompressedFileInfo and vfsgen۰FileInfo types. Useful for other using packages that need to ensure that both types are present.

    opened by kenshaw 8
  • vfsgendev: look up source in the current module

    vfsgendev: look up source in the current module

    Currently vfsgendev only considers GOROOT and GOPATH when looking up the source to use. This does not work as expected when running vfsgendev within a go module, as introduced in Go 1.11.

    Specifying the current directory (.) as the source directory for build.Import(), allows the module logic to work when running inside a go module.

    opened by antong 6
  • Add ./cmd/vfsgendev binary to address common use case.

    Add ./cmd/vfsgendev binary to address common use case.

    Add an opinionated binary for specialized use. It uses the convention of using "dev" build tag for development mode, and assumes that the source VFS is defined in a "dev" only environment; it uses "!dev" build tag in output _vfsdata.go file.

    Usage is simple:

    $ vfsgendev -source="import/path".VariableName

    Or in a go:generate directive:

    //go:generate vfsgendev -source="import/path".VariableName

    See sourcegraph/appdash#91 for additional background, motivation, and discussion.

    Resolves #2.

    Closes #14.

    /cc @slimsag

    opened by dmitshur 6
  • Make the VariableName option default to being exported.

    Make the VariableName option default to being exported.

    This change makes the VariableName default to the exported Assets instead of the previously unexported assets. The rational for this is that people creating Go packages will not have to specify a VariableName parameter at all because it will default to being exported. For creators of main packages, they cannot be imported anyway so keeping the field private by default is less valuable.

    opened by slimsag 6
  • README: Add Alternatives and Comparison sections.

    README: Add Alternatives and Comparison sections.

    I've gotten this idea from someone on Twitter (I couldn't find the exact tweet, sadly). It went something like this:

    From now on, all my Go library READMEs will include an Alternatives section!

    I think it's a great idea for the following reasons:

    • This is good for users because they can either be more confident that vfsgen is the best choice for them, or if their needs are different, find a more well-suited package.
    • It's good for vfsgen because it communicates to users more clearly that it is indeed similar to some other existing packages.
    • It's good for alternative packages listed because they get free advertisement and exposure.
    • It's good for everyone because it can help reduce duplication of effort if something can be consolidated, and improved code quality and functionality due to competition. :)

    A great example of 2 packages that already do this is:

    • https://github.com/dchest/htmlmin#alternatives - A simple HTML minifier.
    • https://github.com/tdewolff/minify#alternatives - A more complete, heavyweight solution for minifying HTML, CSS, JS, JSON, SVG, XML.

    I am including some alternative/similar Go libraries that I am aware of. Most of them differ in scope or preferred API for input/output to various degrees.

    /cc @jteeuwen @elazarl @tv42 @rakyll @GeertJohan I mentioned your packages in the alternatives section, please let me know if you have a problem with that and would want me to edit it or remove your package, I will gladly do that.

    Motivation to create vfsgen

    I originally made vfsgen after using go-bindata+go-bindata-assetfs for a while but they suffered from https://github.com/jteeuwen/go-bindata/issues/22, https://github.com/elazarl/go-bindata-assetfs/issues/24 and I saw no way to resolve those issues easily without changing the interface significantly (see my proposal for fork here).

    I also wanted to have the freedom to experiment without being tied to a stable API and see what the best solution in this space is. And I wanted to simplify the code a lot, because I saw a lot of opportunities for that in the original codebases.

    I'm very happy with where vfsgen ended up and it enabled me to do things I couldn't otherwise (e.g., see https://github.com/shurcooL/Go-Package-Store/pull/18#issuecomment-120696770). It's useful to me, and I hope it'll be useful to more people who have similar needs. Together with the alternative packages, this problem space in Go has great coverage now.

    opened by dmitshur 6
  • Use more readable internal naming scheme.

    Use more readable internal naming scheme.

    The original motivation for using the ugly and non-idiomatic _vfsgen_ prefix for all generated internal types was to ensure no possibility of having a name collision with the user's own code. For example, if user had a type FileInfo, and vfsgen tried to generate FileInfo as well, that'd be a compile time error.

    By starting all identifiers with an underscore – something no manually written idiomatic Go code would do – we ensured no collisions.

    The idea here is to use a more readable alternative way of achieving the same goal. Since we're using a hard-to-type unicode character, it's unlikely people would write that by hand, so name collisions are still unlikely.

    That little dot ۰ is an Arabic zero numeral (U+06F0), categories [Nd].

    This idea is inspired by internal code of golang.org/x/tools/go/ssa/interp package. See https://github.com/golang/tools/blob/86ad1193da6aba71355e71191641b9cfb26daa67/go/ssa/interp/external.go#L36.

    opened by dmitshur 5
  • Add include/exclude options

    Add include/exclude options

    I added this to allow me to place .go files in the root directory of my assets folder:

     +- doc.go (mimics https://github.com/shurcooL/home/blob/master/assets/doc.go)
     +- static.go (mimics https://github.com/shurcooL/home/blob/master/assets/assets.go)
     +- assets_vfsdata.go
     |- /css 
     |  |...
     +- /js

    If you approve of this PR, let me know if you want me to add these new options to https://github.com/shurcooL/vfsgen/blob/master/cmd/vfsgendev/generate.go, etc. in this PR, or create a new one.

    opened by rasa 3
  • How can I access template files in assets_vfsdata.go

    How can I access template files in assets_vfsdata.go

    Hi, @shurcooL , this is a great package and its quite handy. I met a problem and did some research and still can't figure out by myself because I am a newbie of golang.

    I have a file called index.templ which has already saved in assets_vfsdata.go, and there are also included many js and css files.

    http.Handle("/", http.StripPrefix("/", fs)) uesed to satisfy my most requirements, but now I write some templates for my html pages, then I have no idea how to return a html page to http server after parsing my template and data.

    It seems I have to retrieve the compressedContent in the map and replace it by using template.New("").Parse() before start http server.(this may not right)

    So, is there a easier(or right) way to access partial template files and make them works like template.ParseFiles("./index.templ").

    Thanks for the help.

    opened by weiofcn 3
  • Support atomic writes

    Support atomic writes

    Generate() creates a file and then writes chunks to it. This can lead to a situation where someone attempts to compile or run the file if it's only half written.

    It would be better to write the file in chunks to a temporary directory and then atomically copy it into place; that way you either get the old file or the new file but not both.

    In addition it would probably be useful to wrap the writer in a bufio.NewWriter to avoid a sequence of small writes.

    opened by kevinburke 3
  • Mimic http.Dir behavior and clean path in Open.

    Mimic http.Dir behavior and clean path in Open.

    This change makes the generated VFS compatible in behavior with http.Dir.

    • Behaves more in line with os.Open and http.Dir.Open.
    • Allows unclean paths like "/folder/../file.txt" to resolve.
    • Allows relative paths like "file.txt" to work. But the canonical paths remain absolute like "/file.txt".

    Resolves #10.

    opened by dmitshur 3
  • Add UseGlobalModTime option to make application reproducible

    Add UseGlobalModTime option to make application reproducible

    This PR adds a new option named UseGlobalModTime to not store file or dir time into the generated files so that application builds could be reproducible.

    The default value of UseGlobalModTime is false. Then anything is not changed. When set UseGlobalModTime as true, a function named GlobalModTime(filename string) time.Time will be called from the generated files. So you could define that function in the same package of the generated files.

    opened by lunny 0
  • evaluate future direction after Go 1.16 changes

    evaluate future direction after Go 1.16 changes

    vfsgen was created to fill in a gap in the ability to embed files in Go programs, and uses net/http.FileSystem as the central filesystem interface.

    Go 1.16 will add //go:embed and io/fs.FS.

    This issue is to determine whether a vfsgen v2 should be made that makes use of the new Go 1.16 features, or if there isn't a need for vfsgen v2 because the Go 1.16 features on their own are sufficient for use cases that vfsgen is used for.

    What's clear is that vfsgen v0 (the current version) should be v1 and its API should not change.

    opened by dmitshur 0
  • Feature Request: path to generate file

    Feature Request: path to generate file

    I am writing a library that has a subpackage, which needs to have assets generated. The folder structure looks like this:


    Here are my constrains:

    1. The asset.go file contains my development http.FileSystem declaration. The generate.go contains the development only main package that generates the code.
    2. I want to generate asset_vfsdata.go in the same folder as asset.go.
    3. I want to use air to live reload asset_vfsdata.go. So ideally I want to run the generate.go command at the root folder.

    My problem is this: if I run the generate.go at the root folder (mypackage), the generated go file will be placed directly at root, which fails to achieve (2). I tried adding path to vfsgen.Options.Filename, but it seems to be ignored by vfsgen.

    I think the clean to do it is to have a vfsgen.Options that specifies the relative output folder somehow.

    opened by yookoala 1
  • Symlink & File Permission Support?

    Symlink & File Permission Support?

    It appears that the default behavior is to strip the Mode and file permission bits and to read symlink targets rather than to save the path as the contents.

    I suppose this could be circumvented by first running tar and then running vfsgen, or running some other process to save the metadata and zipping it together later.

    I couldn't find any issues or docs about either symlinks or file permissions.

    Is this explicitly not a goal of the project? Or just an oversight?


    I'm working on a project that has an init subcommand which generates project files, including a .env.

    # initializes .env and the ./scripts/ directory
    gitdeploy init
    # run with the default configuration
    gitdeploy run
    opened by coolaj86 1
  • Add option to generate a function rather than global variable

    Add option to generate a function rather than global variable

    It would be great to have another field in Options struct called FunctionName, which would generate a function returning http.FileSystem, rather than a function assigned to global variable, as globals are magic and should not be used whenever possible (though a function in global is not that bad :smile:).

    opened by invidian 4
  • Generation of assets fails with GOOS=freebsd

    Generation of assets fails with GOOS=freebsd

    When generating contents prior to building for freebsd, generation fails with a segfault:

    I'm executing the generate step as a dependency of the build step, therefore the env variables are also set for the generate step. The behaviour is the same when I run GOOS=freebsd GOARCH=amd64 go generate code.vikunja.io/api/pkg/static directly.

    $ GOOS=freebsd GOARCH=amd64 make build
    go generate code.vikunja.io/api/pkg/static
    signal: segmentation fault (core dumped)
    pkg/static/static.go:17: running "go": exit status 1
    make: *** [Makefile:105: generate] Error 1

    The code is here.

    If I generate the assets for my own platform (linux) and run the build with all env set for freebsd, it seems to work, but only if I don't run the generate step.

    I'm not sure if this is an issue with vfsgen or some other part of the go toolchain. It is imho not critical since the workaround with running the generate step first and only then setting the env variables for freebsd when compiling the binary is an okay-ish workaround. I only happend to stuble upon this because of the way my makefile is set up.

    opened by kolaente 2
A set of io/fs filesystem abstractions and utilities for Go

A set of io/fs filesystem abstractions and utilities for Go Please ⭐ this project Overview This package provides io/fs interfaces for: Cloud providers

null 10 Nov 19, 2022
Grep archive search in any files on the filesystem, in archive and even inner archive.

grep-archive Grep archive search for string in any files on the filesystem, in archive and even inner archive. Supported archive format are : Tar Form

Michel Prunet 0 Jan 26, 2022
s3fs provides a S3 implementation for Go1.16 filesystem interface.

S3 FileSystem (fs.FS) implementation.Since S3 is a flat structure, s3fs simulates directories by using prefixes and "/" delim. ModTime on directories is always zero value.

Jacek Szwec 147 Nov 9, 2022
A FileSystem Abstraction System for Go

A FileSystem Abstraction System for Go Overview Afero is a filesystem framework providing a simple, uniform and universal API interacting with any fil

Steve Francia 4.9k Jan 9, 2023
A package to allow one to concurrently go through a filesystem with ease

skywalker Skywalker is a package to allow one to concurrently go through a filesystem with ease. Features Concurrency BlackList filtering WhiteList fi

Will Dixon 87 Nov 14, 2022
An implementation of the FileSystem interface for tar files.

TarFS A wrapper around tar.Reader. Implements the FileSystem interface for tar files. Adds an Open method, that enables reading of file according to i

Eyal Posener 51 Sep 26, 2022
memfs: A simple in-memory io/fs.FS filesystem

memfs: A simple in-memory io/fs.FS filesystem memfs is an in-memory implementation of Go's io/fs.FS interface. The goal is to make it easy and quick t

Peter Sanford 79 Jan 8, 2023
A Go io/fs filesystem implementation for reading files in a Github gists.

GistFS GistFS is an io/fs implementation that enables to read files stored in a given Gist. Requirements This module depends on io/fs which is only av

Jean Hadrien Chabran 126 Oct 14, 2022
A Small Virtual Filesystem in Go

This is a virtual filesystem I'm coding to teach myself Go in a fun way. I'm documenting it with a collection of Medium posts that you can find here.

Alyson 32 Dec 11, 2022
CRFS: Container Registry Filesystem

CRFS: Container Registry Filesystem Discussion: https://github.com/golang/go/issues/30829 Overview CRFS is a read-only FUSE filesystem that lets you m

Google 1.3k Dec 26, 2022
Encrypted overlay filesystem written in Go

An encrypted overlay filesystem written in Go. Official website: https://nuetzlich.net/gocryptfs (markdown source). gocryptfs is built on top the exce

null 2.6k Jan 8, 2023
Go filesystem implementations for various URL schemes

hairyhenderson/go-fsimpl This module contains a collection of Go filesystem implementations that can discovered dynamically by URL scheme. All filesys

Dave Henderson 238 Dec 28, 2022
filesystem for golang

filesystem filesystem for golang installation go get github.com/go-component/filesystem import import "github.com/go-component/filesystem" Usage sup

null 5 Nov 1, 2022
Tarserv serves streaming tar files from filesystem snapshots.

tarserv A collection of tools that allow serving large datasets from local filesystem snapshots. It is meant for serving big amounts of data to shell

Aurora 1 Jan 11, 2022
Warp across your filesystem in ~5 ms

WarpDrive: the Go version. What does this do? Instead of having a huge cd routine to get where you want, with WarpDrive you use short keywords to warp

Ishan Goel 17 Dec 14, 2022
A basic file server automatically generates self certificates and serves the given folder.

A basic file server automatically generates self certificates and serves the given folder.

Ahmet ÖZER 4 Jul 20, 2022
Package cae implements PHP-like Compression and Archive Extensions.

Compression and Archive Extensions 中文文档 Package cae implements PHP-like Compression and Archive Extensions. But this package has some modifications de

ᴜɴᴋɴᴡᴏɴ 36 Jun 16, 2022
Allows parsing CSV files into custom structs and implements required fields that can't be empty

Welcome to Go Custom CSV Parser ?? Allows parsing CSV files into custom structs and implements required fields that can't be empty ?? Homepage Install

Elmedin Turkeš 2 Nov 9, 2021
searchHIBP is a golang tool that implements binary search over a hash ordered binary file.

searchHIBP is a golang tool that implements binary search over a hash ordered binary file.

fblz 0 Nov 9, 2021