1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package dmpkg
import (
"encoding/json"
"fmt"
"math"
)
const kMaxBodyLength = math.MaxUint32 - uint64(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
}
|