utils.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package myth
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. )
  6. const (
  7. _ = iota
  8. // KB kilo byte
  9. KB int = 1 << (10 * iota)
  10. // MB mega byte
  11. MB
  12. // GB giga byte
  13. GB
  14. // TB tera byte
  15. TB
  16. // PB peta byte
  17. PB
  18. )
  19. // M is a shortcut for map[string]interface{}
  20. type M map[string]interface{}
  21. // NewM new map[string]interface{}
  22. func NewM() M {
  23. return make(map[string]interface{})
  24. }
  25. // Set key-value to map[string]interface{}
  26. func (m M) Set(k string, v interface{}) {
  27. m[k] = v
  28. }
  29. // Get value from map[string]interface{}
  30. func (m M) Get(k string) (v interface{}, ok bool) {
  31. v, ok = m[k]
  32. return
  33. }
  34. // String map to json string
  35. func (m M) String() string {
  36. bs, _ := json.Marshal(m)
  37. return string(bs)
  38. }
  39. // Bytes map to json bytes
  40. func (m M) Bytes() []byte {
  41. bs, _ := json.Marshal(m)
  42. return bs
  43. }
  44. // MarshalXML allows type Map to be used with xml.Marshal.
  45. func (m M) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  46. start.Name = xml.Name{
  47. Space: "",
  48. Local: "map",
  49. }
  50. if err := e.EncodeToken(start); err != nil {
  51. return err
  52. }
  53. for key, value := range m {
  54. elem := xml.StartElement{
  55. Name: xml.Name{Space: "", Local: key},
  56. Attr: []xml.Attr{},
  57. }
  58. if err := e.EncodeElement(value, elem); err != nil {
  59. return err
  60. }
  61. }
  62. return e.EncodeToken(xml.EndElement{Name: start.Name})
  63. }