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

vfsgen

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.

Features:

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

Installation

go get -u github.com/shurcooL/vfsgen

Usage

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 {
	log.Fatalln(err)
}

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 (
	"log"

	"example.com/project/data"
	"github.com/shurcooL/vfsgen"
)

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

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.
	NotWorthGzipCompressing()
}

Comparison

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.

Alternatives

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

Attribution

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

License

Comments
  • 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.

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

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

  • 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

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

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

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

  • 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:

    /static
     +- 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.

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

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

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

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

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

  • 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:

    mypackage/
      .air.toml
      cmd/
        example/
          main.go
          resources/
            generate.go
            asset.go
            templates/
              index.go.html
              login.go.html
    

    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.

  • 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?

    Why?

    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
    
  • 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:).

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

:file_folder: Embeds static resources into go files for single binary compilation + works with http.FileSystem + symlinks

Package statics Package statics embeds static files into your go applications. It provides helper methods and objects to retrieve embeded files and se

Sep 27, 2022
Generates go code to embed resource files into your library or executable

Deprecating Notice go is now going to officially support embedding files. The go command will support //go:embed tags. Go Embed Generates go code to e

Jun 2, 2021
A tool to be used with 'go generate' to embed external template files into Go code.

templify A tool to be used with 'go generate' to embed external template files into Go code. Scenario An often used scenario in developing go applicat

Sep 27, 2022
The simple and easy way to embed static files into Go binaries.

NOTICE: Please consider migrating your projects to github.com/markbates/pkger. It has an idiomatic API, minimal dependencies, a stronger test suite (t

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

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

Dec 18, 2022
Advent of Code Input Loader, provide a session cookie and a problem date, returns a string or []byte of the input

Advent of Code Get (aocget) A small lib to download your puzzle input for a given day. Uses your session token to authenticate to obtain your personal

Dec 9, 2021
DSV Parallel Processor takes input files and query specification via a spec file

DSV Parallel Processor Spec file DSV Parallel Processor takes input files and query specification via a spec file (conventionally named "spec.toml").

Oct 9, 2021
A simple javascript website that takes user input, queries a Go based backend which then creates ascii art and sends it back to the frontend

A simple javascript website that takes user input, queries a Go based backend which then creates ascii art and sends it back to the frontend. Finally the site displays the ascii art and offers the option to download as multiple file types.

Jan 7, 2022
Service that calls uzma24/project1 service, takes input from .txt file and prints JSON output returned from the service.

Service that calls uzma24/project1 service, takes input from .txt file and prints JSON output returned from the service. Program can take large input files.

Feb 6, 2022
Read from standard input and output a Haags translation of the given input.

haags Read from standard input and output a Haags translation of the given input. Building make && sudo make install You may also run go build on syst

Oct 23, 2022
Code generator that generates boilerplate code for a go http server

http-bootstrapper This is a code generator that uses go templates to generate a bootstrap code for a go http server. Usage Generate go http server cod

Nov 20, 2021
A ocilloscope writen in GO. Supported serial input, portaudio input.

A ocilloscope writen in GO. Supported serial input, portaudio input.

Oct 23, 2021
Benthos-input-grpc - gRPC custom benthos input

gRPC custom benthos input Create a custom benthos input that receives messages f

Sep 26, 2022
dfg - Generates dockerfiles based on various input channels.

dfg - Dockerfile Generator dfg is both a go library and an executable that produces valid Dockerfiles using various input channels. Table of Contents

Dec 23, 2022
Binaryscarf generates double-knitting patterns for some corpus of input text.

binaryscarf binaryscarf generates double-knit patterns for some corpus of input text. The layout follows the same style as described here. Output is s

Dec 31, 2022
Generates random text based on trigrams generated from input text
Generates random text based on trigrams generated from input text

Trigrams Generates random text based on trigrams generated from input text Contents Building Running Using Implementation notes NGram size Maximum wor

Feb 9, 2022
ReverseSSH - a statically-linked ssh server with reverse shell functionality for CTFs and such
 ReverseSSH - a statically-linked ssh server with reverse shell functionality for CTFs and such

ReverseSSH A statically-linked ssh server with a reverse connection feature for simple yet powerful remote access. Most useful during HackTheBox chall

Jan 5, 2023
Operator Permissions Advisor is a CLI tool that will take a catalog image and statically parse it to determine what permissions an Operator will request of OLM during an install

Operator Permissions Advisor is a CLI tool that will take a catalog image and statically parse it to determine what permissions an Operator will request of OLM during an install. The permissions are aggregated from the following sources:

Apr 22, 2022
⛵ EdgeVPN: the immutable, decentralized, statically built VPN. NO central server!

⛵ EdgeVPN Fully Decentralized. Immutable. Portable. Easy to use Statically compiled VPN Usage Generate a config: ./edgevpn -g > config.yaml Run it on

Jan 3, 2023
Simple API that returns JSON of statically defined

GOLANG API This is a simple example of a Go API using: Docker Docker-compose Built in go packages How to run using Docker-compose (Easiest) Clone repo

Nov 2, 2021