登录
首页 >  Golang >  Go问答

大文件在GOLANG中Base64编码和解码大小不匹配

来源:stackoverflow

时间:2024-03-24 15:51:37 189浏览 收藏

在 Go 语言中使用 Base64 对大文件进行编码和解码时,原始文件和解码文件之间的字节长度可能不匹配。对于文本文件,不匹配发生在新行上,而对于二进制文件,则发生在两个字节上。本文探讨了这种字节丢失的可能原因。

问题内容

当我尝试使用 golang 对大文件进行 base64 编码和解码时,原始文件和解码文件之间的字节长度不匹配。

在我的测试过程中,文本文件不匹配(1 字节)新行,并且二进制文件不匹配(2 字节)。

什么可能导致这些字节丢失?

package main

import (
    "encoding/base64"
    "io"
    "os"
    "log"
)

func Encode(infile, outfile string) error {
    input, err := os.Open(infile)
    if err != nil {
        return err
    }
    // Close input file
    defer input.Close()

    // Open output file
    output, err := os.Create(outfile)
    if err != nil {
        return err
    }
    // Close output file
    defer output.Close()

    encoder := base64.NewEncoder(base64.StdEncoding, output)
    l, err := io.Copy(encoder, input)
    if err!=nil {
        log.Printf("Failed to encode file:%v",err)
        return err
    } else {
        log.Printf("Wrote %v bytes",l)
    }

    return nil
}

func Decode(infile, outfile string) error {
    input, err := os.Open(infile)
    if err != nil {
        return err
    }
    // Close input file
    defer input.Close()

    // Open output file
    output, err := os.Create(outfile)
    if err != nil {
        return err
    }
    // Close output file
    defer output.Close()

    decoder := base64.NewDecoder(base64.StdEncoding, input)
    l, err := io.Copy(output, decoder)
    if err!=nil {
        log.Printf("Failed to encode file:%v",err)
        return err
    } else {
        log.Printf("Wrote %v bytes",l)
    }

    return nil
}

正确答案


您不需要 clos​​e() encoder,因此它不会刷新所有数据。来自 docs(强调我的):

func newencoder(enc *encoding, w io.writer) io.writecloser

newencoder 返回一个新的 base64 流编码器。数据写入 返回的 writer 将使用 enc 进行编码,然后写入 w。 base64 编码以 4 字节块运行;写完后, 调用者必须关闭返回的编码器以刷新任何部分写入的 块。

我还引用了文档中的示例,其中有一个很好的评论:

package main

import (
    "encoding/base64"
    "os"
)

func main() {
    input := []byte("foo\x00bar")
    encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
    encoder.Write(input)
    // Must close the encoder when finished to flush any partial blocks.
    // If you comment out the following line, the last partial block "r"
    // won't be encoded.
    encoder.Close()
}

终于介绍完啦!小伙伴们,这篇关于《大文件在GOLANG中Base64编码和解码大小不匹配》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>