port_split.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package net
  14. import (
  15. "strings"
  16. "k8s.io/kubernetes/pkg/util/sets"
  17. )
  18. var validSchemes = sets.NewString("http", "https", "")
  19. // SplitSchemeNamePort takes a string of the following forms:
  20. // * "<name>", returns "", "<name>","", true
  21. // * "<name>:<port>", returns "", "<name>","<port>",true
  22. // * "<scheme>:<name>:<port>", returns "<scheme>","<name>","<port>",true
  23. //
  24. // Name must be non-empty or valid will be returned false.
  25. // Scheme must be "http" or "https" if specified
  26. // Port is returned as a string, and it is not required to be numeric (could be
  27. // used for a named port, for example).
  28. func SplitSchemeNamePort(id string) (scheme, name, port string, valid bool) {
  29. parts := strings.Split(id, ":")
  30. switch len(parts) {
  31. case 1:
  32. name = parts[0]
  33. case 2:
  34. name = parts[0]
  35. port = parts[1]
  36. case 3:
  37. scheme = parts[0]
  38. name = parts[1]
  39. port = parts[2]
  40. default:
  41. return "", "", "", false
  42. }
  43. if len(name) > 0 && validSchemes.Has(scheme) {
  44. return scheme, name, port, true
  45. } else {
  46. return "", "", "", false
  47. }
  48. }
  49. // JoinSchemeNamePort returns a string that specifies the scheme, name, and port:
  50. // * "<name>"
  51. // * "<name>:<port>"
  52. // * "<scheme>:<name>:<port>"
  53. // None of the parameters may contain a ':' character
  54. // Name is required
  55. // Scheme must be "", "http", or "https"
  56. func JoinSchemeNamePort(scheme, name, port string) string {
  57. if len(scheme) > 0 {
  58. // Must include three segments to specify scheme
  59. return scheme + ":" + name + ":" + port
  60. }
  61. if len(port) > 0 {
  62. // Must include two segments to specify port
  63. return name + ":" + port
  64. }
  65. // Return name alone
  66. return name
  67. }