replyParser.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package goSam
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // The Possible Results send by SAM
  7. const (
  8. ResultOk = "OK" //Operation completed successfully
  9. ResultCantReachPeer = "CANT_REACH_PEER" //The peer exists, but cannot be reached
  10. ResultDuplicatedID = "DUPLICATED_ID" //If the nickname is already associated with a session :
  11. ResultDuplicatedDest = "DUPLICATED_DEST" //The specified Destination is already in use
  12. ResultI2PError = "I2P_ERROR" //A generic I2P error (e.g. I2CP disconnection, etc.)
  13. ResultInvalidKey = "INVALID_KEY" //The specified key is not valid (bad format, etc.)
  14. ResultKeyNotFound = "KEY_NOT_FOUND" //The naming system can't resolve the given name
  15. ResultPeerNotFound = "PEER_NOT_FOUND" //The peer cannot be found on the network
  16. ResultTimeout = "TIMEOUT" // Timeout while waiting for an event (e.g. peer answer)
  17. )
  18. // A ReplyError is a custom error type, containing the Result and full Reply
  19. type ReplyError struct {
  20. Result string
  21. Reply *Reply
  22. }
  23. func (r ReplyError) Error() string {
  24. return fmt.Sprintf("ReplyError: Result:%s - Reply:%+v", r.Result, r.Reply)
  25. }
  26. // Reply is the parsed result of a SAM command, containing a map of all the key-value pairs
  27. type Reply struct {
  28. Topic string
  29. Type string
  30. Pairs map[string]string
  31. }
  32. func parseReply(line string) (*Reply, error) {
  33. line = strings.TrimSpace(line)
  34. parts := strings.Split(line, " ")
  35. if len(parts) < 3 {
  36. return nil, fmt.Errorf("Malformed Reply.\n%s\n", line)
  37. }
  38. r := &Reply{
  39. Topic: parts[0],
  40. Type: parts[1],
  41. Pairs: make(map[string]string, len(parts)-2),
  42. }
  43. for _, v := range parts[2:] {
  44. kvPair := strings.SplitN(v, "=", 2)
  45. if kvPair != nil {
  46. if len(kvPair) != 2 {
  47. return nil, fmt.Errorf("Malformed key-value-pair.\n%s\n", kvPair)
  48. }
  49. }
  50. r.Pairs[kvPair[0]] = kvPair[1]
  51. }
  52. return r, nil
  53. }