3
* Copyright 2020 gRPC authors.
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
9
* http://www.apache.org/licenses/LICENSE-2.0
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.
19
// Package grpcutil provides a bunch of utility functions to be used across the
26
"google.golang.org/grpc/resolver"
29
// split2 returns the values from strings.SplitN(s, sep, 2).
30
// If sep is not found, it returns ("", "", false) instead.
31
func split2(s, sep string) (string, string, bool) {
32
spl := strings.SplitN(s, sep, 2)
36
return spl[0], spl[1], true
39
// ParseTarget splits target into a resolver.Target struct containing scheme,
40
// authority and endpoint. skipUnixColonParsing indicates that the parse should
41
// not parse "unix:[path]" cases. This should be true in cases where a custom
42
// dialer is present, to prevent a behavior change.
44
// If target is not a valid scheme://authority/endpoint as specified in
45
// https://github.com/grpc/grpc/blob/master/doc/naming.md,
46
// it returns {Endpoint: target}.
47
func ParseTarget(target string, skipUnixColonParsing bool) (ret resolver.Target) {
49
if strings.HasPrefix(target, "unix-abstract:") {
50
if strings.HasPrefix(target, "unix-abstract://") {
51
// Maybe, with Authority specified, try to parse it
53
ret.Scheme, remain, _ = split2(target, "://")
54
ret.Authority, ret.Endpoint, ok = split2(remain, "/")
56
// No Authority, add the "//" back
57
ret.Endpoint = "//" + remain
59
// Found Authority, add the "/" back
60
ret.Endpoint = "/" + ret.Endpoint
63
// Without Authority specified, split target on ":"
64
ret.Scheme, ret.Endpoint, _ = split2(target, ":")
68
ret.Scheme, ret.Endpoint, ok = split2(target, "://")
70
if strings.HasPrefix(target, "unix:") && !skipUnixColonParsing {
71
// Handle the "unix:[local/path]" and "unix:[/absolute/path]" cases,
72
// because splitting on :// only handles the
73
// "unix://[/absolute/path]" case. Only handle if the dialer is nil,
74
// to avoid a behavior change with custom dialers.
75
return resolver.Target{Scheme: "unix", Endpoint: target[len("unix:"):]}
77
return resolver.Target{Endpoint: target}
79
ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/")
81
return resolver.Target{Endpoint: target}
83
if ret.Scheme == "unix" {
84
// Add the "/" back in the unix case, so the unix resolver receives the
85
// actual endpoint in the "unix://[/absolute/path]" case.
86
ret.Endpoint = "/" + ret.Endpoint