Split message into multiple

Hello all,

I am very new to GO and so I would be really grateful if you can guide me with this:

This is the formatter.go file:

package formatters
import (
	"go.thethings.network/lorawan-stack/pkg/ttnpb"
)

// Formatter formats upstream and downstream messages.
type Formatter interface {
	FromUp(*ttnpb.ApplicationUp) ([]byte, error)
	ToDownlinks([]byte) (*ttnpb.ApplicationDownlinks, error)
	ToDownlinkQueueRequest([]byte) (*ttnpb.DownlinkQueueRequest, error)
}

and this is the json.go file:

package formatters

import (
	"go.thethings.network/lorawan-stack/pkg/jsonpb"
	"go.thethings.network/lorawan-stack/pkg/ttnpb"
)

type json struct {
}

func (json) FromUp(msg *ttnpb.ApplicationUp) ([]byte, error) {
	return jsonpb.TTN().Marshal(msg)
}

func (json) ToDownlinks(data []byte) (*ttnpb.ApplicationDownlinks, error) {
	res := &ttnpb.ApplicationDownlinks{}
	if err := jsonpb.TTN().Unmarshal(data, &res); err != nil {
		return nil, err
	}
	return res, nil
}

func (json) ToDownlinkQueueRequest(data []byte) (*ttnpb.DownlinkQueueRequest, error) {
	res := &ttnpb.DownlinkQueueRequest{}
	if err := jsonpb.TTN().Unmarshal(data, &res); err != nil {
		return nil, err
	}
	return res, nil
}

// JSON is a formatter that uses JSON marshaling.
var JSON Formatter = &json{}

Now, in the *ttnpb.ApplicationUp I would like to return [][]byte instead of just []byte. How can I do that?
Thank you so much in advance.

I guess it is in the method FromUp that you want to return a [][]byte instead of []byte.
What you could do is split the returned byte slice. What you didn’t say in your question is how you want to split the size ? Do you want fixed size slices ? What size ? Do you want another rule ?

Splitting a slice in smaller slices is trivial. Consider the code below that split a slice in smaller slices of fixed size (sz), except the last.

func split(data []byte, sz int) [][]byte {
    var r = make([][]byte, 0, (len(data)+sz-1)/sz)
    var i int
    for i = 0; i+sz < len(data); i += sz {
        r = append(r, data[i:i+sz])
    }
    return append(r, data[i:])
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.