// getEndpointURL - construct a new endpoint.
165163
func getEndpointURL(endpoint string, secure bool) (*url.URL, error) {
	if strings.Contains(endpoint, ":") {
		host, _, err := net.SplitHostPort(endpoint)
		if err != nil {
			return nil, err
		}
		if !s3utils.IsValidIP(host) && !s3utils.IsValidDomain(host) {
			msg := "Endpoint: " + endpoint + " does not follow ip address or domain name standards."
			return nil, ErrInvalidArgument(msg)
		}
	} else {
		if !s3utils.IsValidIP(endpoint) && !s3utils.IsValidDomain(endpoint) {
			msg := "Endpoint: " + endpoint + " does not follow ip address or domain name standards."
			return nil, ErrInvalidArgument(msg)
		}
	}
	// If secure is false, use 'http' scheme.
	scheme := "https"
	if !secure {
		scheme = "http"
	}

	// Construct a secured endpoint URL.
	endpointURLStr := scheme + "://" + endpoint
	endpointURL, err := url.Parse(endpointURLStr)
	if err != nil {
		return nil, err
	}

	// Validate incoming endpoint URL.
	if err := isValidEndpointURL(*endpointURL); err != nil {
		return nil, err
	}
	return endpointURL, nil
}
1129882
func WithEndpointBase(endpointBase string) ClientOption {
	return func(client *Client) error {
		u, err := url.ParseRequestURI(endpointBase)
		if err != nil {
			return err
		}
		client.endpointBase = u
		return nil
	}
}
718150
func NewEndpoint(arg string) (ep Endpoint, e error) {
	// isEmptyPath - check whether given path is not empty.
	isEmptyPath := func(path string) bool {
		return path == "" || path == "/" || path == `\`
	}

	if isEmptyPath(arg) {
		return ep, fmt.Errorf("empty or root endpoint is not supported")
	}

	var isLocal bool
	var host string
	u, err := url.Parse(arg)
	if err == nil && u.Host != "" {
		// URL style of endpoint.
		// Valid URL style endpoint is
		// - Scheme field must contain "http" or "https"
		// - All field should be empty except Host and Path.
		if !((u.Scheme == "http" || u.Scheme == "https") &&
			u.User == nil && u.Opaque == "" && !u.ForceQuery && u.RawQuery == "" && u.Fragment == "") {
			return ep, fmt.Errorf("invalid URL endpoint format")
		}

		var port string
		host, port, err = net.SplitHostPort(u.Host)
		if err != nil {
			if !strings.Contains(err.Error(), "missing port in address") {
				return ep, fmt.Errorf("invalid URL endpoint format: %s", err)
			}

			host = u.Host
		} else {
			var p int
			p, err = strconv.Atoi(port)
			if err != nil {
				return ep, fmt.Errorf("invalid URL endpoint format: invalid port number")
			} else if p < 1 || p > 65535 {
				return ep, fmt.Errorf("invalid URL endpoint format: port number must be between 1 to 65535")
			}
		}
		if i := strings.Index(host, "%"); i > -1 {
			host = host[:i]
		}

		if host == "" {
			return ep, fmt.Errorf("invalid URL endpoint format: empty host name")
		}

		// As this is path in the URL, we should use path package, not filepath package.
		// On MS Windows, filepath.Clean() converts into Windows path style ie `/foo` becomes `\foo`
		u.Path = path.Clean(u.Path)
		if isEmptyPath(u.Path) {
			return ep, fmt.Errorf("empty or root path is not supported in URL endpoint")
		}

		// On windows having a preceding "/" will cause problems, if the
		// command line already has C:/<export-folder/ in it. Final resulting
		// path on windows might become C:/C:/ this will cause problems
		// of starting minio server properly in distributed mode on windows.
		// As a special case make sure to trim the separator.

		// NOTE: It is also perfectly fine for windows users to have a path
		// without C:/ since at that point we treat it as relative path
		// and obtain the full filesystem path as well. Providing C:/
		// style is necessary to provide paths other than C:/,
		// such as F:/, D:/ etc.
		//
		// Another additional benefit here is that this style also
		// supports providing \\host\share support as well.
		if runtime.GOOS == globalWindowsOSName {
			if filepath.VolumeName(u.Path[1:]) != "" {
				u.Path = u.Path[1:]
			}
		}

	} else {
		// Only check if the arg is an ip address and ask for scheme since its absent.
		// localhost, example.com, any FQDN cannot be disambiguated from a regular file path such as
		// /mnt/export1. So we go ahead and start the minio server in FS modes in these cases.
		if isHostIP(arg) {
			return ep, fmt.Errorf("invalid URL endpoint format: missing scheme http or https")
		}
		u = &url.URL{Path: path.Clean(arg)}
		isLocal = true
	}

	return Endpoint{
		URL:      u,
		IsLocal:  isLocal,
		HostName: host,
	}, nil
}
367537
func (auth *v2Auth) endpointUrl(Type string, endpointType EndpointType) string {
	for _, catalog := range auth.Auth.Access.ServiceCatalog {
		if catalog.Type == Type {
			for _, endpoint := range catalog.Endpoints {
				if auth.Region == "" || (auth.Region == endpoint.Region) {
					switch endpointType {
					case EndpointTypeInternal:
						return endpoint.InternalUrl
					case EndpointTypePublic:
						return endpoint.PublicUrl
					case EndpointTypeAdmin:
						return endpoint.AdminUrl
					default:
						return ""
					}
				}
			}
		}
	}
	return ""
}
141272
func (c *S3Cli) S3Endpoint() string {
	if c.Host == "" {
		return ""
	}
	if c.Port != 0 {
		return fmt.Sprintf("%s:%d", c.Host, c.Port)
	}
	return c.Host
}
858878
func (lbc *loadBalancerController) getEndpoints(
	s *api.Service, servicePort *api.ServicePort) (endpoints []string) {
	ep, err := lbc.epLister.GetServiceEndpoints(s)
	if err != nil {
		return
	}

	// The intent here is to create a union of all subsets that match a targetPort.
	// We know the endpoint already matches the service, so all pod ips that have
	// the target port are capable of service traffic for it.
	for _, ss := range ep.Subsets {
		for _, epPort := range ss.Ports {
			var targetPort int
			switch servicePort.TargetPort.Type {
			case intstr.Int:
				if epPort.Port == getTargetPort(servicePort) {
					targetPort = epPort.Port
				}
			case intstr.String:
				if epPort.Name == servicePort.TargetPort.StrVal {
					targetPort = epPort.Port
				}
			}
			if targetPort == 0 {
				continue
			}
			for _, epAddress := range ss.Addresses {
				endpoints = append(endpoints, fmt.Sprintf("%v:%v", epAddress.IP, targetPort))
			}
		}
	}
	return
}
739979
func NewGetEndpointIDConfig(ctx *middleware.Context, handler GetEndpointIDConfigHandler) *GetEndpointIDConfig {
	return &GetEndpointIDConfig{Context: ctx, Handler: handler}
}
756859
func getEndpoints(ctx *app.ListEndpointsContext, fileHandler asseter) (*app.Endpoints, error) {
	// Get an unmarshal swagger specification
	swaggerJSON, err := fileHandler.Asset(embeddedSwaggerSpecFile)
	if err != nil {
		// TODO(tinakurian): fix error handling
		return nil, errors.NewNotFoundError("file", embeddedSwaggerSpecFile)
	}

	var result map[string]interface{}
	err = json.Unmarshal(swaggerJSON, &result)
	if err != nil {
		return nil, errs.Wrapf(err, `unable to unmarshal the file with id "%s"`, embeddedSwaggerSpecFile)
	}

	// Get and iterate over paths from swagger specification.
	swaggerPaths, ok := result["paths"]
	if !ok {
		return nil, errors.NewInternalErrorFromString(`failed to find field "paths" in swagger specification`)
	}

	swaggerPathz, ok := swaggerPaths.(map[string]interface{})
	if !ok {
		return nil, errors.NewInternalErrorFromString(`unable to assert concrete type map for field "paths" in swagger specification`)
	}

	basePathObj, ok := result["basePath"]
	if !ok {
		return nil, errors.NewInternalErrorFromString(`failed to find field "basePath" in swagger specification`)
	}

	basePath, ok := basePathObj.(string)
	if !ok {
		return nil, errors.NewInternalErrorFromString(`unable to assert concrete type string for field "basePath" in swagger specification`)
	}

	absoluteBasePath := rest.AbsoluteURL(ctx.Request, basePath)

	// the namedPaths map stores paths as key and URLs as values
	namedPaths := make(map[string]interface{})
	for path, swaggerPath := range swaggerPathz {

		// Currently not supporting endpoints that contain parameters.
		if !strings.Contains(path, "{") {
			key := path

			pathsObj, ok := swaggerPath.(map[string]interface{})
			if !ok {
				return nil, errors.NewInternalErrorFromString("unable to assert concrete type map for field `paths` in swagger specification")
			}

			// Get the x-tag value. If the tag exists, use it as path name.
			xtagObj, ok := pathsObj["x-tag"]
			if ok {
				xtag, ok := xtagObj.(string)
				if !ok {
					return nil, errors.NewInternalErrorFromString("unable to assert concrete type string for field `x-tag` in swagger specification")
				}

				key = xtag
			}

			// cleanup the key to conform to JSONAPI member names
			key = jsonapi.FormatMemberName(key)

			// Set the related field and link objects for each name.
			if key != "" {
				namedPaths[key] = map[string]interface{}{
					"links": map[string]string{
						"related": absoluteBasePath + path,
					},
				}
			}
		}
	}

	return &app.Endpoints{
		Type:          "endpoints",
		ID:            uuid.NewV4(),
		Relationships: namedPaths,
		Links: &app.GenericLinks{
			Self: ptr.String(absoluteBasePath),
		},
	}, nil
}
464899
func (a *InternalAPIEngine) getURL(arg APIArg) url.URL {
	u := *a.config.URL
	var path string
	if len(a.config.Prefix) > 0 {
		path = a.config.Prefix
	} else {
		path = APIURIPathPrefix
	}
	u.Path = path + "/" + arg.Endpoint + ".json"
	return u
}
585727
func FindLinkEndpoint(id tcpip.LinkEndpointID) LinkEndpoint {
	linkEPMu.RLock()
	defer linkEPMu.RUnlock()

	return linkEndpoints[id]
}
725966
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter {
	return NamedTypeGetter{
		name:       name,
		typeGetter: getter,
	}
}
1061575
func (a *Application) defaultEndpointBindings() (map[string]string, error) {
	if a.doc.CharmURL == nil {
		return map[string]string{}, nil
	}

	appCharm, _, err := a.Charm()
	if err != nil {
		return nil, errors.Trace(err)
	}

	return DefaultEndpointBindingsForCharm(appCharm.Meta()), nil
}
185443
func (network *HostComputeNetwork) CreateEndpoint(endpoint *HostComputeEndpoint) (*HostComputeEndpoint, error) {
	isRemote := endpoint.Flags&EndpointFlagsRemoteEndpoint != 0
	logrus.Debugf("hcn::HostComputeNetwork::CreatEndpoint, networkId=%s remote=%t", network.Id, isRemote)

	endpoint.HostComputeNetwork = network.Id
	endpointSettings, err := json.Marshal(endpoint)
	if err != nil {
		return nil, err
	}
	newEndpoint, err := createEndpoint(network.Id, string(endpointSettings))
	if err != nil {
		return nil, err
	}
	return newEndpoint, nil
}
1104184
func (n *NIC) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior) *referencedNetworkEndpoint {
	id := NetworkEndpointID{address}

	n.mu.RLock()
	ref := n.endpoints[id]
	if ref != nil && !ref.tryIncRef() {
		ref = nil
	}
	spoofing := n.spoofing
	n.mu.RUnlock()

	if ref != nil || !spoofing {
		return ref
	}

	// Try again with the lock in exclusive mode. If we still can't get the
	// endpoint, create a new "temporary" endpoint. It will only exist while
	// there's a route through it.
	n.mu.Lock()
	ref = n.endpoints[id]
	if ref == nil || !ref.tryIncRef() {
		ref, _ = n.addAddressLocked(protocol, address, peb, true)
		if ref != nil {
			ref.holdsInsertRef = false
		}
	}
	n.mu.Unlock()
	return ref
}
1264954
func getEndpointsAndPort(endpoints []string) (endpointsR []string, portR int, err error) {
	var resultEndpoints []string
	var resultPort int

	if len(endpoints) > 1 {
		return nil, 0, ErrInvalidEndpointConfig
	}

	if len(endpoints[0]) > 0 {
		v := endpoints[0]

		if !strings.Contains(v, ":") {
			return nil, 0, ErrInvalidEndpointConfig
		}

		if strings.Contains(v, ",") {
			endpointsAndPort := strings.Split(v, ",")
			for _, val := range endpointsAndPort {
				endpointAndPort := strings.Split(val, ":")
				resultEndpoints = append(resultEndpoints, endpointAndPort[0])
				resultPort, err = strconv.Atoi(endpointAndPort[1])
				if err != nil {
					return nil, 0, err
				}
			}

		} else {
			endpointAndPort := strings.Split(v, ":")
			resultEndpoints = append(resultEndpoints, endpointAndPort[0])
			resultPort, err = strconv.Atoi(endpointAndPort[1])
			if err != nil {
				return nil, 0, err
			}
		}
	} else {
		return nil, 0, ErrInvalidEndpointConfig
	}

	return resultEndpoints, resultPort, nil
}
649495
func (a *Client) GetEndpointIDLog(params *GetEndpointIDLogParams) (*GetEndpointIDLogOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetEndpointIDLogParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "GetEndpointIDLog",
		Method:             "GET",
		PathPattern:        "/endpoint/{id}/log",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &GetEndpointIDLogReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetEndpointIDLogOK), nil

}
538098
func GetEndpoint(epID string) (*drivers.OperEndpointState, error) {
	// Get hold of the state driver
	stateDriver, err := GetStateDriver()
	if err != nil {
		return nil, err
	}

	operEp := &drivers.OperEndpointState{}
	operEp.StateDriver = stateDriver
	err = operEp.Read(epID)
	if err != nil {
		return nil, err
	}

	return operEp, nil
}