rice

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2022 License: BSD-2-Clause Imports: 16 Imported by: 1,427

README

go.rice

Build Status Godoc

go.rice is a Go package that makes working with resources such as html,js,css,images and templates easy. During development go.rice will load required files directly from disk. Upon deployment it's easy to add all resource files to a executable using the rice tool, without changing the source code for your package. go.rice provides methods to add resources to a binary in different scenarios.

What does it do

The first thing go.rice does is finding the correct absolute path for your resource files. Say you are executing a binary in your home directory, but your html-files are in $GOPATH/src/yourApplication/html-files. go.rice will lookup the correct path for that directory (relative to the location of yourApplication). All you have to do is include the resources using rice.FindBox("html-files").

This works fine when the source is available to the machine executing the binary, which is the case when installing the executable with go get or go install. But it does not work when you wish to provide a single binary without source. This is where the rice tool comes in. It analyses source code and finds call's to rice.FindBox(..). Then it adds the required directories to the executable binary, There are two strategies to do this. You can 'embed' the assets by generating go source code and then compile them into the executable binary, or you can 'append' the assets to the executable binary after compiling. In both cases the rice.FindBox(..) call detects the embedded or appended resources and load those, instead of looking up files from disk.

Installation

Use go get to install the package the rice tool.

go get github.com/GeertJohan/go.rice
go get github.com/GeertJohan/go.rice/rice

Package usage

Import the package: import "github.com/GeertJohan/go.rice"

Serving a static content folder over HTTP with a rice Box:

http.Handle("/", http.FileServer(rice.MustFindBox("http-files").HTTPBox()))
http.ListenAndServe(":8080", nil)

Serve a static content folder over HTTP at a non-root location:

box := rice.MustFindBox("cssfiles")
cssFileServer := http.StripPrefix("/css/", http.FileServer(box.HTTPBox()))
http.Handle("/css/", cssFileServer)
http.ListenAndServe(":8080", nil)

Note the trailing slash in /css/ in both the call to http.StripPrefix and http.Handle.

Loading a template:

// find a rice.Box
templateBox, err := rice.FindBox("example-templates")
if err != nil {
	log.Fatal(err)
}
// get file contents as string
templateString, err := templateBox.String("message.tmpl")
if err != nil {
	log.Fatal(err)
}
// parse and execute the template
tmplMessage, err := template.New("message").Parse(templateString)
if err != nil {
	log.Fatal(err)
}
tmplMessage.Execute(os.Stdout, map[string]string{"Message": "Hello, world!"})

Never call FindBox() or MustFindBox() from an init() function, as there is no guarantee the boxes are loaded at that time.

Calling FindBox and MustFindBox

Always call FindBox() or MustFindBox() with string literals e.g. FindBox("example"). Do not use string constants or variables. This will prevent the rice tool to fail with error Error: found call to rice.FindBox, but argument must be a string literal..

Tool usage

The rice tool lets you add the resources to a binary executable so the files are not loaded from the filesystem anymore. This creates a 'standalone' executable. There are multiple strategies to add the resources and assets to a binary, each has pro's and con's but all will work without requiring changes to the way you load the resources.

rice embed-go: Embed resources by generating Go source code

Execute this method before building. It generates a single Go source file called rice-box.go for each package. The generated go file contains all assets. The Go tool compiles this into the binary.

The downside with this option is that the generated go source file can become large, which may slow down compilation and requires more memory to compile.

Execute the following commands:

rice embed-go
go build

A Note on Symbolic Links: embed-go uses the os.Walk function from the standard library. The os.Walk function does not follow symbolic links. When creating a box, be aware that any symbolic links inside your box's directory are not followed. When the box itself is a symbolic link, the rice tool resolves its actual location before adding the contents.

rice append: Append resources to executable as zip file

This method changes an already built executable. It appends the resources as zip file to the binary. It makes compilation a lot faster. Using the append method works great for adding large assets to an executable binary.

A downside for appending is that it does not provide a working Seek method.

Run the following commands to create a standalone executable.

go build -o example
rice append --exec example

Help information

Run rice --help for information about all flags and subcommands.

You can use the --help flag on each sub-command. For example: rice append --help.

Order of precedence

When opening a new box, the rice.FindBox(..) tries to locate the resources in the following order:

  • embedded (generated as rice-box.go)
  • appended (appended to the binary executable after compiling)
  • 'live' from filesystem

License

This project is licensed under a Simplified BSD license. Please read the LICENSE file.

Package documentation

You will find package documentation at godoc.org/github.com/GeertJohan/go.rice.

Documentation

Index

Constants

View Source
const (
	LocateFS               = LocateMethod(iota) // Locate on the filesystem according to package path.
	LocateAppended                              // Locate boxes appended to the executable.
	LocateEmbedded                              // Locate embedded boxes.
	LocateWorkingDirectory                      // Locate on the binary working directory
)

Variables

View Source
var Debug = false

Debug can be set to true to enable debugging.

Functions

This section is empty.

Types

type Box

type Box struct {
	// contains filtered or unexported fields
}

Box abstracts a directory for resources/files. It can either load files from disk, or from embedded code (when `rice --embed` was ran).

func FindBox

func FindBox(name string) (*Box, error)

FindBox returns a Box instance for given name. When the given name is a relative path, it's base path will be the calling pkg/cmd's source root. When the given name is absolute, it's absolute. derp. Make sure the path doesn't contain any sensitive information as it might be placed into generated go source (embedded).

func MustFindBox

func MustFindBox(name string) *Box

MustFindBox returns a Box instance for given name, like FindBox does. It does not return an error, instead it panics when an error occurs.

func (*Box) Bytes

func (b *Box) Bytes(name string) ([]byte, error)

Bytes returns the content of the file with given name as []byte.

func (*Box) HTTPBox

func (b *Box) HTTPBox() *HTTPBox

HTTPBox creates a new HTTPBox from an existing Box

func (*Box) IsAppended

func (b *Box) IsAppended() bool

IsAppended indicates wether this box was appended to the application

func (*Box) IsEmbedded

func (b *Box) IsEmbedded() bool

IsEmbedded indicates wether this box was embedded into the application

func (*Box) MustBytes

func (b *Box) MustBytes(name string) []byte

MustBytes returns the content of the file with given name as []byte. panic's on error.

func (*Box) MustString

func (b *Box) MustString(name string) string

MustString returns the content of the file with given name as string. panic's on error.

func (*Box) Name

func (b *Box) Name() string

Name returns the name of the box

func (*Box) Open

func (b *Box) Open(name string) (*File, error)

Open opens a File from the box If there is an error, it will be of type *os.PathError.

func (*Box) String

func (b *Box) String(name string) (string, error)

String returns the content of the file with given name as string.

func (*Box) Time

func (b *Box) Time() time.Time

Time returns how actual the box is. When the box is embedded, it's value is saved in the embedding code. When the box is live, this methods returns time.Now()

func (*Box) Walk

func (b *Box) Walk(path string, walkFn filepath.WalkFunc) error

Walk is like filepath.Walk() Visit http://golang.org/pkg/path/filepath/#Walk for more information

type Config

type Config struct {
	// LocateOrder defines the priority order that boxes are searched for. By
	// default, the package global FindBox searches for embedded boxes first,
	// then appended boxes, and then finally boxes on the filesystem.  That
	// search order may be customized by provided the ordered list here. Leaving
	// out a particular method will omit that from the search space. For
	// example, []LocateMethod{LocateEmbedded, LocateAppended} will never search
	// the filesystem for boxes.
	LocateOrder []LocateMethod
}

Config allows customizing the box lookup behavior.

func (*Config) FindBox

func (c *Config) FindBox(boxName string) (*Box, error)

FindBox searches for boxes using the LocateOrder of the config.

func (*Config) MustFindBox

func (c *Config) MustFindBox(boxName string) *Box

MustFindBox searches for boxes using the LocateOrder of the config, like FindBox does. It does not return an error, instead it panics when an error occurs.

type File

type File struct {
	// contains filtered or unexported fields
}

File implements the io.Reader, io.Seeker, io.Closer and http.File interfaces

func (*File) Close

func (f *File) Close() error

Close is like (*os.File).Close() Visit http://golang.org/pkg/os/#File.Close for more information

func (*File) Read

func (f *File) Read(bts []byte) (int, error)

Read is like (*os.File).Read() Visit http://golang.org/pkg/os/#File.Read for more information

func (*File) Readdir

func (f *File) Readdir(count int) ([]os.FileInfo, error)

Readdir is like (*os.File).Readdir() Visit http://golang.org/pkg/os/#File.Readdir for more information

func (*File) Readdirnames

func (f *File) Readdirnames(count int) ([]string, error)

Readdirnames is like (*os.File).Readdirnames() Visit http://golang.org/pkg/os/#File.Readdirnames for more information

func (*File) Seek

func (f *File) Seek(offset int64, whence int) (int64, error)

Seek is like (*os.File).Seek() Visit http://golang.org/pkg/os/#File.Seek for more information

func (*File) Stat

func (f *File) Stat() (os.FileInfo, error)

Stat is like (*os.File).Stat() Visit http://golang.org/pkg/os/#File.Stat for more information

type HTTPBox

type HTTPBox struct {
	*Box
}

HTTPBox implements http.FileSystem which allows the use of Box with a http.FileServer.

e.g.: http.Handle("/", http.FileServer(rice.MustFindBox("http-files").HTTPBox()))

func (*HTTPBox) Open

func (hb *HTTPBox) Open(name string) (http.File, error)

Open returns a File using the http.File interface

type LocateMethod

type LocateMethod int

LocateMethod defines how a box is located.

type SortByModified

type SortByModified []os.FileInfo

SortByModified allows an array of os.FileInfo objects to be easily sorted by modified date using sort.Sort(SortByModified(array))

func (SortByModified) Len

func (f SortByModified) Len() int

func (SortByModified) Less

func (f SortByModified) Less(i, j int) bool

func (SortByModified) Swap

func (f SortByModified) Swap(i, j int)

type SortByName

type SortByName []os.FileInfo

SortByName allows an array of os.FileInfo objects to be easily sorted by filename using sort.Sort(SortByName(array))

func (SortByName) Len

func (f SortByName) Len() int

func (SortByName) Less

func (f SortByName) Less(i, j int) bool

func (SortByName) Swap

func (f SortByName) Swap(i, j int)

Directories

Path Synopsis
Package embedded defines embedded data types that are shared between the go.rice package and generated code.
Package embedded defines embedded data types that are shared between the go.rice package and generated code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL