udp.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package udp
  15. import (
  16. "encoding/base64"
  17. "encoding/json"
  18. "net"
  19. )
  20. type UdpPacket struct {
  21. Content []byte `json:"-"`
  22. Src *net.UDPAddr `json:"-"`
  23. Dst *net.UDPAddr `json:"-"`
  24. EncodeContent string `json:"content"`
  25. SrcStr string `json:"src"`
  26. DstStr string `json:"dst"`
  27. }
  28. func NewUdpPacket(content []byte, src, dst *net.UDPAddr) *UdpPacket {
  29. up := &UdpPacket{
  30. Src: src,
  31. Dst: dst,
  32. EncodeContent: base64.StdEncoding.EncodeToString(content),
  33. SrcStr: src.String(),
  34. DstStr: dst.String(),
  35. }
  36. return up
  37. }
  38. // parse one udp packet struct to bytes
  39. func (up *UdpPacket) Pack() []byte {
  40. b, _ := json.Marshal(up)
  41. return b
  42. }
  43. // parse from bytes to UdpPacket struct
  44. func (up *UdpPacket) UnPack(packet []byte) error {
  45. err := json.Unmarshal(packet, &up)
  46. if err != nil {
  47. return err
  48. }
  49. up.Content, err = base64.StdEncoding.DecodeString(up.EncodeContent)
  50. if err != nil {
  51. return err
  52. }
  53. up.Src, err = net.ResolveUDPAddr("udp", up.SrcStr)
  54. if err != nil {
  55. return err
  56. }
  57. up.Dst, err = net.ResolveUDPAddr("udp", up.DstStr)
  58. if err != nil {
  59. return err
  60. }
  61. return nil
  62. }