|
| 1 | +package google |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/url" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "google.golang.org/api/option/internaloption" |
| 10 | + "google.golang.org/api/transport" |
| 11 | +) |
| 12 | + |
| 13 | +// The transport libaray does not natively expose logic to determine whether |
| 14 | +// the user is within mtls mode or not. They do return the mtls endpoint if |
| 15 | +// it is enabled during client creation so we will use this logic to determine |
| 16 | +// the mode the user is in and throw away the client they give us back. |
| 17 | +func isMtls() bool { |
| 18 | + regularEndpoint := "https://mockservice.googleapis.com/v1/" |
| 19 | + mtlsEndpoint := getMtlsEndpoint(regularEndpoint) |
| 20 | + _, endpoint, err := transport.NewHTTPClient(context.Background(), |
| 21 | + internaloption.WithDefaultEndpoint(regularEndpoint), |
| 22 | + internaloption.WithDefaultMTLSEndpoint(mtlsEndpoint), |
| 23 | + ) |
| 24 | + if err != nil { |
| 25 | + return false |
| 26 | + } |
| 27 | + isMtls := endpoint == mtlsEndpoint |
| 28 | + return isMtls |
| 29 | +} |
| 30 | + |
| 31 | +func getMtlsEndpoint(baseEndpoint string) string { |
| 32 | + u, err := url.Parse(baseEndpoint) |
| 33 | + if err != nil { |
| 34 | + if strings.Contains(baseEndpoint, ".googleapis") { |
| 35 | + return strings.Replace(baseEndpoint, ".googleapis", ".mtls.googleapis", 1) |
| 36 | + } |
| 37 | + return baseEndpoint |
| 38 | + } |
| 39 | + domainParts := strings.Split(u.Host, ".") |
| 40 | + if len(domainParts) > 1 { |
| 41 | + u.Host = fmt.Sprintf("%s.mtls.%s", domainParts[0], strings.Join(domainParts[1:], ".")) |
| 42 | + } else { |
| 43 | + u.Host = fmt.Sprintf("%s.mtls", domainParts[0]) |
| 44 | + } |
| 45 | + return u.String() |
| 46 | +} |
0 commit comments