Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go Base64编码实例
Go Base64编码实例
作者:--    发布时间:2019-11-20

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!?$*&()'-=@~

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册