/
util.go
94 lines (76 loc) · 1.46 KB
/
util.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package image
import (
"fmt"
"image"
"io"
"os"
"path/filepath"
_ "image/jpeg"
_ "image/png"
)
func basicErr(e error) {
if e != nil {
fmt.Fprintf(os.Stderr, "FATAL: %s\n", e)
os.Exit(-1)
}
}
type xrror struct {
base string
vals []interface{}
}
func (x *xrror) Error() string {
return fmt.Sprintf("%s", fmt.Sprintf(x.base, x.vals...))
}
func (x *xrror) Out(vals ...interface{}) *xrror {
x.vals = vals
return x
}
func Xrror(base string) *xrror {
return &xrror{base: base}
}
func openImage(path string) (image.Image, error) {
file, err := openFile(path)
if err != nil {
return nil, err
}
defer file.Close()
i, err := decodeImage(file)
if err != nil {
return nil, err
}
return i, nil
}
func exist(path string) {
if _, err := os.Stat(path); os.IsNotExist(err) {
os.MkdirAll(path, os.ModeDir|0755)
}
}
var openFileError = Xrror("unable to find or open file %s, provided %s").Out
//
func openFile(path string) (*os.File, error) {
p := filepath.Clean(path)
dir, name := filepath.Split(p)
var fp string
var err error
switch dir {
case "":
fp, err = filepath.Abs(name)
default:
exist(dir)
fp, err = filepath.Abs(p)
}
if err != nil {
return nil, err
}
if file, err := os.OpenFile(fp, os.O_RDWR|os.O_CREATE, 0660); err == nil {
return file, nil
}
return nil, openFileError(fp, path)
}
func decodeImage(r io.Reader) (image.Image, error) {
img, _, err := image.Decode(r)
if err != nil {
return nil, err
}
return img, nil
}