├── .gitignore ├── LICENSE.md ├── README.md ├── embed.go ├── embed_test.go └── example_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (C) 2013 Clint Caywood 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | embed 2 | ===== 3 | 4 | Package embed allows for storing data resources in a virtual filesystem that gets compiled directly into the output program, eliminating the need to distribute data files with the application. This is especially useful for small web servers that need to deliver content files. 5 | 6 | The data is gzipped to save space. 7 | 8 | An external tool for generating output files can be found [here](http://github.com/cratonica/embedder) 9 | 10 | View the full documentation [here](http://godoc.org/github.com/cratonica/embed) 11 | 12 | Example 13 | ------- 14 | // Create a resource map from files in a directory 15 | resourceMap, _ := embed.CreateFromFiles("/www/js") 16 | 17 | // Pack the files into a serializeable byte buffer 18 | packed, _ := embed.Pack(resourceMap) 19 | 20 | // Generate a .go file that we can include in our project 21 | goCode := embed.GenerateGoCode("main", "Scripts", packed) 22 | fout, _ := os.Open("scripts.go") 23 | fout.Write([]byte(goCode)) 24 | fout.Close() 25 | 26 | // ... 27 | 28 | // Now in our consumer program, we have a variable called "Scripts" 29 | var Scripts embed.PackedResourceMap 30 | 31 | // Unpack the resource map so we can use it 32 | scriptMap, _ := embed.Unpack(Scripts) 33 | 34 | // Pull out the resource we want 35 | jquery := scriptMap["jquery/jquery.min.js"] 36 | 37 | // Use the embedded file data 38 | fmt.Print(jquery) 39 | 40 | -------------------------------------------------------------------------------- /embed.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package embed allows for storing data resources in a virtual filesystem 3 | that gets compiled directly into the output program, eliminating the need 4 | to distribute data files with the application. This is especially useful for small 5 | web servers that need to deliver content files. 6 | 7 | The data is gzipped to save space. 8 | 9 | An external tool for generating output files can be found at http://github.com/cratonica/embedder 10 | 11 | Author: Clint Caywood 12 | 13 | http://github.com/cratonica/embed 14 | */ 15 | package embed 16 | 17 | import ( 18 | "bytes" 19 | "compress/gzip" 20 | "encoding/binary" 21 | "fmt" 22 | "io" 23 | "io/ioutil" 24 | "log" 25 | "os" 26 | "path/filepath" 27 | "sort" 28 | "strings" 29 | ) 30 | 31 | // A mapping of resource identifiers to associated data 32 | type ResourceMap map[string][]byte 33 | 34 | // A compressed resource map that can be used for serialization 35 | type PackedResourceMap []byte 36 | 37 | var byteOrder binary.ByteOrder = binary.LittleEndian 38 | 39 | // Packs the map of resource identifiers => []byte into 40 | // a buffer. This process is reversed by calling Unpack. 41 | func Pack(data ResourceMap) (PackedResourceMap, error) { 42 | var buf bytes.Buffer 43 | writer, err := gzip.NewWriterLevel(&buf, gzip.BestCompression) 44 | if err != nil { 45 | return nil, err 46 | } 47 | keys := make([]string, len(data)) 48 | idx := 0 49 | for key := range data { 50 | keys[idx] = key 51 | idx++ 52 | } 53 | sort.Strings(keys) 54 | for _, i := range keys { 55 | v := data[i] 56 | if err = binary.Write(writer, byteOrder, int32(len(i))); err != nil { 57 | return nil, err 58 | } 59 | if _, err = writer.Write([]byte(i)); err != nil { 60 | return nil, err 61 | } 62 | if err = binary.Write(writer, byteOrder, int32(len(v))); err != nil { 63 | return nil, err 64 | } 65 | if _, err = writer.Write(v); err != nil { 66 | } 67 | } 68 | if err = writer.Close(); err != nil { 69 | return nil, err 70 | } 71 | result := buf.Bytes() 72 | return result, nil 73 | } 74 | 75 | type DeserializationError struct { 76 | what string 77 | expected int 78 | actual int 79 | } 80 | 81 | func (this *DeserializationError) Error() string { 82 | return fmt.Sprintf("Failure deserializing resource: expected %v to be %v bytes, but only read %v bytes", this.what, this.expected, this.actual) 83 | } 84 | 85 | func NewDeserializationError(what string, expected int, actual int) *DeserializationError { 86 | return &DeserializationError{what, expected, actual} 87 | } 88 | 89 | // Reads a buffer generated by a call to Pack, returning the original map 90 | func Unpack(data PackedResourceMap) (ResourceMap, error) { 91 | result := make(map[string][]byte) 92 | buf := bytes.NewBuffer(data) 93 | reader, err := gzip.NewReader(buf) 94 | defer reader.Close() 95 | if err != nil { 96 | return nil, err 97 | } 98 | for { 99 | var size int32 100 | err := binary.Read(reader, byteOrder, &size) 101 | if err != nil { 102 | if err == io.EOF { 103 | break 104 | } 105 | return nil, err 106 | } 107 | keyBuf, err := readAll(reader, int(size)) 108 | if err != nil { 109 | return nil, err 110 | } 111 | err = binary.Read(reader, byteOrder, &size) 112 | if err != nil { 113 | return nil, err 114 | } 115 | dataBuf, err := readAll(reader, int(size)) 116 | if err != nil { 117 | return nil, err 118 | } 119 | result[string(keyBuf)] = dataBuf 120 | } 121 | return result, nil 122 | } 123 | 124 | // Recursively packs all files in the given directory into 125 | // a resource map. Directory delimiters are converted to Unix-style / 126 | // regardless of the host operating system. 127 | func CreateFromFiles(path string) (ResourceMap, error) { 128 | result := make(map[string][]byte) 129 | err := crawl(filepath.Clean(path), filepath.Clean(path), result) 130 | if err != nil { 131 | return nil, err 132 | } 133 | return result, nil 134 | } 135 | 136 | // Generates Go code containing the given data that can be included in the target project 137 | func GenerateGoCode(packageName string, varName string, data PackedResourceMap) string { 138 | template := ` 139 | package %v 140 | 141 | import "github.com/cratonica/embed" 142 | 143 | var %v embed.PackedResourceMap = %#v 144 | ` 145 | return fmt.Sprintf(template, packageName, varName, data) 146 | } 147 | 148 | func readAll(reader io.Reader, size int) ([]byte, error) { 149 | result := make([]byte, size) 150 | totalBytes := 0 151 | for totalBytes < size { 152 | readSize, err := reader.Read(result[totalBytes:]) 153 | if err != nil { 154 | if err == io.EOF && totalBytes+readSize == size { 155 | return result, nil 156 | } else { 157 | return nil, err 158 | } 159 | } 160 | totalBytes += readSize 161 | } 162 | return result, nil 163 | } 164 | 165 | func crawl(rootPath string, currentPath string, dest map[string][]byte) error { 166 | files, err := ioutil.ReadDir(currentPath) 167 | if err != nil { 168 | return err 169 | } 170 | for _, file := range files { 171 | fullPath := filepath.Join(currentPath, file.Name()) 172 | if file.IsDir() { 173 | err := crawl(rootPath, fullPath, dest) 174 | if err != nil { 175 | return err 176 | } 177 | } else { 178 | buf, err := ioutil.ReadFile(fullPath) 179 | if err != nil { 180 | log.Printf("Failure reading file %v: %v", fullPath, err) 181 | } else { 182 | key := strings.TrimLeft(fullPath, rootPath) 183 | if strings.HasPrefix(key, string(os.PathSeparator)) { 184 | key = key[1:] 185 | } 186 | // Convert to unix style for internal use 187 | key = strings.Replace(key, string(os.PathSeparator), "/", -1) 188 | dest[key] = buf 189 | } 190 | } 191 | } 192 | return nil 193 | } 194 | -------------------------------------------------------------------------------- /embed_test.go: -------------------------------------------------------------------------------- 1 | package embed 2 | 3 | import ( 4 | "go/parser" 5 | "go/token" 6 | "io/ioutil" 7 | "os" 8 | "path/filepath" 9 | "testing" 10 | ) 11 | 12 | func TestPack(t *testing.T) { 13 | input := make(map[string][]byte) 14 | input["Foo"] = []byte{0, 1, 2, 3} 15 | packed, err := Pack(input) 16 | if err != nil { 17 | t.Fatal(err) 18 | } 19 | unpacked, err := Unpack(packed) 20 | if err != nil { 21 | t.Fatal(err) 22 | } 23 | for i := 0; i < 4; i++ { 24 | if input["Foo"][i] != unpacked["Foo"][i] { 25 | t.Fatal("Data mismatch") 26 | } 27 | } 28 | } 29 | 30 | func TestPackLarge(t *testing.T) { 31 | input := make(map[string][]byte) 32 | data := make([]byte, 1024*1024) 33 | for i := 0; i < len(data); i++ { 34 | data[i] = byte(i % 256) 35 | } 36 | input["Foo"] = data 37 | packed, err := Pack(input) 38 | if err != nil { 39 | t.Fatal(err) 40 | } 41 | unpacked, err := Unpack(packed) 42 | if err != nil { 43 | t.Fatal(err) 44 | } 45 | for i := 0; i < len(data); i++ { 46 | if data[i] != unpacked["Foo"][i] { 47 | t.Fatal("Data mismatch") 48 | } 49 | } 50 | } 51 | 52 | func TestCreateFromFiles(t *testing.T) { 53 | workDir, err := ioutil.TempDir("", "datamap_test_") 54 | if err != nil { 55 | t.Fatal(err) 56 | } 57 | defer func() { 58 | os.RemoveAll(workDir) 59 | }() 60 | os.Mkdir(filepath.Join(workDir, "SubDir"), 0777) 61 | testMap := map[string][]byte{ 62 | "File0": []byte{0, 1, 2, 3}, 63 | "SubDir" + string(os.PathSeparator) + "File1": []byte{4, 5, 6, 7}, 64 | } 65 | for k, v := range testMap { 66 | err = ioutil.WriteFile(filepath.Join(workDir, k), v, 0777) 67 | if err != nil { 68 | t.Fatal(err) 69 | } 70 | } 71 | resultMap, err := CreateFromFiles(workDir) 72 | if err != nil { 73 | t.Fatal(err) 74 | } 75 | for k, v := range testMap { 76 | for i := 0; i < len(v); i++ { 77 | if resultMap[k][i] != v[i] { 78 | t.Fatal("Data mismatch") 79 | } 80 | } 81 | } 82 | } 83 | 84 | func TestGenerateGoCode(t *testing.T) { 85 | code := GenerateGoCode("mypackage", "Resources", []byte{1, 2, 3}) 86 | _, err := parser.ParseFile(token.NewFileSet(), "", code, 0) 87 | t.Log(code) 88 | if err != nil { 89 | t.Fatal(err) 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package embed_test 2 | 3 | import ( 4 | "fmt" 5 | "github.com/cratonica/embed" 6 | "os" 7 | ) 8 | 9 | func Example() { 10 | // Note: This serialization part is implemented in a tool that can be found at http://github.com/cratonica/embedder 11 | 12 | // Create a resource map from files in a directory 13 | resourceMap, _ := embed.CreateFromFiles("/www/js") 14 | 15 | // Pack the files into a serializeable byte buffer 16 | packed, _ := embed.Pack(resourceMap) 17 | 18 | // Generate a .go file that we can include in our project 19 | goCode := embed.GenerateGoCode("main", "Scripts", packed) 20 | fout, _ := os.Open("scripts.go") 21 | fout.Write([]byte(goCode)) 22 | fout.Close() 23 | 24 | // ... 25 | 26 | // Now in our consumer program, we have a variable called "Scripts" 27 | var Scripts embed.PackedResourceMap 28 | 29 | // Unpack the resource map so we can use it 30 | scriptMap, _ := embed.Unpack(Scripts) 31 | 32 | // Pull out the resource we want 33 | jquery := scriptMap["jquery/jquery.min.js"] 34 | 35 | // Use the embedded file data 36 | fmt.Print(jquery) 37 | } 38 | --------------------------------------------------------------------------------