mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-26 21:05:30 +00:00
Merge pull request #32 from jwetzell/feat/json-encode
add processor to encode json bytes
This commit is contained in:
42
internal/processor/json-encode.go
Normal file
42
internal/processor/json-encode.go
Normal 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
|
||||
},
|
||||
})
|
||||
}
|
||||
45
internal/processor/json-encode_test.go
Normal file
45
internal/processor/json-encode_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user