Created
November 11, 2021 16:39
-
-
Save AndreaNicola/f8702f3ca96648f5b941af6f5f7a09fb to your computer and use it in GitHub Desktop.
Function useful to compress a variadic of files in a zip file byte slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package compress | |
import ( | |
"archive/zip" | |
"bytes" | |
"fmt" | |
) | |
type SingleCompressError struct { | |
Index int | |
Filename string | |
err error | |
} | |
type CompressError struct { | |
Err string | |
Errs []SingleCompressError | |
} | |
func (c CompressError) Error() string { | |
if c.Errs != nil && len(c.Errs) > 0 { | |
return fmt.Sprintf("error compressing %d files", len(c.Errs)) | |
} else { | |
return c.Err | |
} | |
} | |
func addGenericError(compressError *CompressError, err error) *CompressError { | |
if compressError == nil { | |
compressError = &CompressError{} | |
} | |
compressError.Err = err.Error() | |
return compressError | |
} | |
func addError(compressError *CompressError, index int, filename string, err error) *CompressError { | |
if compressError == nil { | |
compressError = &CompressError{ | |
Err: "", | |
Errs: []SingleCompressError{}, | |
} | |
} | |
compressError.Errs = append(compressError.Errs, SingleCompressError{ | |
Index: index, | |
Filename: filename, | |
err: err, | |
}) | |
return compressError | |
} | |
func Compress(files ...struct { | |
Filename string | |
Content []byte | |
}) ([]byte, *CompressError) { | |
buf := new(bytes.Buffer) | |
var compressError *CompressError = nil | |
// Create a new zip archive. | |
zipWriter := zip.NewWriter(buf) | |
for index, file := range files { | |
zipFile, err := zipWriter.Create(file.Filename) | |
if err != nil { | |
compressError = addError(compressError, index, file.Filename, err) | |
} | |
_, err = zipFile.Write(file.Content) | |
if err != nil { | |
compressError = addError(compressError, index, file.Filename, err) | |
} | |
} | |
err := zipWriter.Close() | |
if err != nil { | |
compressError = addGenericError(compressError, err) | |
} | |
return buf.Bytes(), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment