-
Notifications
You must be signed in to change notification settings - Fork 3k
/
gzip.go
76 lines (69 loc) · 1.96 KB
/
gzip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package ioutil
import (
"compress/gzip"
"encoding/json"
"fmt"
"io"
"os"
"strings"
)
// OpenDecompressed opens a reader for the specified file and automatically gzip decompresses the content
// if the filename ends with .gz
func OpenDecompressed(path string) (io.ReadCloser, error) {
var r io.ReadCloser
r, err := os.Open(path)
if err != nil {
return nil, err
}
if IsGzip(path) {
r, err = gzip.NewReader(r)
if err != nil {
return nil, fmt.Errorf("failed to create gzip reader: %w", err)
}
}
return r, nil
}
// OpenCompressed opens a file for writing and automatically compresses the content if the filename ends with .gz
func OpenCompressed(file string, flag int, perm os.FileMode) (io.WriteCloser, error) {
var out io.WriteCloser
out, err := os.OpenFile(file, flag, perm)
if err != nil {
return nil, err
}
return CompressByFileType(file, out), nil
}
// WriteCompressedBytes writes a byte slice to the specified file.
// If the filename ends with .gz, a byte slice is compressed and written.
func WriteCompressedBytes(file string, data []byte, flag int, perm os.FileMode) error {
out, err := OpenCompressed(file, flag, perm)
if err != nil {
return err
}
defer out.Close()
_, err = out.Write(data)
return err
}
// WriteCompressedJson writes the object to the specified file as a compressed json object
// if the filename ends with .gz.
func WriteCompressedJson(file string, obj any) error {
if !IsGzip(file) {
return fmt.Errorf("file %v does not have .gz extension", file)
}
out, err := OpenCompressed(file, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer out.Close()
return json.NewEncoder(out).Encode(obj)
}
// IsGzip determines if a path points to a gzip compressed file.
// Returns true when the file has a .gz extension.
func IsGzip(path string) bool {
return strings.HasSuffix(path, ".gz")
}
func CompressByFileType(file string, out io.WriteCloser) io.WriteCloser {
if IsGzip(file) {
return gzip.NewWriter(out)
}
return out
}