go提供对base64
编码/解码的内置支持。导入带有b64
名称的encoding/base64
软件包,而不是默认的base64
。它会节省我们一些空间。go支持标准和url兼容的base64
。 以下是使用标准编码器进行编码的方法。编码器需要一个[]byte
,所以将字符串转换为该类型。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html
base64-encoding.go
的完整代码如下所示 -
package main
// this syntax imports the `encoding/base64` package with
// the `b64` name instead of the default `base64`. it'll
// save us some space below.
import b64 "encoding/base64"
import "fmt"
func main() {
// here's the `string` we'll encode/decode.
data := "abc123!?$*&()'-=@~"
// go supports both standard and url-compatible
// base64. here's how to encode using the standard
// encoder. the encoder requires a `[]byte` so we
// cast our `string` to that type.
senc := b64.stdencoding.encodetostring([]byte(data))
fmt.println(senc)
// decoding may return an error, which you can check
// if you don't already know the input to be
// well-formed.
sdec, _ := b64.stdencoding.decodestring(senc)
fmt.println(string(sdec))
fmt.println()
// this encodes/decodes using a url-compatible base64
// format.
uenc := b64.urlencoding.encodetostring([]byte(data))
fmt.println(uenc)
udec, _ := b64.urlencoding.decodestring(uenc)
fmt.println(string(udec))
}
执行上面代码,将得到以下输出结果 -
f:\worksp\golang>go run base64-encoding.go
ywjjmtizit8kkiyoksctpub+
abc123!?$*&()'-=@~
ywjjmtizit8kkiyoksctpub-
abc123!?$*&()'-=@~