您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

66 行
1.6 KiB

  1. package packet
  2. // UNSUBSCRIBE represents an UNSUBSCRIBE Packet.
  3. type UNSUBSCRIBE struct {
  4. base
  5. // PacketID is the Packet Identifier of the variable header.
  6. PacketID uint16
  7. // TopicFilters represents a slice of the Topic Filters
  8. TopicFilters [][]byte
  9. }
  10. // setFixedHeader sets the fixed header to the Packet.
  11. func (p *UNSUBSCRIBE) setFixedHeader() {
  12. // Append the first byte to the fixed header.
  13. p.fixedHeader = append(p.fixedHeader, TypeUNSUBSCRIBE<<4|0x02)
  14. // Append the Remaining Length to the fixed header.
  15. p.appendRemainingLength()
  16. }
  17. // setVariableHeader sets the variable header to the Packet.
  18. func (p *UNSUBSCRIBE) setVariableHeader() {
  19. // Append the Packet Identifier to the variable header.
  20. p.variableHeader = append(p.variableHeader, encodeUint16(p.PacketID)...)
  21. }
  22. // setPayload sets the payload to the Packet.
  23. func (p *UNSUBSCRIBE) setPayload() {
  24. // Append each Topic Filter to the payload.
  25. for _, tf := range p.TopicFilters {
  26. // Append the Topic Filter to the payload.
  27. p.payload = appendLenStr(p.payload, tf)
  28. }
  29. }
  30. // NewUNSUBSCRIBE creates and returns an UNSUBSCRIBE Packet.
  31. func NewUNSUBSCRIBE(opts *UNSUBSCRIBEOptions) (Packet, error) {
  32. // Initialize the options.
  33. if opts == nil {
  34. opts = &UNSUBSCRIBEOptions{}
  35. }
  36. // Validate the options.
  37. if err := opts.validate(); err != nil {
  38. return nil, err
  39. }
  40. // Create a SUBSCRIBE Packet.
  41. p := &UNSUBSCRIBE{
  42. PacketID: opts.PacketID,
  43. TopicFilters: opts.TopicFilters,
  44. }
  45. // Set the variable header to the Packet.
  46. p.setVariableHeader()
  47. // Set the payload to the Packet.
  48. p.setPayload()
  49. // Set the Fixed header to the Packet.
  50. p.setFixedHeader()
  51. // Return the Packet.
  52. return p, nil
  53. }