// 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.funccopyFile(src, dststring) error {
sfi, err:=os.Stat(src)
iferr!=nil {
returnerr
}
if!sfi.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,// symlinks, devices, etc.)returnfmt.Errorf("CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String())
}
dfi, err:=os.Stat(dst)
iferr!=nil {
if!os.IsNotExist(err) {
returnerr
}
} else {
if!(dfi.Mode().IsRegular()) {
returnfmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
}
ifos.SameFile(sfi, dfi) {
returnerr
}
}
iferr=os.Link(src, dst); err==nil {
returnerr
}
err=copyFileContents(src, dst)
returnerr
}
// 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.funccopyFileContents(src, dststring) (errerror) {
in, err:=os.Open(src)
iferr!=nil {
return
}
deferin.Close()
out, err:=os.Create(dst)
iferr!=nil {
return
}
deferfunc() {
cerror:=out.Close()
iferr==nil {
err=cerror
}
}()
if_, err=io.Copy(out, in); err!=nil {
return
}
err=out.Sync()
return
}
3 List files from directory
//listFiles show the file list in directoryfunclistFiles(dirnamestring) []string {
fileList:= []string{}
files, _:=ioutil.ReadDir(dirname)
for_, fileInfo:=rangefiles {
if!fileInfo.IsDir() {
fileList=append(fileList, fileInfo.Name())
}
}
returnfileList
}
4 Check path existing or not
if_, err:=os.Stat(DefaultContent); !os.IsNotExist(err) {
log.Fatalf("Already has default config:%s", DefaultContent)
}