| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"strings" |
| 6 |
|
| 7 |
"github.com/peterbourgon/diskv/v3" |
| 8 |
) |
| 9 |
|
| 10 |
func AdvancedTransformExample(key string) *diskv.PathKey { |
| 11 |
path := strings.Split(key, "/") |
| 12 |
last := len(path) - 1 |
| 13 |
return &diskv.PathKey{ |
| 14 |
Path: path[:last], |
| 15 |
FileName: path[last] + ".txt", |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
// If you provide an AdvancedTransform, you must also provide its |
| 20 |
// inverse: |
| 21 |
|
| 22 |
func InverseTransformExample(pathKey *diskv.PathKey) (key string) { |
| 23 |
txt := pathKey.FileName[len(pathKey.FileName)-4:] |
| 24 |
if txt != ".txt" { |
| 25 |
panic("Invalid file found in storage folder!") |
| 26 |
} |
| 27 |
return strings.Join(pathKey.Path, "/") + pathKey.FileName[:len(pathKey.FileName)-4] |
| 28 |
} |
| 29 |
|
| 30 |
func main() { |
| 31 |
d := diskv.New(diskv.Options{ |
| 32 |
BasePath: "my-data-dir", |
| 33 |
AdvancedTransform: AdvancedTransformExample, |
| 34 |
InverseTransform: InverseTransformExample, |
| 35 |
CacheSizeMax: 1024 * 1024, |
| 36 |
}) |
| 37 |
// Write some text to the key "alpha/beta/gamma". |
| 38 |
key := "alpha/beta/gamma" |
| 39 |
d.WriteString(key, "¡Hola!") // will be stored in "<basedir>/alpha/beta/gamma.txt" |
| 40 |
fmt.Println(d.ReadString("alpha/beta/gamma")) |
| 41 |
} |