base64 - 编码/解码base64

标签 base64 go

这是我的代码,我不明白为什么解码功能不起作用。

请稍加见解。

func EncodeB64(message string) (retour string) {
    base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(message)))
    base64.StdEncoding.Encode(base64Text, []byte(message))
    return string(base64Text)
}

func DecodeB64(message string) (retour string) {
    base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
    base64.StdEncoding.Decode(base64Text, []byte(message))
    fmt.Printf("base64: %s\n", base64Text)
    return string(base64Text)
}

它给了我: [解码错误 - 输出不是 utf-8][解码错误 - 输出不是 utf-8]

最佳答案

len前缀很肤浅,导致无效的utf-8错误:

package main

import (
        "encoding/base64"
        "fmt"
        "log"
)

func main() {
        str := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
        fmt.Println(str)

        data, err := base64.StdEncoding.DecodeString(str)
        if err != nil {
                log.Fatal("error:", err)
        }

        fmt.Printf("%q\n", data)
}

(也称为 here)


输出

SGVsbG8sIHBsYXlncm91bmQ=
"Hello, playground"

编辑:我读得太快了,len 没有用作前缀。 dystroy 做对了。

关于base64 - 编码/解码base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15334220/

相关文章:

go - 为什么不读/写其内容的结构方法仍然会导致竞争情况?

email - 是否在76之后是RFC 2045所定义的MIME节的行长限制?

javascript - Postman 上带有 base64 字符串的无效 JSON 数据

go - 为什么此 channel 上的发送不会被阻塞?

dictionary - 分配给 nil 映射中的条目

go - 如何将指针的值从映射传递到函数参数

go - 在GoDog测试框架中使用断言库

angularjs - 将base64数据url转换为angularjs中的图像文件

java - Base64 编码与 Ascii85 编码

javascript - 转换数据:image/png;base64 into an image type in database