target.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. *
  3. * Copyright 2020 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. */
  18. // Package grpcutil provides a bunch of utility functions to be used across the
  19. // gRPC codebase.
  20. package grpcutil
  21. import (
  22. "strings"
  23. "google.golang.org/grpc/resolver"
  24. )
  25. // split2 returns the values from strings.SplitN(s, sep, 2).
  26. // If sep is not found, it returns ("", "", false) instead.
  27. func split2(s, sep string) (string, string, bool) {
  28. spl := strings.SplitN(s, sep, 2)
  29. if len(spl) < 2 {
  30. return "", "", false
  31. }
  32. return spl[0], spl[1], true
  33. }
  34. // ParseTarget splits target into a resolver.Target struct containing scheme,
  35. // authority and endpoint.
  36. //
  37. // If target is not a valid scheme://authority/endpoint, it returns {Endpoint:
  38. // target}.
  39. func ParseTarget(target string) (ret resolver.Target) {
  40. var ok bool
  41. ret.Scheme, ret.Endpoint, ok = split2(target, "://")
  42. if !ok {
  43. return resolver.Target{Endpoint: target}
  44. }
  45. ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/")
  46. if !ok {
  47. return resolver.Target{Endpoint: target}
  48. }
  49. return ret
  50. }