Generates go code to embed resource files into your library or executable

Overview

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!

You might also like...
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

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.

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

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

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

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

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

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

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

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

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

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

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

πŸ“¦ 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

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

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

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/

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

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

erchive is a go program that compresses and encrypts files and entire directories into .zep files (encrypted zip files).

erchive/zep erchive is a go program that compresses and encrypts files and entire directories into .zep files (encrypted zip files). it compresses usi

Releases(1.1.1)
Owner
Peter
@EqualExperts(@iowna, @zeta, @lifebox-healthcare), previous @unbarrier, @playlyfe
Peter
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

Michael Wolber 28 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

Buffalo - The Go Web Eco-System 3.4k Nov 16, 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

null 619 Oct 28, 2022
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

Aletheia 525 Nov 20, 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

null 949 Nov 16, 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

Go Playgound 65 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

null 60 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

Jaana Dogan 3.5k Nov 26, 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

Jaana Dogan 3.5k Nov 21, 2022
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

Lea Anthony 22 Sep 27, 2022