Skip to content

Instantly share code, notes, and snippets.

@1xch
Created February 27, 2019 15:43
Show Gist options
  • Save 1xch/bba3af2ffae46126097c1b22f46fddd2 to your computer and use it in GitHub Desktop.
Save 1xch/bba3af2ffae46126097c1b22f46fddd2 to your computer and use it in GitHub Desktop.
my goto file open in go
import (
"github.com/Laughs-In-Flowers/xrr"
)
func openFile(path string) (*os.File, error) {
p := filepath.Clean(path)
dir, name := filepath.Split(p)
var fp string
var aErr error
switch dir {
case "":
fp, aErr = filepath.Abs(name)
default:
exist(dir)
fp, aErr = filepath.Abs(p)
}
if aErr != nil {
return nil, aErr
}
var file *os.File
var oErr error
if file, oErr = os.OpenFile(fp, os.O_RDWR|os.O_CREATE, 0660); oErr != nil {
return nil, openError(fp, path)
}
return file, nil
}
func exist(path string) {
if _, err := os.Stat(path); os.IsNotExist(err) {
os.MkdirAll(path, os.ModeDir|0755)
}
}
var openError = xrr.Xrror("unable to find or open file %s, provided %s").Out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment