-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
62 lines (56 loc) · 1.52 KB
/
file.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
package testutil
import (
"bufio"
"encoding/base64"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
)
// ReadAndHexDecode reads a hex-encoded file and returns the decoded data.
// Each line is returned as its own buffer.
func ReadAndHexDecode(filename string) ([][]byte, error) {
path := getTestDataPath(filename)
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("os.Open: %v", err)
}
defer file.Close()
lines := make([]string, 0)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
data := make([][]byte, len(lines))
for i, line := range lines {
data[i], err = hex.DecodeString(line)
if err != nil {
return nil, fmt.Errorf("hex.DecodeString: %v", err)
}
}
return data, nil
}
// ReadAndBase64Decode reads a base64-encoded file and returns the decoded data.
// The entire content is returned as a single buffer.
func ReadAndBase64Decode(filename string) ([]byte, error) {
path := getTestDataPath(filename)
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("os.Open: %v", err)
}
defer file.Close()
var sb strings.Builder
scanner := bufio.NewScanner(file)
for scanner.Scan() {
sb.WriteString(scanner.Text())
}
return base64.StdEncoding.DecodeString(sb.String())
}
// getTestDataPath returns the absolute path of the testdata directory.
func getTestDataPath(filename string) string {
_, path, _, _ := runtime.Caller(0)
root := filepath.Join(filepath.Dir(path), "..")
return filepath.Join(root, "testdata", filename)
}