Skip to content

Commit

Permalink
adds jsonwriter
Browse files Browse the repository at this point in the history
  • Loading branch information
gosom committed Sep 8, 2023
1 parent e3ac237 commit b81ce85
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions adapters/writers/jsonwriter/jsonwriter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package jsonwriter

import (
"context"
"encoding/json"
"io"

"github.com/gosom/scrapemate"
)

var _ scrapemate.ResultWriter = (*jsonWriter)(nil)

type jsonWriter struct {
enc *json.Encoder
}

func NewJSONWriter(w io.Writer) scrapemate.ResultWriter {
enc := json.NewEncoder(w)
return &jsonWriter{enc: enc}
}

func (c *jsonWriter) Run(_ context.Context, in <-chan scrapemate.Result) error {
for result := range in {
items := asSlice(result.Data)

for i := range items {
if err := c.enc.Encode(items[i]); err != nil {
return err
}
}
}

return nil
}

func asSlice(t any) []any {
isSlice, ok := t.([]any)
if ok {
return isSlice
}

var elements []any

elements = append(elements, t)

return elements
}

0 comments on commit b81ce85

Please sign in to comment.