-
Notifications
You must be signed in to change notification settings - Fork 0
/
opt.go
76 lines (60 loc) · 1.2 KB
/
opt.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 gosfile
import (
"encoding/base64"
"os"
"strings"
)
type Option struct {
src string
err error
}
func newOption(src string, err error) *Option {
return &Option{
src: src,
err: err,
}
}
func (opt *Option) ToString() (string, error) {
if err := opt.validate(); err != nil {
return "", err
}
return string(opt.src), nil
}
func (opt *Option) ExportTo(pathAndName string) error {
if err := opt.validate(); err != nil {
return err
}
listWord := strings.Split(string(opt.src), "base64,")
if len(listWord) != 2 {
return opt.writeFile([]byte(opt.src), pathAndName)
}
wordBase64 := listWord[1]
decodeString, err := base64.StdEncoding.DecodeString(wordBase64)
if err != nil {
return err
}
return opt.writeFile(decodeString, pathAndName)
}
func (opt *Option) writeFile(wordBase64 []byte, pathAndName string) error {
fPlain, err := os.Create(pathAndName)
if err != nil {
return err
}
defer fPlain.Close()
if _, err := fPlain.Write(wordBase64); err != nil {
return err
}
if err := fPlain.Sync(); err != nil {
return err
}
return nil
}
func (opt *Option) validate() (err error) {
if opt == nil {
return ErrInternal
}
if opt.err != nil {
return err
}
return nil
}