-
Notifications
You must be signed in to change notification settings - Fork 0
/
commonio.go
68 lines (47 loc) · 1.5 KB
/
commonio.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
package common
import (
"encoding/gob"
"os"
"path/filepath"
)
/* BEGIN EXPORTED METHODS */
// CreateDirIfDoesNotExist - create given directory if does not exist
func CreateDirIfDoesNotExist(dir string) error {
dir = filepath.FromSlash(dir) // Just to be safe
if _, err := os.Stat(dir); os.IsNotExist(err) { // Check dir exists
err = os.MkdirAll(dir, 0755) // Create directory
if err != nil { // Check for errors
return err // Return error
}
}
return nil // No error occurred
}
// WriteGob - create gob from specified object, at filePath
func WriteGob(filePath string, object interface{}) error {
file, err := os.Create(filePath) // Attempt to create file at path
if err != nil { // Check for errors
return err // Return found error
}
encoder := gob.NewEncoder(file) // Write to file
err = encoder.Encode(object) // Encode object
if err != nil { // Check for errors
return err // Return found error
}
file.Close() // Close file operation
return err // Return error (might be nil)
}
// ReadGob - read gob specified at path
func ReadGob(filePath string, object interface{}) error {
file, err := os.Open(filePath) // Attempt to open file at path
if err != nil { // Check for errors
return err // Return found error
}
decoder := gob.NewDecoder(file) // Attempt to decode gob
err = decoder.Decode(object) // Assign to error
if err != nil { // Check for errors
return err // Return found error
}
file.Close() // Close file
return err // Return error
}
/* END EXPORTED METHODS */