-
Notifications
You must be signed in to change notification settings - Fork 176
/
arprint.go
48 lines (42 loc) · 988 Bytes
/
arprint.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
// ex10.2 detects and reads zip and tar archives.
package arprint
import (
"bufio"
"fmt"
"io"
"os"
)
type format struct {
name, magic string
magicOffset int
reader NewReader
}
type NewReader func(*os.File) (io.Reader, error)
var formats []format
// We could probably just try opening readers instead of checking magic
// numbers.
func RegisterFormat(name, magic string, magicOffset int, f NewReader) {
formats = append(formats, format{name, magic, magicOffset, f})
}
func Open(file *os.File) (io.Reader, error) {
var found *format
r := bufio.NewReader(file)
for _, f := range formats {
p, err := r.Peek(f.magicOffset + len(f.magic))
if err != nil {
continue
}
if string(p[f.magicOffset:]) == f.magic {
found = &f
break
}
}
if found == nil {
return nil, fmt.Errorf("open archive: can't determine format")
}
_, err := file.Seek(0, os.SEEK_SET)
if err != nil {
return nil, fmt.Errorf("open archive: %s", err)
}
return found.reader(file)
}