Movatterモバイル変換


[0]ホーム

URL:


packr

packagemodule
v2.8.3Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2021 License:MITImports:20Imported by:1,403

Details

Repository

github.com/gobuffalo/packr

Links

README

NOTICE: Please consider migrating your projects toembed which is native file embedding feature of Go,or github.com/markbates/pkger. It has an idiomatic API, minimal dependencies, a stronger test suite (tested directly against the std lib counterparts), transparent tooling, and more.

https://blog.gobuffalo.io/introducing-pkger-static-file-embedding-in-go-1ce76dc79c65

Packr (v2)

GoDocActions Status

Packr is a simple solution for bundling static assets inside of Go binaries. Most importantly it does it in a way that is friendly to developers while they are developing.

At this moment, supported go versions are:

  • 1.16.x
  • 1.17.x

even though it may (or may not) working well with older versions.

Intro Video

To get an idea of the what and why of Packr, please enjoy this short video:https://vimeo.com/219863271.

Library Installation

Go 1.16 and above
$ go install github.com/gobuffalo/packr/v2@v2.8.3

or

$ go install github.com/gobuffalo/packr/v2@latest
Go 1.15 and below
$ go get -u github.com/gobuffalo/packr/...

Binary Installation

Go 1.16 and above
$ go install github.com/gobuffalo/packr/v2/packr2@v2.8.3

or

$ go install github.com/gobuffalo/packr/v2/packr2@latest
Go 1.15 and below
$ go get -u github.com/gobuffalo/packr/packr2

New File Format FAQs

In versionv2.0.0 the file format changed and is not backward compatible with thepackr-v1.x library.

Canpackr-v1.x read the new format?

No, it can not. Because of the way the new file format works porting it topackr-v1.x would be difficult. PRs are welcome though. :)

Canpackr-v2.x readpackr-v1.x files?

Yes it can, but that ability will eventually be phased out. Because of that we recommend moving to the new format.

Canpackr-v2.x generatepackr-v1.x files?

Yes it can, but that ability will eventually be phased out. Because of that we recommend moving to the new format.

The--legacy command is available on all commands that generate-packr.go files.

$ packr2 --legacy

Usage

In Code

The first step in using Packr is to create a new box. A box represents a folder on disk. Once you have a box you can getstring or[]byte representations of the file.

// set up a new box by giving it a name and an optional (relative) path to a folder on disk:box := packr.New("My Box", "./templates")// Get the string representation of a file, or an error if it doesn't exist:html, err := box.FindString("index.html")// Get the []byte representation of a file, or an error if it doesn't exist:html, err := box.Find("index.html")
What is a Box?

A box represents a folder, and any sub-folders, on disk that you want to have access to in your binary. When compiling a binary using thepackr2 CLI the contents of the folder will be converted into Go files that can be compiled inside of a "standard" go binary. Inside of the compiled binary the files will be read from memory. When working locally the files will be read directly off of disk. This is a seamless switch that doesn't require any special attention on your part.

Example

Assume the follow directory structure:

├── main.go└── templates    ├── admin    │   └── index.html    └── index.html

The following program will read the./templates/admin/index.html file and print it out.

package mainimport (  "fmt"  "github.com/gobuffalo/packr/v2")func main() {  box := packr.New("myBox", "./templates")  s, err := box.FindString("admin/index.html")  if err != nil {    log.Fatal(err)  }  fmt.Println(s)}
Development Made Easy

In order to get static files into a Go binary, those files must first be converted to Go code. To do that, Packr, ships with a few tools to help build binaries. See below.

During development, however, it is painful to have to keep running a tool to compile those files.

Packr uses the following resolution rules when looking for a file:

  1. Look for the file in-memory (inside a Go binary)
  2. Look for the file on disk (during development)

Because Packr knows how to fall through to the file system, developers don't need to worry about constantly compiling their static files into a binary. They can work unimpeded.

Packr takes file resolution a step further. When declaring a new box you use a relative path,./templates. When Packr receives this call it calculates out the absolute path to that directory. By doing this it means you can be guaranteed that Packr can find your files correctly, even if you're not running in the directory that the box was created in. This helps with the problem of testing, where Go changes thepwd for each package, making relative paths difficult to work with. This is not a problem when using Packr.


Usage with HTTP

A box implements thehttp.FileSystem interface, meaning it can be used to serve static files.

package mainimport ("net/http""github.com/gobuffalo/packr/v2")func main() {box := packr.New("someBoxName", "./templates")http.Handle("/", http.FileServer(box))http.ListenAndServe(":3000", nil)}

Building a Binary

Before you build your Go binary, run thepackr2 command first. It will look for all the boxes in your code and then generate.go files that pack the static files into bytes that can be bundled into the Go binary.

$ packr2

Then run yourgo build command like normal.

NOTE: It is not recommended to check-in these generated-packr.go files. They can be large, and can easily become out of date if not careful. It is recommended that you always runpackr2 clean after running thepackr2 tool.

Cleaning Up

When you're done it is recommended that you run thepackr2 clean command. This will remove all of the generated files that Packr created for you.

$ packr2 clean

Why do you want to do this? Packr first looks to the information stored in these generated files, if the information isn't there it looks to disk. This makes it easy to work with in development.


Debugging

Thepackr2 command passes all arguments down to the underlyinggo command, this includes the-v flag to print outgo build information. Packr looks for the-v flag, and will turn on its own verbose logging. This is very useful for trying to understand what thepackr command is doing when it is run.


FAQ

Compilation Errors with Go Templates

Q: I have a program with Go template files, those files are namedfoo.go and look like the following:

// Copyright {{.Year}} {{.Author}}. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package {{.Project}}

When I runpackr2 I get errors like:

expected 'IDENT', found '{'

A: Packr works by searching your.go files forgithub.com/gobuffalo/packr/v2#New orgithub.com/gobuffalo/packr/v2#NewBox calls. Because those files aren't "proper" Go files, Packr can't parse them to find the box declarations. To fix this you need to tell Packr to ignore those files when searching for boxes. A couple solutions to this problem are:

  • Name the files something else. The.tmpl extension is the idiomatic way of naming these types of files.
  • Rename the folder containing these files to start with an_, for example_templates. Packr, like Go, will ignore folders starting with the_ character when searching for boxes.
Dynamic Box Paths

Q: I need to set the path of a box using a variable, butpackr.New("foo", myVar) doesn't work correctly.

A: Packr attempts to "automagically" set it's resolution directory when usinggithub.com/gobuffalo/packr/v2#New, however, for dynamic paths you need to set it manually:

box := packr.New("foo", "|")box.ResolutionDir = myVar
I don't want to pack files, but still use the Packr interface.

Q: I want to write code that using the Packr tools, but doesn't actually pack the files into my binary. How can I do that?

A: Usinggithub.com/gobuffalo/packr/v2#Folder gives you back a*packr.Box that can be used as normal, but is excluded by the Packr tool when compiling.

Packr Finds No Boxes

Q: I runpackr2 -v but it doesn't find my boxes:

DEBU[2019-03-18T18:48:52+01:00] *parser.Parser#NewFromRoots found prospects=0DEBU[2019-03-18T18:48:52+01:00] found 0 boxes

A: Packr works by parsing.go files to findgithub.com/gobuffalo/packr/v2#Box andgithub.com/gobuffalo/packr/v2#NewBox declarations. If there aren't any.go in the folder thatpackr2 is run in it can not find those declarations. To fix this problem run thepackr2 command in the directory containing your.go files.

Box Interfaces

Q: I want to be able to easily test my applications by passing in mock boxes. How do I do that?

A: Packr boxes and files conform to the interfaces found atgithub.com/gobuffalo/packd. Change your application to use those interfaces instead of the concrete Packr types.

// using concrete typefunc myFunc(box *packr.Box) {}// using interfacesfunc myFunc(box packd.Box) {}

Documentation

Index

Constants

View Source
const Version = "v2.8.3"

Version of Packr

Variables

View Source
var (// ErrResOutsideBox gets returned in case of the requested resources being outside the box// DeprecatedErrResOutsideBox =fmt.Errorf("can't find a resource outside the box"))

Functions

funcPackBytes

func PackBytes(boxstring, namestring, bb []byte)

PackBytes packs bytes for a file into a box.Deprecated

funcPackBytesGzip

func PackBytesGzip(boxstring, namestring, bb []byte)error

PackBytesGzip packets the gzipped compressed bytes into a box.Deprecated

funcPackJSONBytes

func PackJSONBytes(boxstring, namestring, jbbstring)error

PackJSONBytes packs JSON encoded bytes for a file into a box.Deprecated

Types

typeBox

type Box struct {Pathstring            `json:"path"`Namestring            `json:"name"`ResolutionDirstring            `json:"resolution_dir"`DefaultResolverresolver.Resolver `json:"default_resolver"`// contains filtered or unexported fields}

Box represent a folder on a disk you want tohave access to in the built Go binary.

funcFolderadded inv2.0.9

func Folder(pathstring) *Box

Folder returns a Box that will NOT be packed.This is useful for writing tests or tools thatneed to work with a folder at runtime.

funcNew

func New(namestring, pathstring) *Box

New returns a new Box with the name of the boxand the path of the box.

funcNewBox

func NewBox(pathstring) *Box

NewBox returns a Box that can be used toretrieve files from either disk or the embeddedbinary.Deprecated: Use New instead.

func (*Box)AddBytes

func (b *Box) AddBytes(pathstring, t []byte)error

AddBytes sets t in b.data by the given path

func (*Box)AddString

func (b *Box) AddString(pathstring, tstring)error

AddString converts t to a byteslice and delegates to AddBytes to add to b.data

func (*Box)Bytes

func (b *Box) Bytes(namestring) []byte

Bytes is deprecated. Use Find instead

func (*Box)Find

func (b *Box) Find(namestring) ([]byte,error)

Find returns either the byte slice of the requestedfile or an error if it can not be found.

func (*Box)FindString

func (b *Box) FindString(namestring) (string,error)

FindString returns either the string of the requestedfile or an error if it can not be found.

func (*Box)Has

func (b *Box) Has(namestring)bool

Has returns true if the resource exists in the box

func (*Box)HasDir

func (b *Box) HasDir(namestring)bool

HasDir returns true if the directory exists in the box

func (*Box)List

func (b *Box) List() []string

List shows "What's in the box?"

func (*Box)MustBytes

func (b *Box) MustBytes(namestring) ([]byte,error)

MustBytes is deprecated. Use Find instead.

func (*Box)MustString

func (b *Box) MustString(namestring) (string,error)

MustString is deprecated. Use FindString instead

func (*Box)Open

func (b *Box) Open(namestring) (http.File,error)

Open returns a File using the http.File interface

func (*Box)Resolve

func (b *Box) Resolve(keystring) (file.File,error)

Resolve will attempt to find the file in the box,returning an error if the find can not be found.

func (*Box)SetResolver

func (b *Box) SetResolver(filestring, resresolver.Resolver)

SetResolver allows for the use of a custom resolver forthe specified file

func (*Box)String

func (b *Box) String(namestring)string

String is deprecated. Use FindString instead

func (*Box)Walk

func (b *Box) Walk(wfWalkFunc)error

Walk will traverse the box and call the WalkFunc for each file in the box/folder.

func (*Box)WalkPrefix

func (b *Box) WalkPrefix(prefixstring, wfWalkFunc)error

WalkPrefix will call box.Walk and call the WalkFunc when it finds paths that have a matching prefix

typeFile

type File =file.File

File has been deprecated and file.File should be used instead

typePointer

type Pointer struct {ForwardBoxstringForwardPathstring}

Pointer is a resolvr which resolvesa file from a different box.

func (Pointer)Resolve

func (pPointer) Resolve(boxstring, pathstring) (file.File,error)

Resolve attempts to find the file in the specific boxwith the specified key

typeWalkFunc

type WalkFunc =packd.WalkFunc

WalkFunc is used to walk a box

Source Files

View all Source files

Directories

PathSynopsis
_fixtures
resolver/encoding/hex
Package hex implements hexadecimal encoding and decoding.
Package hex implements hexadecimal encoding and decoding.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp