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 embed resource files into your library or executable. This is more suitable for web servers as it gzip compresses all the files automatically and computes the hash so that it can be used for caching the assets in the frontends.

go-embed v1.0.0
Generates go code to embed resource files into your library or executable

  Usage:
    -input  string  The path to the folder containing the assets
    -output string  The output filename

  example:
    go-embed -input public/ -output assets/main.go

You can use this to embed your css, js and images into a single executable.

This is similar to go-bindata.

This is similar to pony-embed.

This is similar to rust-embed.

Installation

go get github.com/pyros2097/go-embed

Documentation

You can directly access your files as constants from the assets package or you can use this func to serve all files stored in your assets folder which is useful for webservers and has gzip compression and hash creation for caching. Just see the example as to how same caching and compression works in production and development.

assets.IndexHTML // direct access
assets.Asset(base, path) (data, hash, contentType, error)

Examples

A simple http server which serves its resources directly.

Navigate to the example folder and run these commands,

To see it in action in development, go run main.go

To see it in action in production,

cd examples
go-embed -input public/ -output assets/main.go
go run main.go
git stash
git stash drop
package main

import (
  "net/http"

  "github.com/pyros2097/go-embed/examples/assets"
)

func main() {
  http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
    println("GET " + req.URL.Path)
    data, hash, contentType, err := assets.Asset("public/", req.URL.Path)
    if err != nil {
      data, hash, contentType, err = assets.Asset("public", "/index.html")
      if err != nil {
        data = []byte(err.Error())
      }
    }
    res.Header().Set("Content-Encoding", "gzip")
    res.Header().Set("Content-Type", contentType)
    res.Header().Add("Cache-Control", "public, max-age=31536000")
    res.Header().Add("ETag", hash)
    if req.Header.Get("If-None-Match") == hash {
      res.WriteHeader(http.StatusNotModified)
    } else {
      res.WriteHeader(http.StatusOK)
      _, err := res.Write(data)
      if err != nil {
        panic(err)
      }
    }
  })
  println("Server running on 127.0.0.1:3000")
  http.ListenAndServe(":3000", nil)
}

For development mode you can use this as a template file for running your server and loading the assets directly from the filesystem and in release this file would be rewritten by the go-embed tool to contain the actual file data and after you run your build command you might need to checkout this file again. This file can be safely committed to your git repository.

package assets

import (
  "bytes"
  "compress/gzip"
  "crypto/md5"
  "encoding/hex"
  "io/ioutil"
  "mime"
  "path/filepath"
)

func init() {
  mime.AddExtensionType(".ico", "image/x-icon")
  mime.AddExtensionType(".eot", "font/eot")
  mime.AddExtensionType(".tff", "font/tff")
  mime.AddExtensionType(".woff", "application/font-woff")
  mime.AddExtensionType(".woff2", "application/font-woff")
}

// Asset Gets the file from system if debug otherwise gets it from the stored
// data returns the data, the md5 hash of its content and its content type and
// and error if it is not found
// In production the base parameter is ignored
// use it for developement as the relativepath/to/your/public/folder
// ex: ui/myproject/src/public
func Asset(base, path string) ([]byte, string, string, error) {
  var b bytes.Buffer
  file := base + path
  data, err := ioutil.ReadFile(file)
  if err != nil {
    return nil, "", "", err
  }
  if data != nil {
    w := gzip.NewWriter(&b)
    w.Write(data)
    w.Close()
    data = b.Bytes()
  }
  sum := md5.Sum(data)
  return data, hex.EncodeToString(sum[1:]), mime.TypeByExtension(filepath.Ext(file)), nil
}

This is how I use it in my make file,

cd ui/$(Project) && npm install && npm run build
go-embed -input ui/$(Project)/src/public -output assets/main.go
go build -o $(Project) -tags '$(Project)' $(Project).go
git checkout assets/main.go

Go Gophers!

The power is yours!

Owner
Peter
@EqualExperts(@iowna, @zeta, @lifebox-healthcare), previous @unbarrier, @playlyfe
Peter
Similar Resources

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

Split multiple Kubernetes files into smaller files with ease. Split multi-YAML files into individual files.

Split multiple Kubernetes files into smaller files with ease. Split multi-YAML files into individual files.

Dec 29, 2022

Split multiple Kubernetes files into smaller files with ease. Split multi-YAML files into individual files.

kubectl-slice: split Kubernetes YAMLs into files kubectl-slice is a neat tool that allows you to split a single multi-YAML Kubernetes manifest into mu

Jan 3, 2023

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

a better customizable tool to embed files in go; also update embedded files remotely without restarting the server

fileb0x What is fileb0x? A better customizable tool to embed files in go. It is an alternative to go-bindata that have better features and organized c

Dec 27, 2022

Terraform Provider for Azure (Resource Manager)Terraform Provider for Azure (Resource Manager)

Terraform Provider for Azure (Resource Manager)Terraform Provider for Azure (Resource Manager)

Terraform Provider for Azure (Resource Manager) Version 2.x of the AzureRM Provider requires Terraform 0.12.x and later, but 1.0 is recommended. Terra

Oct 16, 2021

Fadvisor(FinOps Advisor) is a collection of exporters which collect cloud resource pricing and billing data guided by FinOps, insight cost allocation for containers and kubernetes resource

Fadvisor(FinOps Advisor) is a collection of exporters which collect cloud resource pricing and billing data guided by FinOps, insight cost allocation for containers and kubernetes resource

[TOC] Fadvisor: FinOps Advisor fadvisor(finops advisor) is used to solve the FinOps Observalibility, it can be integrated with Crane to help users to

Jan 3, 2023

Eos-resource-purchase-cal - Calculate eos resource fee with golang

eos-resource-purchase-cal calculate eos resource fee Info this rep complete eosi

Jan 20, 2022

Apachedist-resource - A concourse resource to track updates of an apache distribution, e.g. tomcat

Apache Distribution Resource A concourse resource that can track information abo

Feb 2, 2022

cluster-api-state-metrics (CASM) is a service that listens to the Kubernetes API server and generates metrics about the state of custom resource objects related of Kubernetes Cluster API.

Overview cluster-api-state-metrics (CASM) is a service that listens to the Kubernetes API server and generates metrics about the state of custom resou

Oct 27, 2022

📦 Package Node.js applications into executable binaries 📦

caxa 📦 Package Node.js applications into executable binaries 📦 Support Recurring support on Patreon: https://patreon.com/leafac One-time support on

Jan 6, 2023

donLoader is a shellcode loader creation tool that uses donut to convert executable payloads into shellcode to evade detection on disk.

donLoader WARNING: This is WIP, barely anything was tested properly. Use at your own risk. Description donLoader is a shellcode loader creation tool t

Sep 20, 2022

Ghostinthepdf - This is a small tool that helps to embed a PostScript file into a PDF

This is a small tool that helps to embed a PostScript file into a PDF in a way that GhostScript will run the PostScript code during the

Dec 20, 2022

This command line converts .html file into .html with images embed.

embed-html This command line converts .html file into .html with images embed. Install go get github.com/gonejack/embed-html Usage embed-html *.ht

Oct 6, 2022

Command line tool for adding Windows resources to executable files

go-winres A simple command line tool for embedding usual resources in Windows executables built with Go: A manifest An application icon Version inform

Dec 27, 2022

A quick and easy password protected web server for your files. httpfolder makes downloading/uploading files from your current working directory easy, even for fairly large files.

httpfolder A quick and easy password protected web server for your files. httpfolder makes downloading/uploading files from your current working direc

Sep 12, 2022

Using brotli compression to embed static files in Go.

Using brotli compression to embed static files in Go.

🥦 Broccoli go get -u aletheia.icu/broccoli Broccoli uses brotli compression to embed a virtual file system of static files inside Go executables. A f

Nov 25, 2022

Embed static files in Go binaries (replacement for gobuffalo/packr)

Pkger github.com/markbates/pkger is a tool for embedding static files into Go binaries. It will, hopefully, be a replacement for github.com/gobuffalo/

Dec 29, 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 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
a better customizable tool to embed files in go; also update embedded files remotely without restarting the server

fileb0x What is fileb0x? A better customizable tool to embed files in go. It is an alternative to go-bindata that have better features and organized c

Dec 27, 2022
Using brotli compression to embed static files in Go.
Using brotli compression to embed static files in Go.

?? Broccoli go get -u aletheia.icu/broccoli Broccoli uses brotli compression to embed a virtual file system of static files inside Go executables. A f

Nov 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
: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
Embed arbitrary resources into a go executable at runtime, after the executable has been built.

ember Ember is a lightweight library and tool for embedding arbitrary resources into a go executable at runtime. The resources don't need to exist at

Nov 9, 2022
Embed files into a Go executable

statik statik allows you to embed a directory of static files into your Go binary to be later served from an http.FileSystem. Is this a crazy idea? No

Dec 29, 2022
Embed files into a Go executable

statik statik allows you to embed a directory of static files into your Go binary to be later served from an http.FileSystem. Is this a crazy idea? No

Jan 6, 2023
Get an embed.FS from inside an embed.FS
Get an embed.FS from inside an embed.FS

embed.FS wrapper providing additional functionality Features Get an embed.FS from an embedded subdirectory Handy Copy(sourcePath, targetPath) method t

Sep 27, 2022