resolver.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. package endpoints
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
  19. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
  20. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  21. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
  22. "sync"
  23. )
  24. var debug utils.Debug
  25. func init() {
  26. debug = utils.Init("sdk")
  27. }
  28. const (
  29. ResolveEndpointUserGuideLink = ""
  30. )
  31. var once sync.Once
  32. var resolvers []Resolver
  33. type Resolver interface {
  34. TryResolve(param *ResolveParam) (endpoint string, support bool, err error)
  35. GetName() (name string)
  36. }
  37. func Resolve(param *ResolveParam) (endpoint string, err error) {
  38. supportedResolvers := getAllResolvers()
  39. for _, resolver := range supportedResolvers {
  40. endpoint, supported, err := resolver.TryResolve(param)
  41. if supported {
  42. debug("resolve endpoint with %s\n", param)
  43. debug("\t%s by resolver(%s)\n", endpoint, resolver.GetName())
  44. return endpoint, err
  45. }
  46. }
  47. // not support
  48. errorMsg := fmt.Sprintf(errors.CanNotResolveEndpointErrorMessage, param, ResolveEndpointUserGuideLink)
  49. err = errors.NewClientError(errors.CanNotResolveEndpointErrorCode, errorMsg, nil)
  50. return
  51. }
  52. func getAllResolvers() []Resolver {
  53. once.Do(func() {
  54. resolvers = []Resolver{
  55. &SimpleHostResolver{},
  56. &MappingResolver{},
  57. &LocationResolver{},
  58. &LocalRegionalResolver{},
  59. &LocalGlobalResolver{},
  60. }
  61. })
  62. return resolvers
  63. }
  64. type ResolveParam struct {
  65. Domain string
  66. Product string
  67. RegionId string
  68. LocationProduct string
  69. LocationEndpointType string
  70. CommonApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) `json:"-"`
  71. }
  72. func (param *ResolveParam) String() string {
  73. jsonBytes, err := json.Marshal(param)
  74. if err != nil {
  75. return fmt.Sprint("ResolveParam.String() process error:", err)
  76. }
  77. return string(jsonBytes)
  78. }