Golang File IO Operations

Read File into []byte in Package:ioutil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func readFileIntoByte(filename string) []byte {
var fmwConfigJsonBuf []byte

fin, err := os.Open(filename)

if err != nil {
panic(err)
} else {
fmwConfigJsonBuf, err = ioutil.ReadAll(fin)
if err != nil {
panic(err)
}
}
fin.Close()
return fmwConfigJsonBuf
}

File Copy

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
// CopyFile copies a file from src to dst. If src and dst files exist, and are
// the same, then return success. Otherise, attempt to create a hard link
// between the two files. If that fail, copy the file contents from src to dst.
func copyFile(src, dst string) error {
sfi, err := os.Stat(src)
if err != nil {
return err
}
if !sfi.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,
// symlinks, devices, etc.)
return fmt.Errorf("CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String())
}
dfi, err := os.Stat(dst)
if err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
if !(dfi.Mode().IsRegular()) {
return fmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
}
if os.SameFile(sfi, dfi) {
return err
}
}
if err = os.Link(src, dst); err == nil {
return err
}
err = copyFileContents(src, dst)
return err
}

// copyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
func copyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cerror := out.Close()
if err == nil {
err = cerror
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}

List files from directory

1
2
3
4
5
6
7
8
9
10
11
//listFiles show the file list in directory
func listFiles(dirname string) []string {
fileList := []string{}
files, _ := ioutil.ReadDir(dirname)
for _, fileInfo := range files {
if !fileInfo.IsDir() {
fileList = append(fileList, fileInfo.Name())
}
}
return fileList
}

Check path existing or not

1
2
3
if _, err := os.Stat(DefaultContent); !os.IsNotExist(err) {
log.Fatalf("Already has default config:%s", DefaultContent)
}

Remove directory and its’ contents

1
2
3
if err := os.RemoveAll(filePath); err != nil {
panic(err)
}

Change relative path into abs path

1
2
3
import "path/filepath"

uploads, _ := filepath.Abs(uploadPath)