Merge pull request #32 from jwetzell/feat/json-encode

add processor to encode json bytes
This commit is contained in:
Joel Wetzell
2025-12-28 16:27:12 -06:00
committed by GitHub
2 changed files with 87 additions and 0 deletions

View File

@@ -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
},
})
}

View File

@@ -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)
}
})
}
}