douzhi1972 2019-03-06 09:03
浏览 186

需要在golang中生成运行时二进制编码文件

I am working on the project in which I need to generate a file as binary encoded(bytes). Thing is that, I don't want to store the file but just need the encoded data to verify with some test data.

Here is the sample code I have zip file

Above example is for zip but I am not restricted to use zip or any file type. And here we need to have stored file to read but I don't want to store and delete the file later.

I know it has not much efforts to ask for the help, but as an newbie, I come to that only.

Thanks.

  • 写回答

1条回答 默认 最新

  • doudu7626 2019-03-06 10:15
    关注

    A better practice is to not rely on concrete types (e.g. os.File), but use interfaces instead that describe the functionality you want to use the file for.

    E.g. if you have a function that takes a file because it wants to read from it, use io.Reader instead:

    func process(r io.Reader) error {
        // ...
    }
    

    Similarly, if you want to write to the file, use io.Writer, or if you want to do both, use io.ReadWriter or io.ReadWriteCloser. You may pass an *os.File value to these functions, because *os.File implements those interfaces.

    The benefit of this is that you can call these functions with any values that implement the interface. If you want to test these functions, you may pass an in-memory bytes.Buffer which implements io.Reader and io.Writer, and whose content you can construct manually, at runtime, for example:

    buf := &bytes.Buffer{}
    buf.Write([]byte{1, 2, 3})
    buf.WriteString("Hello")
    

    Here buf will contain the bytes 1, 2, 3 and the string "Hello". After that you may pass buf where a reader or writer is needed, e.g.:

    process(buf)
    

    See similar / related questions and examples:

    Fill os.Stdin for function that reads from it

    Example code for testing the filesystem in Golang

    评论

报告相同问题?

悬赏问题

  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件