I'm wondering what is the best way to convert binary File
to []byte
Here is a sample code that doesn't work. I'm wondering how I should adjust it to return the content as
func ReadFileAndReturnByteArray(extractedFilePath string) ([]byte, error) {
file, err := os.Open(extractedFilePath)
if err != nil {
return nil, err
}
defer file.Close()
fileinfo, err := file.Stat()
if err != nil {
fmt.Println(err)
return nil, err
}
filesize := fileinfo.Size()
buffer := make([]byte, filesize)
_, err = file.Read(buffer)
if err != nil {
fmt.Println(err)
return nil, err
}
return buffer, nil
}
CodePudding user response:
The os package provides a ReadFile function which only works for files. It has the exact same signature as your ReadFileAndReturnByteArray
function and should be a drop-in replacement.
The io package provides the ReadAll function which works for any io.Reader
.
Example:
func ReadFileAndReturnByteArray(extractedFilePath string) ([]byte, error) {
file, err := os.Open(extractedFilePath)
if err != nil {
return nil, err
}
defer file.Close()
return io.ReadAll()
}