I'm working on a library for handling a wire protocol that sends specific messages where elements could be represented by bits in a byte, a fixed byte or word, or even a variable array of bytes. The methods in encoding/binary sounds great for my purpose except they only work with fixed length fields. It is important for my project that each unique message has a specific struct associated with it.
My first approach was to jimmy a struct tag and custom Marshal/Unmarshal methods that handles bit fields and slices via reflect. The prototype works, and could be generalized to a separate library, but I don't want to recreate the wheel.
Does anyone know of an existing library/pattern?
评论:
connor4312:
fncypants:Protocol buffers and/or msgpack sounds a lot like what you're doing here, you may be able to use those off the shelf if you have control over the other consumer of the protocol.
rchrome:Thanks, but my client is the consumer of the wire protocol so I don't get to define the serialization representation. Instead, it is parsing a series of bytes as a fixed structure describing fields that may be bit flags, bytes, words, or an array of those.
You can write binaries using net/http.
Here is an example where I convert a struct to binary representation:
https://github.com/amitu/rtime/blob/master/src/rtime/boltdb.go#L267-L282
Let me know if you have questions or example is not clear.
