Skip to main content
Version: 2.8.x(Latest)
tip

The examples in this chapter demonstrate encryption/decryption while performing packing/unpacking. Most business projects do not actually require encryption/decryption, so direct use of tools for packing is sufficient.

In the previous chapter, we introduced how to use the gf toolchain for file/directory packing and generate Go files compiled into executables. In this chapter, we introduce the methods involved in resource management and demonstrate a custom packing/unpacking feature through an example of binary resource file packing/unpacking. We also show how to use custom encryption and decryption to protect our resource file contents.

Interface Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/os/gres

Brief Introduction:

  1. The Pack*/ Unpack* methods can implement packing/unpacking for any file, packing to binary files or Go code files.
  2. Resource management is implemented by the Resource object, which can add packed content, search files, and traverse directories.
  3. Resource files are implemented by the File object, which is similar to the os.File object and implements the http.File interface.
  4. ScanDir is used for file/directory search in a specific directory, supporting recursive search.
  5. ScanDirFile is used for file search in a specific directory, supporting recursive search.
  6. The Dump method prints out all files of the Resource object on the terminal, with the file separator in the resource manager unified as /.
  7. Furthermore, the gres resource management module provides a default Resource object with package methods for operating that default object.

Custom Packing Example

We will pack the public and config directories under the project root directory into a data.bin binary file, and encrypt the generated binary content using the gaes encryption algorithm.

package main

import (
"github.com/gogf/gf/v2/crypto/gaes"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gres"
)

var (
CryptoKey = []byte("x76cgqt36i9c863bzmotuf8626dxiwu0")
)

func main() {
binContent, err := gres.Pack("public,config")
if err != nil {
panic(err)
}
binContent, err = gaes.Encrypt(binContent, CryptoKey)
if err != nil {
panic(err)
}
if err := gfile.PutBytes("data.bin", binContent); err != nil {
panic(err)
}
}

Custom Unpacking Example

We will use the data.bin just packed, requiring decryption and unpacking operations.

package main

import (
"github.com/gogf/gf/v2/crypto/gaes"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gres"
)

var (
CryptoKey = []byte("x76cgqt36i9c863bzmotuf8626dxiwu0")
)

func main() {
binContent := gfile.GetBytes("data.bin")
binContent, err := gaes.Decrypt(binContent, CryptoKey)
if err != nil {
panic(err)
}
if err := gres.Add(binContent); err != nil {
panic(err)
}
gres.Dump()
}

Finally, we use gres.Dump() to print out the list of successfully added files to see if the resource files are added successfully.