summaryrefslogtreecommitdiff
path: root/danmaku/dmpkg/raw.go
diff options
context:
space:
mode:
authorKeuin <[email protected]>2022-09-07 02:48:46 +0800
committerKeuin <[email protected]>2022-09-07 02:48:46 +0800
commit8e15d802865ed57db0018c15ea5559c8bd44c01f (patch)
tree48f4632a1ad044bd7f7f8da3ebe2bb03ab4ca6fe /danmaku/dmpkg/raw.go
parent88234ca8fffc4e120adbe0d38071b625ad2f43c7 (diff)
First working version. Just a POC.
Diffstat (limited to 'danmaku/dmpkg/raw.go')
-rw-r--r--danmaku/dmpkg/raw.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/danmaku/dmpkg/raw.go b/danmaku/dmpkg/raw.go
new file mode 100644
index 0000000..1cbd12e
--- /dev/null
+++ b/danmaku/dmpkg/raw.go
@@ -0,0 +1,47 @@
+package dmpkg
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+)
+
+const kMaxBodyLength = math.MaxUint32 - kHeaderLength
+
+// NewPlainExchange creates a new exchange with raw body specified.
+// body: a struct or a raw string
+func NewPlainExchange(operation Operation, body interface{}) (exc DanmakuExchange, err error) {
+ var bodyData []byte
+
+ // convert body to []byte
+ if _, ok := body.(string); ok {
+ // a string
+ bodyData = []byte(body.(string))
+ } else if _, ok := body.([]byte); ok {
+ // a []byte
+ copy(bodyData, body.([]byte))
+ } else {
+ // a JSON struct
+ bodyData, err = json.Marshal(body)
+ if err != nil {
+ return
+ }
+ }
+
+ length := uint64(kHeaderLength + len(bodyData))
+ if length > kMaxBodyLength {
+ err = fmt.Errorf("body is too large (> %d)", kMaxBodyLength)
+ return
+ }
+ exc = DanmakuExchange{
+ DanmakuExchangeHeader: DanmakuExchangeHeader{
+ Length: uint32(length),
+ HeaderLength: kHeaderLength,
+ ProtocolVer: ProtoPlainJson,
+ Operation: operation,
+ SequenceId: kSequenceId,
+ },
+ Body: bodyData,
+ }
+ return
+}