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:
- The
Pack*/Unpack*methods can implement packing/unpacking for any file, packing to binary files or Go code files. - Resource management is implemented by the
Resourceobject, which can add packed content, search files, and traverse directories. - Resource files are implemented by the
Fileobject, which is similar to theos.Fileobject and implements thehttp.Fileinterface. ScanDiris used for file/directory search in a specific directory, supporting recursive search.ScanDirFileis used for file search in a specific directory, supporting recursive search.- The
Dumpmethod prints out all files of theResourceobject on the terminal, with the file separator in the resource manager unified as/. - Furthermore, the
gresresource management module provides a defaultResourceobject 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.