github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/utils/file.go (about)

     1  package utils
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/unicornultrafoundation/go-u2u/log"
     9  )
    10  
    11  func OpenFile(path string, isSyncMode bool) *os.File {
    12  	const dirPerm = 0700
    13  	if err := os.MkdirAll(filepath.Dir(path), dirPerm); err != nil {
    14  		log.Crit("Failed to create file dir", "file", path, "err", err)
    15  	}
    16  	sync := 0
    17  	if isSyncMode {
    18  		sync = os.O_SYNC
    19  	}
    20  	fh, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|sync, 0666)
    21  	if err != nil {
    22  		log.Crit("Failed to open file", "file", path, "err", err)
    23  	}
    24  	return fh
    25  }
    26  
    27  func FileExists(path string) bool {
    28  	_, err := os.Stat(path)
    29  	return err == nil
    30  }
    31  
    32  func FilePut(path string, content []byte, isSyncMode bool) {
    33  	fh := OpenFile(path, isSyncMode)
    34  	defer fh.Close()
    35  	if err := fh.Truncate(0); err != nil {
    36  		log.Crit("Failed to truncate file", "file", path, "err", err)
    37  	}
    38  	if _, err := fh.Write(content); err != nil {
    39  		log.Crit("Failed to write to file", "file", path, "err", err)
    40  	}
    41  }
    42  
    43  func FileGet(path string) []byte {
    44  	if !FileExists(path) {
    45  		return nil
    46  	}
    47  	fh, err := os.Open(path)
    48  	if err != nil {
    49  		log.Crit("Failed to open file", "file", path, "err", err)
    50  	}
    51  	defer fh.Close()
    52  	res, _ := ioutil.ReadAll(fh)
    53  	return res
    54  }