utils.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // Map is a shortcut for map[string]interface{}
  20. type Map map[string]interface{}
  21. // NewMap new map
  22. func NewMap() Map {
  23. return make(map[string]interface{})
  24. }
  25. // String map to json string
  26. func (m Map) String() string {
  27. bs, _ := json.Marshal(m)
  28. return string(bs)
  29. }
  30. // Bytes map to json bytes
  31. func (m Map) Bytes() []byte {
  32. bs, _ := json.Marshal(m)
  33. return bs
  34. }
  35. // MarshalXML allows type Map to be used with xml.Marshal.
  36. func (m Map) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  37. start.Name = xml.Name{
  38. Space: "",
  39. Local: "map",
  40. }
  41. if err := e.EncodeToken(start); err != nil {
  42. return err
  43. }
  44. for key, value := range m {
  45. elem := xml.StartElement{
  46. Name: xml.Name{Space: "", Local: key},
  47. Attr: []xml.Attr{},
  48. }
  49. if err := e.EncodeElement(value, elem); err != nil {
  50. return err
  51. }
  52. }
  53. return e.EncodeToken(xml.EndElement{Name: start.Name})
  54. }