diff --git a/internal/processor/json-encode.go b/internal/processor/json-encode.go new file mode 100644 index 0000000..acfd12f --- /dev/null +++ b/internal/processor/json-encode.go @@ -0,0 +1,42 @@ +package processor + +import ( + "bytes" + "context" + "encoding/json" + + "github.com/jwetzell/showbridge-go/internal/config" +) + +type JsonEncode struct { + config config.ProcessorConfig +} + +func (je *JsonEncode) Process(ctx context.Context, payload any) (any, error) { + var payloadBuffer bytes.Buffer + + err := json.NewEncoder(&payloadBuffer).Encode(payload) + + if err != nil { + return nil, err + } + + payloadBytes := payloadBuffer.Bytes() + + payloadBytes = payloadBytes[0 : len(payloadBytes)-1] + + return payloadBytes, nil +} + +func (je *JsonEncode) Type() string { + return je.config.Type +} + +func init() { + RegisterProcessor(ProcessorRegistration{ + Type: "json.encode", + New: func(config config.ProcessorConfig) (Processor, error) { + return &JsonEncode{config: config}, nil + }, + }) +} diff --git a/internal/processor/json-encode_test.go b/internal/processor/json-encode_test.go new file mode 100644 index 0000000..501f0c4 --- /dev/null +++ b/internal/processor/json-encode_test.go @@ -0,0 +1,45 @@ +package processor_test + +import ( + "slices" + "testing" + + "github.com/jwetzell/osc-go" + "github.com/jwetzell/showbridge-go/internal/processor" +) + +func TestGoodJsonEncode(t *testing.T) { + stringEncoder := processor.JsonEncode{} + tests := []struct { + processor processor.Processor + name string + payload any + expected []byte + }{ + { + processor: &stringEncoder, + name: "hello", + payload: osc.OSCMessage{ + Address: "/hello", + }, + expected: []byte("{\"address\":\"/hello\",\"args\":null}"), + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got, err := test.processor.Process(t.Context(), test.payload) + + gotBytes, ok := got.([]byte) + if !ok { + t.Fatalf("json.encode returned a %T payload: %s", got, got) + } + if err != nil { + t.Fatalf("json.encode failed: %s", err) + } + if !slices.Equal(gotBytes, test.expected) { + t.Fatalf("json.encode got %x, expected %s", got, test.expected) + } + }) + } +}