68 lines
1.3 KiB
Go
68 lines
1.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
func openOrCreateFile(path string) (*os.File, error) {
|
|
// ensure the dir the path is in exists
|
|
basedir := filepath.Dir(path)
|
|
|
|
err := isDirOrError(basedir)
|
|
if err != nil && os.IsNotExist(err) {
|
|
err = os.MkdirAll(basedir, 0o775)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
} else if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var file *os.File
|
|
err = isFileOrError(path);
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
file, err = os.Create(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
} else {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
if file == nil {
|
|
file, err = os.OpenFile(path, os.O_WRONLY | os.O_APPEND, 0)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return file, nil
|
|
}
|
|
|
|
func isFileOrError(path string) error {
|
|
f, err := os.Stat(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if f.IsDir() {
|
|
return fmt.Errorf("%s is not a file", path)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isDirOrError(path string) error {
|
|
f, err := os.Stat(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if !f.IsDir() {
|
|
return fmt.Errorf("%s is not a directory", path)
|
|
}
|
|
return nil
|
|
} |