summaryrefslogtreecommitdiff
path: root/data/datasource_stdin.go
blob: 13bb5fa4c9e0c57fd96676a165e83ab04979785e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package data

import (
	"context"
	"fmt"
	"io"
	"os"
)

func readStdin(ctx context.Context, _ *Source, _ ...string) ([]byte, error) {
	stdin := stdinFromContext(ctx)

	b, err := io.ReadAll(stdin)
	if err != nil {
		return nil, fmt.Errorf("can't read %s: %w", stdin, err)
	}
	return b, nil
}

type stdinCtxKey struct{}

func ContextWithStdin(ctx context.Context, r io.Reader) context.Context {
	return context.WithValue(ctx, stdinCtxKey{}, r)
}

func stdinFromContext(ctx context.Context) io.Reader {
	if r, ok := ctx.Value(stdinCtxKey{}).(io.Reader); ok {
		return r
	}

	return os.Stdin
}