package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
)
type PvRelationList struct {
Item []PvRelationInfo `json:"item"`
}
type PvRelationInfo struct {
PodName string `json:"pod_name"`
PodUid string `json:"pod_uid"`
}
func readFile(f *os.File) ([]byte, error) {
var size int
if info, err := f.Stat(); err == nil {
size64 := info.Size()
if int64(int(size64)) == size64 {
size = int(size64)
}
}
size++ // one byte for final read at EOF
if size < 512 {
size = 512
}
data := make([]byte, 0, size)
for {
if len(data) >= cap(data) {
d := append(data[:cap(data)], 0)
data = d[:len(data)]
}
n, err := f.Read(data[len(data):cap(data)])
data = data[:len(data)+n]
if err != nil {
if err == io.EOF {
err = nil
}
return data, err
}
}
}
func isFileEmpty(filePath string) (bool, error) {
fileInfo, err := os.Stat(filePath)
if err != nil {
return false, err
}
return fileInfo.Size() == 0, nil
}
func main() {
filename := "1.log"
f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
panic(err.Error())
}
defer f.Close()
readInfo, err := readFile(f)
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("read data %v \n", string(readInfo))
//write
pvRelationList := make([]PvRelationInfo, 0)
res, err := isFileEmpty(filename)
if err != nil {
panic(err.Error())
}
if !res {
err = json.Unmarshal(readInfo, &pvRelationList)
if err != nil {
panic(err.Error())
}
}
pvRelationInfo := PvRelationInfo{
PodName: "ioioiuo",
PodUid: "97492uwoer8u",
}
pvRelationList = append(pvRelationList, pvRelationInfo)
pvRelationListByte, err := json.Marshal(pvRelationList)
if err != nil {
panic(err.Error())
}
err = f.Truncate(0)
if err != nil {
panic(err.Error())
}
// 将文件指针移动到文件的开始位置
_, err = f.Seek(0, 0)
if err != nil {
log.Fatalf("failed to seek file: %s", err)
}
fmt.Printf("write data %v \n", string(pvRelationListByte))
writeRes, err := f.Write(pvRelationListByte)
if err != nil {
panic(err.Error())
}
fmt.Println(writeRes)
}