endpoints.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Package endpoints validates regional endpoints for services.
  2. package endpoints
  3. //go:generate go run -tags codegen ../model/cli/gen-endpoints/main.go endpoints.json endpoints_map.go
  4. //go:generate gofmt -s -w endpoints_map.go
  5. import (
  6. "fmt"
  7. "regexp"
  8. "strings"
  9. )
  10. // NormalizeEndpoint takes and endpoint and service API information to return a
  11. // normalized endpoint and signing region. If the endpoint is not an empty string
  12. // the service name and region will be used to look up the service's API endpoint.
  13. // If the endpoint is provided the scheme will be added if it is not present.
  14. func NormalizeEndpoint(endpoint, serviceName, region string, disableSSL, useDualStack bool) (normEndpoint, signingRegion string) {
  15. if endpoint == "" {
  16. return EndpointForRegion(serviceName, region, disableSSL, useDualStack)
  17. }
  18. return AddScheme(endpoint, disableSSL), ""
  19. }
  20. // EndpointForRegion returns an endpoint and its signing region for a service and region.
  21. // if the service and region pair are not found endpoint and signingRegion will be empty.
  22. func EndpointForRegion(svcName, region string, disableSSL, useDualStack bool) (endpoint, signingRegion string) {
  23. dualStackField := ""
  24. if useDualStack {
  25. dualStackField = "/dualstack"
  26. }
  27. derivedKeys := []string{
  28. region + "/" + svcName + dualStackField,
  29. region + "/*" + dualStackField,
  30. "*/" + svcName + dualStackField,
  31. "*/*" + dualStackField,
  32. }
  33. for _, key := range derivedKeys {
  34. if val, ok := endpointsMap.Endpoints[key]; ok {
  35. ep := val.Endpoint
  36. ep = strings.Replace(ep, "{region}", region, -1)
  37. ep = strings.Replace(ep, "{service}", svcName, -1)
  38. endpoint = ep
  39. signingRegion = val.SigningRegion
  40. break
  41. }
  42. }
  43. return AddScheme(endpoint, disableSSL), signingRegion
  44. }
  45. // Regular expression to determine if the endpoint string is prefixed with a scheme.
  46. var schemeRE = regexp.MustCompile("^([^:]+)://")
  47. // AddScheme adds the HTTP or HTTPS schemes to a endpoint URL if there is no
  48. // scheme. If disableSSL is true HTTP will be added instead of the default HTTPS.
  49. func AddScheme(endpoint string, disableSSL bool) string {
  50. if endpoint != "" && !schemeRE.MatchString(endpoint) {
  51. scheme := "https"
  52. if disableSSL {
  53. scheme = "http"
  54. }
  55. endpoint = fmt.Sprintf("%s://%s", scheme, endpoint)
  56. }
  57. return endpoint
  58. }