Serge Bazanski | cc25bdf | 2018-10-25 14:02:58 +0200 | [diff] [blame] | 1 | package packr |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "compress/gzip" |
| 6 | "encoding/json" |
| 7 | "runtime" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | ) |
| 11 | |
| 12 | var gil = &sync.Mutex{} |
| 13 | var data = map[string]map[string][]byte{} |
| 14 | |
| 15 | // PackBytes packs bytes for a file into a box. |
| 16 | func PackBytes(box string, name string, bb []byte) { |
| 17 | gil.Lock() |
| 18 | defer gil.Unlock() |
| 19 | if _, ok := data[box]; !ok { |
| 20 | data[box] = map[string][]byte{} |
| 21 | } |
| 22 | data[box][name] = bb |
| 23 | } |
| 24 | |
| 25 | // PackBytesGzip packets the gzipped compressed bytes into a box. |
| 26 | func PackBytesGzip(box string, name string, bb []byte) error { |
| 27 | var buf bytes.Buffer |
| 28 | w := gzip.NewWriter(&buf) |
| 29 | _, err := w.Write(bb) |
| 30 | if err != nil { |
| 31 | return err |
| 32 | } |
| 33 | err = w.Close() |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | PackBytes(box, name, buf.Bytes()) |
| 38 | return nil |
| 39 | } |
| 40 | |
| 41 | // PackJSONBytes packs JSON encoded bytes for a file into a box. |
| 42 | func PackJSONBytes(box string, name string, jbb string) error { |
| 43 | var bb []byte |
| 44 | err := json.Unmarshal([]byte(jbb), &bb) |
| 45 | if err != nil { |
| 46 | return err |
| 47 | } |
| 48 | PackBytes(box, name, bb) |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | // UnpackBytes unpacks bytes for specific box. |
| 53 | func UnpackBytes(box string) { |
| 54 | gil.Lock() |
| 55 | defer gil.Unlock() |
| 56 | delete(data, box) |
| 57 | } |
| 58 | |
| 59 | func osPaths(paths ...string) []string { |
| 60 | if runtime.GOOS == "windows" { |
| 61 | for i, path := range paths { |
| 62 | paths[i] = strings.Replace(path, "/", "\\", -1) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | return paths |
| 67 | } |
| 68 | |
| 69 | func osPath(path string) string { |
| 70 | if runtime.GOOS == "windows" { |
| 71 | return strings.Replace(path, "/", "\\", -1) |
| 72 | } |
| 73 | return path |
| 74 | } |