file_util.go 1.2 KB
package webutility

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// ReadFileContent ...
func ReadFileContent(path string) ([]byte, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	buf := &bytes.Buffer{}
	if _, err = io.Copy(buf, f); err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

// ReadFileLines ...
func ReadFileLines(path string) ([]string, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var s strings.Builder

	if _, err = io.Copy(&s, f); err != nil {
		return nil, err
	}

	lines := strings.Split(s.String(), "\n")
	for i := range lines {
		lines[i] = strings.TrimRight(lines[i], "\r\n")
	}

	return lines, nil
}

// LinesToFile ...
func LinesToFile(path string, lines []string) error {
	content := ""
	for _, l := range lines {
		content += l + "\n"
	}

	return ioutil.WriteFile(path, []byte(content), 0644) // drw-r--r--
}

// InsertLine ...
func InsertLine(lines *[]string, pos int64, l string) {
	tail := append([]string{l}, (*lines)[pos:]...)

	*lines = append((*lines)[:pos], tail...)
}

func WriteFile(path string, content []byte) error {
	return ioutil.WriteFile(path, content, 0644) // drw-r--r--
}