internal.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. // Package internal contains functions/structs shared by xds
  18. // balancers/resolvers.
  19. package internal
  20. import (
  21. "encoding/json"
  22. "fmt"
  23. )
  24. // LocalityID is xds.Locality without XXX fields, so it can be used as map
  25. // keys.
  26. //
  27. // xds.Locality cannot be map keys because one of the XXX fields is a slice.
  28. type LocalityID struct {
  29. Region string `json:"region,omitempty"`
  30. Zone string `json:"zone,omitempty"`
  31. SubZone string `json:"subZone,omitempty"`
  32. }
  33. // ToString generates a string representation of LocalityID by marshalling it into
  34. // json. Not calling it String() so printf won't call it.
  35. func (l LocalityID) ToString() (string, error) {
  36. b, err := json.Marshal(l)
  37. if err != nil {
  38. return "", err
  39. }
  40. return string(b), nil
  41. }
  42. // LocalityIDFromString converts a json representation of locality, into a
  43. // LocalityID struct.
  44. func LocalityIDFromString(s string) (ret LocalityID, _ error) {
  45. err := json.Unmarshal([]byte(s), &ret)
  46. if err != nil {
  47. return LocalityID{}, fmt.Errorf("%s is not a well formatted locality ID, error: %v", s, err)
  48. }
  49. return ret, nil
  50. }