This repository has been archived by the owner on May 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage_type.go
87 lines (75 loc) · 2.12 KB
/
message_type.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package cap
import (
"encoding/json"
"encoding/xml"
"errors"
"strings"
)
const (
MessageTypeUnknown = iota
MessageTypeAlert
MessageTypeUpdate
MessageTypeCancel
MessageTypeAck
MessageTypeError
)
type MessageType int
// UnmarshalString unmarshals the string into a MessageType value.
func (messageType *MessageType) UnmarshalString(str string) error {
str = strings.ToLower(str)
if str == "alert" {
*messageType = MessageTypeAlert
} else if str == "update" {
*messageType = MessageTypeUpdate
} else if str == "cancel" {
*messageType = MessageTypeCancel
} else if str == "ack" {
*messageType = MessageTypeAck
} else if str == "error" {
*messageType = MessageTypeError
} else {
return errors.New("Unknown MessageType value")
}
return nil
}
// UnmarshalXML unmarshals the XML into a MessageType value.
func (messageType *MessageType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var str string
if err := d.DecodeElement(&str, &start); err != nil {
return err
}
return messageType.UnmarshalString(str)
}
// UnmarshalJSON unmarshals the XML into a MessageType value.
func (messageType *MessageType) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return err
}
return messageType.UnmarshalString(str)
}
// MarshalJSON returns the string version of the message type.
func (messageType *MessageType) MarshalJSON() ([]byte, error) {
return json.Marshal(messageType.String())
}
// MarshalXML returns the string version of the message type.
func (messageType *MessageType) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return e.EncodeElement(messageType.String(), start)
}
// String returns a MessageType as a string
func (messageType MessageType) String() string {
if messageType == MessageTypeAlert {
return "Alert"
} else if messageType == MessageTypeUpdate {
return "Update"
} else if messageType == MessageTypeCancel {
return "Cancel"
} else if messageType == MessageTypeAck {
return "Ack"
} else if messageType == MessageTypeError {
return "Error"
} else if messageType == MessageTypeUnknown {
return "Unknown"
}
return ""
}