/core/networking/vswitch/uuid.go

https://gitlab.com/silenteh/gantryos · Go · 57 lines · 39 code · 12 blank · 6 comment · 8 complexity · 6401afcd54e6e8bb9e78383103b83f66 MD5 · raw file

  1. package vswitch
  2. import (
  3. "encoding/json"
  4. "errors"
  5. //"fmt"
  6. //"reflect"
  7. "regexp"
  8. )
  9. type UUID struct {
  10. GoUuid string `json:"uuid"`
  11. }
  12. // <set> notation requires special marshaling
  13. func (u UUID) MarshalJSON() ([]byte, error) {
  14. var uuidSlice []string
  15. err := u.validateUUID()
  16. if err == nil {
  17. uuidSlice = []string{"uuid", u.GoUuid}
  18. } else {
  19. uuidSlice = []string{"named-uuid", u.GoUuid}
  20. }
  21. return json.Marshal(uuidSlice)
  22. }
  23. func (u *UUID) UnmarshalJSON(b []byte) (err error) {
  24. var ovsUuid []string
  25. if err := json.Unmarshal(b, &ovsUuid); err == nil {
  26. u.GoUuid = ovsUuid[1]
  27. }
  28. return err
  29. }
  30. func (u UUID) validateUUID() error {
  31. if len(u.GoUuid) != 36 {
  32. return errors.New("uuid exceeds 36 characters")
  33. }
  34. var validUUID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
  35. if !validUUID.MatchString(u.GoUuid) {
  36. return errors.New("uuid does not match regexp")
  37. }
  38. return nil
  39. }
  40. func newNamedUUID(id string) []string {
  41. //uuidMap := make(map[string]string)
  42. //uuidMap["named-uuid"] = id
  43. //return []map[string]string{uuidMap}
  44. return []string{"named-uuid", id}
  45. }