first commit
This commit is contained in:
44
output/writer/output.go
Normal file
44
output/writer/output.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package writer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gitoa.ru/go-4devs/console/output"
|
||||
)
|
||||
|
||||
func Stderr() output.Output {
|
||||
return New(os.Stderr, String)
|
||||
}
|
||||
|
||||
func Stdout() output.Output {
|
||||
return New(os.Stdout, String)
|
||||
}
|
||||
|
||||
func Buffer(buf *bytes.Buffer) output.Output {
|
||||
return New(buf, String)
|
||||
}
|
||||
|
||||
func String(_ output.Verbosity, msg string, kv ...output.KeyValue) string {
|
||||
if len(kv) > 0 {
|
||||
newline := ""
|
||||
if msg[len(msg)-1:] == "\n" {
|
||||
newline = "\n"
|
||||
}
|
||||
|
||||
return "msg=\"" + strings.TrimSpace(msg) + "\", " + output.KeyValues(kv).String() + newline
|
||||
|
||||
}
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
func New(w io.Writer, format func(verb output.Verbosity, msg string, kv ...output.KeyValue) string) output.Output {
|
||||
return func(ctx context.Context, verb output.Verbosity, msg string, kv ...output.KeyValue) (int, error) {
|
||||
return fmt.Fprint(w, format(verb, msg, kv...))
|
||||
}
|
||||
}
|
||||
49
output/writer/output_test.go
Normal file
49
output/writer/output_test.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package writer_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"gitoa.ru/go-4devs/console/output"
|
||||
"gitoa.ru/go-4devs/console/output/writer"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
buf := bytes.Buffer{}
|
||||
wr := writer.New(&buf, writer.String)
|
||||
|
||||
cases := map[string]struct {
|
||||
ex string
|
||||
kv []output.KeyValue
|
||||
}{
|
||||
"message": {
|
||||
ex: "message",
|
||||
},
|
||||
"msg with kv": {
|
||||
ex: "msg=\"msg with kv\", string key=\"string value\", bool key=\"false\", int key=\"42\"",
|
||||
kv: []output.KeyValue{
|
||||
output.String("string key", "string value"),
|
||||
output.Bool("bool key", false),
|
||||
output.Int("int key", 42),
|
||||
},
|
||||
},
|
||||
"msg with newline \n": {
|
||||
ex: "msg=\"msg with newline\", int=\"42\"\n",
|
||||
kv: []output.KeyValue{
|
||||
output.Int("int", 42),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for msg, data := range cases {
|
||||
wr.InfoKV(ctx, msg, data.kv...)
|
||||
|
||||
if data.ex != buf.String() {
|
||||
t.Errorf("message not equals expext:%s, got:%s", data.ex, buf.String())
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user