You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
971 B

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. package p2plib
  2. import (
  3. "encoding/json"
  4. "log"
  5. "time"
  6. )
  7. type Msg struct {
  8. Type string `json:"type"`
  9. Date time.Time `json:"date"`
  10. Content string `json:"content"`
  11. PeersList PeersList `json:"peerslist"`
  12. Data []byte `json:"data"`
  13. }
  14. type Case struct {
  15. Case string
  16. Function func(Peer, Msg)
  17. }
  18. var msgCases map[string]func(Peer, Msg)
  19. func MessageHandler(peer Peer, msg Msg) {
  20. log.Println("[New msg]")
  21. log.Println(msg)
  22. /*for c, caseFunction := range msgCases {
  23. if msg.Type == c {
  24. caseFunction(peer, msg)
  25. }
  26. }*/
  27. msgCases[msg.Type](peer, msg)
  28. }
  29. func (msg *Msg) Construct(msgtype string, msgcontent string) {
  30. msg.Type = msgtype
  31. msg.Content = msgcontent
  32. msg.Date = time.Now()
  33. }
  34. func (msg Msg) ToBytes() []byte {
  35. msgS, err := json.Marshal(msg)
  36. check(err)
  37. l := string(msgS) + "\n"
  38. r := []byte(l)
  39. return r
  40. }
  41. func (msg Msg) CreateFromBytes(bytes []byte) Msg {
  42. err := json.Unmarshal(bytes, &msg)
  43. check(err)
  44. return msg
  45. }