add: [filerwatcher] base64 or json files

master
Jean-Louis Huynen 2021-02-16 11:30:12 +01:00
parent e6be49a2a1
commit 36d7e16bd2
No known key found for this signature in database
GPG Key ID: 64799157F4BD6B93
1 changed files with 25 additions and 13 deletions

View File

@ -21,19 +21,23 @@ type FileWatcherReader struct {
exit chan string exit chan string
// Current buffer // Current buffer
buf []byte buf []byte
// json
json bool
} }
// NewFileWatcherReader creates a new FileWatcherReader // NewFileWatcherReader creates a new FileWatcherReader
func NewFileWatcherReader(f *os.File) (*FileWatcherReader, error) { // json specifies whether we now we handle json files
func NewFileWatcherReader(f *os.File, j bool) (*FileWatcherReader, error) {
r := &FileWatcherReader{ r := &FileWatcherReader{
folderfd: f, folderfd: f,
eic: make(chan notify.EventInfo, 1), eic: make(chan notify.EventInfo, 1),
json: j,
} }
return r, nil return r, nil
} }
// Read waits for InCloseWrite file event uses a bytes reader to copy // Read waits for InCloseWrite file event uses a bytes reader to copy
// the resulting file in p // the resulting file encoded in b64 in p
func (fw *FileWatcherReader) Read(p []byte) (n int, err error) { func (fw *FileWatcherReader) Read(p []byte) (n int, err error) {
if err := notify.Watch("./...", fw.eic, notify.InCloseWrite); err != nil { if err := notify.Watch("./...", fw.eic, notify.InCloseWrite); err != nil {
log.Fatal(err) log.Fatal(err)
@ -49,6 +53,8 @@ func (fw *FileWatcherReader) Read(p []byte) (n int, err error) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
// if not json it could be anything so we encode it in b64
if !fw.json{
// base64 stream encoder // base64 stream encoder
b64buf := new(bytes.Buffer) b64buf := new(bytes.Buffer)
b64encoder := base64.NewEncoder(base64.StdEncoding, b64buf) b64encoder := base64.NewEncoder(base64.StdEncoding, b64buf)
@ -59,6 +65,12 @@ func (fw *FileWatcherReader) Read(p []byte) (n int, err error) {
b64buf.WriteString("\n") b64buf.WriteString("\n")
//rreader := bytes.NewReader(fw.buf) //rreader := bytes.NewReader(fw.buf)
n, err = b64buf.Read(p) n, err = b64buf.Read(p)
}else{
fw.buf = append(fw.buf, "\n"...)
rreader := bytes.NewReader(fw.buf)
n, err = rreader.Read(p)
return n, err
}
return n, err return n, err
case <-fw.exit: case <-fw.exit:
// Exiting // Exiting