0

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.

Vinay
  • 324
  • 1
  • 3
  • 15
  • 1
    It's not clear what you want to create and how you want to use it. In general, you can just use an in-memory buffer, be it a simple `[]byte` or a `bytes.Buffer` which implements `io.Reader` and `io.Writer`, so you can use it to read and write just like a file. – icza Mar 06 '19 at 09:05
  • Actually I have scenario like `test cases`, where I need a dummy encoded bytes of File(but don't want to create it) and need to check with other data. Otherwise I have to create a file and then perform the operation, but I don't have definite scenario to delete it(though I can't keep it ) – Vinay Mar 06 '19 at 09:14
  • 1
    You should change the use cases to not rely on the concrete `os.File` type but use interfaces instead (`io.Reader`, `io.Writer` and similar). That way no matter if you pass a `*bytes.Buffer` or an `*os.File`, it will work with both. – icza Mar 06 '19 at 09:22
  • @icza You wants me to change the functionality? Considered it as test cases then how we can generate the bytes of virtual file? – Vinay Mar 06 '19 at 10:08

1 Answers1

3

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

icza
  • 389,944
  • 63
  • 907
  • 827