94 lines
1.4 KiB
Go
Raw Normal View History

2024-03-22 18:05:47 +08:00
package xfile
import (
2024-03-23 21:25:19 +08:00
"bufio"
"encoding/json"
2024-03-22 18:05:47 +08:00
"esgo2dump/internal/interfaces"
2024-03-23 21:25:19 +08:00
"github.com/sirupsen/logrus"
2024-03-22 18:05:47 +08:00
"os"
)
type client struct {
2024-03-23 21:25:19 +08:00
f *os.File
scanner *bufio.Scanner
2024-03-22 18:05:47 +08:00
}
2024-03-23 21:25:19 +08:00
func (c *client) IsInput() bool {
2024-03-22 18:05:47 +08:00
//TODO implement me
panic("implement me")
}
2024-03-23 21:25:19 +08:00
func (c *client) IsFile() bool {
return true
2024-03-22 18:05:47 +08:00
}
2024-03-23 21:25:19 +08:00
func (c *client) Write(docs []*interfaces.ESSource) (int, error) {
var (
err error
bs []byte
count = 0
)
for _, doc := range docs {
if bs, err = json.Marshal(doc); err != nil {
return count, err
}
bs = append(bs, '\n')
if _, err = c.f.Write(bs); err != nil {
return count, err
}
count++
}
return count, nil
}
func (c *client) Read(i int) ([]*interfaces.ESSource, error) {
var (
err error
count = 0
list = make([]*interfaces.ESSource, 0, i)
)
for c.scanner.Scan() {
line := c.scanner.Text()
logrus.Debugf("xfile.Read: line=%s", line)
item := new(interfaces.ESSource)
if err = json.Unmarshal([]byte(line), item); err != nil {
return list, err
}
list = append(list, item)
count++
if count >= i {
break
}
}
if err = c.scanner.Err(); err != nil {
return list, err
}
return list, nil
}
func (c *client) Close() error {
return c.f.Close()
2024-03-22 18:05:47 +08:00
}
2024-03-23 21:25:19 +08:00
func NewClient(file *os.File, ioType interfaces.IO) (interfaces.DumpIO, error) {
c := &client{f: file}
if ioType == interfaces.IOInput {
c.scanner = bufio.NewScanner(c.f)
}
return c, nil
2024-03-22 18:05:47 +08:00
}