github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/util/net/port_split.go (about)

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