From 07fefbd0f010d578d8a091998715b3169f6f6e04 Mon Sep 17 00:00:00 2001 From: Bachue Zhou Date: Tue, 24 Sep 2024 15:03:19 +0800 Subject: [PATCH] Releases/v7.23.0 (#142) --- .github/workflows/ci-test.yml | 9 +- CHANGELOG.md | 10 + Makefile | 3 + README.md | 2 +- api-specs | 2 +- audit/apis/api_query_log.go | 123 +++++ audit/apis/apis.go | 27 ++ audit/apis/query_log/api.go | 241 +++++++++ audit/doc.go | 5 + conf/conf.go | 2 +- go.mod | 1 + go.sum | 3 +- iam/apis/api_create_group.go | 93 ++++ iam/apis/api_create_policy.go | 93 ++++ iam/apis/api_create_user.go | 93 ++++ iam/apis/api_create_user_keypairs.go | 97 ++++ iam/apis/api_delete_group.go | 96 ++++ iam/apis/api_delete_group_policies.go | 108 +++++ iam/apis/api_delete_group_users.go | 108 +++++ iam/apis/api_delete_policy.go | 96 ++++ iam/apis/api_delete_user.go | 96 ++++ iam/apis/api_delete_user_keypair.go | 101 ++++ iam/apis/api_delete_user_policy.go | 108 +++++ iam/apis/api_disable_user_keypair.go | 102 ++++ iam/apis/api_enable_user_keypair.go | 102 ++++ iam/apis/api_get_actions.go | 102 ++++ iam/apis/api_get_audits.go | 117 +++++ iam/apis/api_get_group.go | 96 ++++ iam/apis/api_get_group_policies.go | 114 +++++ .../api_get_group_service_action_resources.go | 107 ++++ iam/apis/api_get_group_users.go | 114 +++++ iam/apis/api_get_groups.go | 99 ++++ iam/apis/api_get_policies.go | 99 ++++ iam/apis/api_get_policy.go | 96 ++++ iam/apis/api_get_policy_groups.go | 114 +++++ iam/apis/api_get_policy_users.go | 114 +++++ iam/apis/api_get_services.go | 99 ++++ iam/apis/api_get_user.go | 96 ++++ iam/apis/api_get_user_available_services.go | 97 ++++ iam/apis/api_get_user_groups.go | 114 +++++ iam/apis/api_get_user_keypairs.go | 114 +++++ iam/apis/api_get_user_policies.go | 114 +++++ .../api_get_user_service_action_resources.go | 107 ++++ iam/apis/api_get_users.go | 102 ++++ iam/apis/api_modify_group.go | 107 ++++ iam/apis/api_modify_group_policies.go | 108 +++++ iam/apis/api_modify_group_users.go | 108 +++++ iam/apis/api_modify_policy.go | 107 ++++ iam/apis/api_modify_user.go | 107 ++++ iam/apis/api_modify_user_policies.go | 108 +++++ iam/apis/api_update_group_policies.go | 108 +++++ iam/apis/api_update_group_users.go | 108 +++++ iam/apis/api_update_policy_groups.go | 108 +++++ iam/apis/api_update_policy_users.go | 108 +++++ iam/apis/api_update_user_groups.go | 108 +++++ iam/apis/api_update_user_policies.go | 108 +++++ iam/apis/apis.go | 27 ++ iam/apis/create_group/api.go | 140 ++++++ iam/apis/create_policy/api.go | 265 ++++++++++ iam/apis/create_user/api.go | 152 ++++++ iam/apis/create_user_keypairs/api.go | 107 ++++ iam/apis/delete_group/api.go | 15 + iam/apis/delete_group_policies/api.go | 50 ++ iam/apis/delete_group_users/api.go | 50 ++ iam/apis/delete_policy/api.go | 15 + iam/apis/delete_user/api.go | 15 + iam/apis/delete_user_keypair/api.go | 16 + iam/apis/delete_user_policy/api.go | 50 ++ iam/apis/disable_user_keypair/api.go | 16 + iam/apis/enable_user_keypair/api.go | 16 + iam/apis/get_actions/api.go | 164 +++++++ iam/apis/get_audits/api.go | 196 ++++++++ iam/apis/get_group/api.go | 113 +++++ iam/apis/get_group_policies/api.go | 219 +++++++++ .../get_group_service_action_resources/api.go | 94 ++++ iam/apis/get_group_users/api.go | 164 +++++++ iam/apis/get_groups/api.go | 157 ++++++ iam/apis/get_policies/api.go | 218 +++++++++ iam/apis/get_policy/api.go | 174 +++++++ iam/apis/get_policy_groups/api.go | 158 ++++++ iam/apis/get_policy_users/api.go | 164 +++++++ iam/apis/get_services/api.go | 52 ++ iam/apis/get_user/api.go | 119 +++++ iam/apis/get_user_available_services/api.go | 51 ++ iam/apis/get_user_groups/api.go | 158 ++++++ iam/apis/get_user_keypairs/api.go | 152 ++++++ iam/apis/get_user_policies/api.go | 219 +++++++++ .../get_user_service_action_resources/api.go | 94 ++++ iam/apis/get_users/api.go | 164 +++++++ iam/apis/modify_group/api.go | 46 ++ iam/apis/modify_group_policies/api.go | 50 ++ iam/apis/modify_group_users/api.go | 50 ++ iam/apis/modify_policy/api.go | 255 ++++++++++ iam/apis/modify_user/api.go | 147 ++++++ iam/apis/modify_user_policies/api.go | 50 ++ iam/apis/update_group_policies/api.go | 46 ++ iam/apis/update_group_users/api.go | 46 ++ iam/apis/update_policy_groups/api.go | 46 ++ iam/apis/update_policy_users/api.go | 46 ++ iam/apis/update_user_groups/api.go | 46 ++ iam/apis/update_user_policies/api.go | 46 ++ iam/doc.go | 5 + .../api-generator/client.go | 456 ++++++++++++------ .../api-generator/form.go | 4 - .../api-generator/headers.go | 0 .../api-generator/json.go | 0 .../api-generator/main.go | 89 ++-- .../api-generator/multipart.go | 0 .../api-generator/path.go | 9 +- .../api-generator/query.go | 13 +- .../api-generator/request.go | 0 .../api-generator/response.go | 0 .../api-generator/types.go | 3 + .../api-generator/utils.go | 0 internal/clientv2/interceptor_auth.go | 9 +- internal/clientv2/interceptor_retry_simple.go | 4 + internal/clientv2/multipart.go | 33 +- .../uplog/block_uplog.go | 0 .../internal => internal}/uplog/dns1.12.go | 0 .../internal => internal}/uplog/dns1.13.go | 0 .../uplog/quality_uplog.go | 0 .../uplog/request_uplog.go | 0 .../internal => internal}/uplog/uplog.go | 0 .../uplog/uplog_buffer.go | 0 .../uplog/uplog_buffer_test.go | 0 .../uplog/uplog_prod_env.go | 0 .../uplog/uplog_test_env.go | 0 .../uplog/uplog_upload.go | 0 .../internal => internal}/uplog/utils.go | 0 media/apis/api_pfop.go | 119 +++++ media/apis/api_prefop.go | 97 ++++ media/apis/apis.go | 27 ++ media/apis/pfop/api.go | 54 +++ media/apis/prefop/api.go | 166 +++++++ media/doc.go | 5 + storage/pfop.go | 165 +++++-- storage/token.go | 3 + storage/upload_manager_uplog_test.go | 434 ++++++++--------- storagev2/apis/api_add_bucket_event_rule.go | 49 +- storagev2/apis/api_add_bucket_rules.go | 49 +- storagev2/apis/api_async_fetch_object.go | 82 ++-- storagev2/apis/api_batch_ops.go | 67 +-- storagev2/apis/api_check_share.go | 161 +++++++ storagev2/apis/api_copy_object.go | 66 +-- storagev2/apis/api_create_bucket.go | 51 +- storagev2/apis/api_create_share.go | 143 ++++++ storagev2/apis/api_delete_bucket.go | 51 +- .../apis/api_delete_bucket_event_rule.go | 49 +- storagev2/apis/api_delete_bucket_rules.go | 49 +- storagev2/apis/api_delete_bucket_taggings.go | 49 +- storagev2/apis/api_delete_object.go | 66 +-- .../apis/api_delete_object_after_days.go | 69 +-- .../apis/api_disable_bucket_index_page.go | 49 +- storagev2/apis/api_fetch_object.go | 66 +-- storagev2/apis/api_get_async_fetch_task.go | 85 ++-- storagev2/apis/api_get_bucket_cors_rules.go | 51 +- storagev2/apis/api_get_bucket_domains.go | 49 +- storagev2/apis/api_get_bucket_domains_v3.go | 49 +- storagev2/apis/api_get_bucket_event_rules.go | 49 +- storagev2/apis/api_get_bucket_info.go | 49 +- storagev2/apis/api_get_bucket_infos.go | 49 +- storagev2/apis/api_get_bucket_quota.go | 51 +- storagev2/apis/api_get_bucket_rules.go | 49 +- storagev2/apis/api_get_bucket_taggings.go | 49 +- storagev2/apis/api_get_buckets.go | 49 +- storagev2/apis/api_get_buckets_v4.go | 49 +- storagev2/apis/api_get_objects.go | 67 +-- storagev2/apis/api_get_objects_v2.go | 67 +-- storagev2/apis/api_get_regions.go | 51 +- .../apis/api_modify_object_life_cycle.go | 66 +-- storagev2/apis/api_modify_object_metadata.go | 66 +-- storagev2/apis/api_modify_object_status.go | 66 +-- storagev2/apis/api_move_object.go | 66 +-- storagev2/apis/api_post_object.go | 65 +-- storagev2/apis/api_prefetch_object.go | 66 +-- storagev2/apis/api_query_bucket_v2.go | 42 +- storagev2/apis/api_query_bucket_v4.go | 42 +- storagev2/apis/api_restore_archived_object.go | 66 +-- .../apis/api_resumable_upload_v1_bput.go | 69 +-- .../api_resumable_upload_v1_make_block.go | 69 +-- .../apis/api_resumable_upload_v1_make_file.go | 69 +-- ...umable_upload_v2_abort_multipart_upload.go | 69 +-- ...ble_upload_v2_complete_multipart_upload.go | 69 +-- ...ble_upload_v2_initiate_multipart_upload.go | 69 +-- .../api_resumable_upload_v2_list_parts.go | 69 +-- .../api_resumable_upload_v2_upload_part.go | 69 +-- storagev2/apis/api_set_bucket_access_mode.go | 51 +- storagev2/apis/api_set_bucket_cors_rules.go | 51 +- storagev2/apis/api_set_bucket_image.go | 51 +- storagev2/apis/api_set_bucket_max_age.go | 49 +- storagev2/apis/api_set_bucket_private.go | 49 +- storagev2/apis/api_set_bucket_quota.go | 51 +- .../apis/api_set_bucket_refer_anti_leech.go | 49 +- storagev2/apis/api_set_bucket_remark.go | 51 +- storagev2/apis/api_set_bucket_taggings.go | 49 +- storagev2/apis/api_set_buckets_mirror.go | 51 +- storagev2/apis/api_set_object_file_type.go | 66 +-- storagev2/apis/api_stat_object.go | 66 +-- storagev2/apis/api_unset_bucket_image.go | 51 +- .../apis/api_update_bucket_event_rule.go | 49 +- storagev2/apis/api_update_bucket_rules.go | 49 +- storagev2/apis/api_verify_share.go | 172 +++++++ storagev2/apis/check_share/api.go | 16 + storagev2/apis/create_share/api.go | 111 +++++ storagev2/apis/get_bucket_quota/api.go | 3 + storagev2/apis/set_bucket_remark/api.go | 3 + storagev2/apis/verify_share/api.go | 128 +++++ storagev2/doc.go | 3 +- storagev2/downloader/download_manager.go | 10 +- storagev2/downloader/download_manager_test.go | 215 +++++++++ storagev2/downloader/urls_provider_test.go | 56 +-- storagev2/downloader/urls_provider_utils.go | 40 ++ storagev2/http_client/http_client.go | 141 +++--- storagev2/region/all.go | 223 +++++++++ storagev2/region/all_test.go | 137 ++++++ storagev2/region/query.go | 96 ++-- storagev2/region/query_test.go | 3 +- storagev2/region/region.go | 130 +++-- storagev2/retrier/retrier.go | 10 +- storagev2/uploader/form_uploader_test.go | 122 +++++ storagev2/uploader/params.go | 2 +- .../resumable_recorder/json_file_system.go | 5 + storagev2/uploader/upload_manager.go | 3 + storagev2/uploader/upload_manager_test.go | 75 +++ storagev2/uploader/uploaders.go | 1 + storagev2/uplog/uplog.go | 2 +- storagev2/uptoken/putpolicy.go | 12 + 227 files changed, 13917 insertions(+), 2973 deletions(-) create mode 100644 audit/apis/api_query_log.go create mode 100644 audit/apis/apis.go create mode 100644 audit/apis/query_log/api.go create mode 100644 audit/doc.go create mode 100644 iam/apis/api_create_group.go create mode 100644 iam/apis/api_create_policy.go create mode 100644 iam/apis/api_create_user.go create mode 100644 iam/apis/api_create_user_keypairs.go create mode 100644 iam/apis/api_delete_group.go create mode 100644 iam/apis/api_delete_group_policies.go create mode 100644 iam/apis/api_delete_group_users.go create mode 100644 iam/apis/api_delete_policy.go create mode 100644 iam/apis/api_delete_user.go create mode 100644 iam/apis/api_delete_user_keypair.go create mode 100644 iam/apis/api_delete_user_policy.go create mode 100644 iam/apis/api_disable_user_keypair.go create mode 100644 iam/apis/api_enable_user_keypair.go create mode 100644 iam/apis/api_get_actions.go create mode 100644 iam/apis/api_get_audits.go create mode 100644 iam/apis/api_get_group.go create mode 100644 iam/apis/api_get_group_policies.go create mode 100644 iam/apis/api_get_group_service_action_resources.go create mode 100644 iam/apis/api_get_group_users.go create mode 100644 iam/apis/api_get_groups.go create mode 100644 iam/apis/api_get_policies.go create mode 100644 iam/apis/api_get_policy.go create mode 100644 iam/apis/api_get_policy_groups.go create mode 100644 iam/apis/api_get_policy_users.go create mode 100644 iam/apis/api_get_services.go create mode 100644 iam/apis/api_get_user.go create mode 100644 iam/apis/api_get_user_available_services.go create mode 100644 iam/apis/api_get_user_groups.go create mode 100644 iam/apis/api_get_user_keypairs.go create mode 100644 iam/apis/api_get_user_policies.go create mode 100644 iam/apis/api_get_user_service_action_resources.go create mode 100644 iam/apis/api_get_users.go create mode 100644 iam/apis/api_modify_group.go create mode 100644 iam/apis/api_modify_group_policies.go create mode 100644 iam/apis/api_modify_group_users.go create mode 100644 iam/apis/api_modify_policy.go create mode 100644 iam/apis/api_modify_user.go create mode 100644 iam/apis/api_modify_user_policies.go create mode 100644 iam/apis/api_update_group_policies.go create mode 100644 iam/apis/api_update_group_users.go create mode 100644 iam/apis/api_update_policy_groups.go create mode 100644 iam/apis/api_update_policy_users.go create mode 100644 iam/apis/api_update_user_groups.go create mode 100644 iam/apis/api_update_user_policies.go create mode 100644 iam/apis/apis.go create mode 100644 iam/apis/create_group/api.go create mode 100644 iam/apis/create_policy/api.go create mode 100644 iam/apis/create_user/api.go create mode 100644 iam/apis/create_user_keypairs/api.go create mode 100644 iam/apis/delete_group/api.go create mode 100644 iam/apis/delete_group_policies/api.go create mode 100644 iam/apis/delete_group_users/api.go create mode 100644 iam/apis/delete_policy/api.go create mode 100644 iam/apis/delete_user/api.go create mode 100644 iam/apis/delete_user_keypair/api.go create mode 100644 iam/apis/delete_user_policy/api.go create mode 100644 iam/apis/disable_user_keypair/api.go create mode 100644 iam/apis/enable_user_keypair/api.go create mode 100644 iam/apis/get_actions/api.go create mode 100644 iam/apis/get_audits/api.go create mode 100644 iam/apis/get_group/api.go create mode 100644 iam/apis/get_group_policies/api.go create mode 100644 iam/apis/get_group_service_action_resources/api.go create mode 100644 iam/apis/get_group_users/api.go create mode 100644 iam/apis/get_groups/api.go create mode 100644 iam/apis/get_policies/api.go create mode 100644 iam/apis/get_policy/api.go create mode 100644 iam/apis/get_policy_groups/api.go create mode 100644 iam/apis/get_policy_users/api.go create mode 100644 iam/apis/get_services/api.go create mode 100644 iam/apis/get_user/api.go create mode 100644 iam/apis/get_user_available_services/api.go create mode 100644 iam/apis/get_user_groups/api.go create mode 100644 iam/apis/get_user_keypairs/api.go create mode 100644 iam/apis/get_user_policies/api.go create mode 100644 iam/apis/get_user_service_action_resources/api.go create mode 100644 iam/apis/get_users/api.go create mode 100644 iam/apis/modify_group/api.go create mode 100644 iam/apis/modify_group_policies/api.go create mode 100644 iam/apis/modify_group_users/api.go create mode 100644 iam/apis/modify_policy/api.go create mode 100644 iam/apis/modify_user/api.go create mode 100644 iam/apis/modify_user_policies/api.go create mode 100644 iam/apis/update_group_policies/api.go create mode 100644 iam/apis/update_group_users/api.go create mode 100644 iam/apis/update_policy_groups/api.go create mode 100644 iam/apis/update_policy_users/api.go create mode 100644 iam/apis/update_user_groups/api.go create mode 100644 iam/apis/update_user_policies/api.go create mode 100644 iam/doc.go rename {storagev2/internal => internal}/api-generator/client.go (60%) rename {storagev2/internal => internal}/api-generator/form.go (98%) rename {storagev2/internal => internal}/api-generator/headers.go (100%) rename {storagev2/internal => internal}/api-generator/json.go (100%) rename {storagev2/internal => internal}/api-generator/main.go (59%) rename {storagev2/internal => internal}/api-generator/multipart.go (100%) rename {storagev2/internal => internal}/api-generator/path.go (97%) rename {storagev2/internal => internal}/api-generator/query.go (97%) rename {storagev2/internal => internal}/api-generator/request.go (100%) rename {storagev2/internal => internal}/api-generator/response.go (100%) rename {storagev2/internal => internal}/api-generator/types.go (98%) rename {storagev2/internal => internal}/api-generator/utils.go (100%) rename {storagev2/internal => internal}/uplog/block_uplog.go (100%) rename {storagev2/internal => internal}/uplog/dns1.12.go (100%) rename {storagev2/internal => internal}/uplog/dns1.13.go (100%) rename {storagev2/internal => internal}/uplog/quality_uplog.go (100%) rename {storagev2/internal => internal}/uplog/request_uplog.go (100%) rename {storagev2/internal => internal}/uplog/uplog.go (100%) rename {storagev2/internal => internal}/uplog/uplog_buffer.go (100%) rename {storagev2/internal => internal}/uplog/uplog_buffer_test.go (100%) rename {storagev2/internal => internal}/uplog/uplog_prod_env.go (100%) rename {storagev2/internal => internal}/uplog/uplog_test_env.go (100%) rename {storagev2/internal => internal}/uplog/uplog_upload.go (100%) rename {storagev2/internal => internal}/uplog/utils.go (100%) create mode 100644 media/apis/api_pfop.go create mode 100644 media/apis/api_prefop.go create mode 100644 media/apis/apis.go create mode 100644 media/apis/pfop/api.go create mode 100644 media/apis/prefop/api.go create mode 100644 media/doc.go create mode 100644 storagev2/apis/api_check_share.go create mode 100644 storagev2/apis/api_create_share.go create mode 100644 storagev2/apis/api_verify_share.go create mode 100644 storagev2/apis/check_share/api.go create mode 100644 storagev2/apis/create_share/api.go create mode 100644 storagev2/apis/verify_share/api.go create mode 100644 storagev2/downloader/urls_provider_utils.go create mode 100644 storagev2/region/all.go create mode 100644 storagev2/region/all_test.go diff --git a/.github/workflows/ci-test.yml b/.github/workflows/ci-test.yml index 6de94881..0ef91de0 100644 --- a/.github/workflows/ci-test.yml +++ b/.github/workflows/ci-test.yml @@ -43,16 +43,17 @@ jobs: rm -rf $GITHUB_WORKSPACE/src/github.com/prometheus/procfs && git clone -b v0.0.6 --depth 1 https://github.com/prometheus/procfs.git $GITHUB_WORKSPACE/src/github.com/prometheus/procfs rm -rf $GITHUB_WORKSPACE/src/howett.net/plist && git clone -b v1.0.0 --depth 1 https://github.com/DHowett/go-plist.git $GITHUB_WORKSPACE/src/howett.net/plist rm -rf $GITHUB_WORKSPACE/src/golang.org/x/sys && git clone -b v0.13.0 --depth 1 https://github.com/golang/sys $GITHUB_WORKSPACE/src/golang.org/x/sys + rm -rf $GITHUB_WORKSPACE/src/github.com/jessevdk/go-flags && git clone -b v1.4.0 --depth 1 https://github.com/jessevdk/go-flags.git $GITHUB_WORKSPACE/src/github.com/jessevdk/go-flags rm -rf $GITHUB_WORKSPACE/src/golang.org/x/crypto && git clone -b v0.10.0 --depth 1 https://go.googlesource.com/crypto $GITHUB_WORKSPACE/src/golang.org/x/crypto - rm -rf $GITHUB_WORKSPACE/src/golang.org/x/text && git clone -b v0.10.0 --depth 1 https://github.com/golang/text $GITHUB_WORKSPACE/src/golang.org/x/text - rm -rf $GITHUB_WORKSPACE/src/golang.org/x/sync && git clone -b v0.3.0 --depth 1 https://github.com/golang/sync $GITHUB_WORKSPACE/src/golang.org/x/sync + rm -rf $GITHUB_WORKSPACE/src/golang.org/x/text && git clone -b v0.10.0 --depth 1 https://github.com/golang/text.git $GITHUB_WORKSPACE/src/golang.org/x/text + rm -rf $GITHUB_WORKSPACE/src/golang.org/x/sync && git clone -b v0.3.0 --depth 1 https://github.com/golang/sync.git $GITHUB_WORKSPACE/src/golang.org/x/sync GOPATH=$GITHUB_WORKSPACE go get github.com/leodido/go-urn GOPATH=$GITHUB_WORKSPACE go get github.com/go-playground/locales - rm -rf $GITHUB_WORKSPACE/src/github.com/dave/jennifer && git clone -b v1.6.1 --depth 1 https://github.com/dave/jennifer $GITHUB_WORKSPACE/src/github.com/dave/jennifer + rm -rf $GITHUB_WORKSPACE/src/github.com/dave/jennifer && git clone -b v1.6.1 --depth 1 https://github.com/dave/jennifer.git $GITHUB_WORKSPACE/src/github.com/dave/jennifer rm -rf $GITHUB_WORKSPACE/src/modernc.org/fileutil && git clone -b v1.0.0 --depth 1 https://gitlab.com/cznic/fileutil.git $GITHUB_WORKSPACE/src/modernc.org/fileutil - rm -rf $GITHUB_WORKSPACE/src/github.com/gorilla/mux && git clone -b v1.7.4 --depth 1 https://github.com/gorilla/mux $GITHUB_WORKSPACE/src/github.com/gorilla/mux + rm -rf $GITHUB_WORKSPACE/src/github.com/gorilla/mux && git clone -b v1.7.4 --depth 1 https://github.com/gorilla/mux.git $GITHUB_WORKSPACE/src/github.com/gorilla/mux GOPATH=$GITHUB_WORKSPACE go get github.com/iancoleman/strcase diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cdfe6fe..5d2e1301 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 7.23.0 +* 新增 + * 支持上传加速 + * 多媒体处理库 [media](github.com/qiniu/go-sdk/v7/media/apis) 包,提供多媒体处理接口 + * IAM [iam](github.com/qiniu/go-sdk/v7/iam/apis) 包,提供权限管理系统接口 + * 获取下载 URL 的实用方法 + * 提供文件夹分享接口 +* 修复 + * `downloader.DownloadDirectory` 下载根目录出错的 Bug + ## 7.22.0 * 新增 * 新版存储客户端库 storagev2 包,包含 diff --git a/Makefile b/Makefile index 3aadd313..9c6bdab1 100644 --- a/Makefile +++ b/Makefile @@ -12,3 +12,6 @@ staticcheck: generate: go generate ./storagev2/ + go generate ./iam/ + go generate ./media/ + go generate ./audit/ diff --git a/README.md b/README.md index 97466ea0..1995a825 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ github.com/qiniu/go-sdk 在您的项目中的 `go.mod` 文件内添加这行代码 ``` -require github.com/qiniu/go-sdk/v7 v7.22.0 +require github.com/qiniu/go-sdk/v7 v7.23.0 ``` 并且在项目中使用 `"github.com/qiniu/go-sdk/v7"` 引用 Qiniu Go SDK。 diff --git a/api-specs b/api-specs index fc527c37..02461c7d 160000 --- a/api-specs +++ b/api-specs @@ -1 +1 @@ -Subproject commit fc527c37e43c96662b1241b1cc228726ade93b55 +Subproject commit 02461c7d1eef0e76837a14b842c11a4a0d08a4c0 diff --git a/audit/apis/api_query_log.go b/audit/apis/api_query_log.go new file mode 100644 index 00000000..a72a3b4c --- /dev/null +++ b/audit/apis/api_query_log.go @@ -0,0 +1,123 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + querylog "github.com/qiniu/go-sdk/v7/audit/apis/query_log" + auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerQueryLogRequest querylog.Request + +func (query *innerQueryLogRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.StartTime != "" { + allQuery.Set("start_time", query.StartTime) + } else { + return nil, errors.MissingRequiredFieldError{Name: "StartTime"} + } + if query.EndTime != "" { + allQuery.Set("end_time", query.EndTime) + } else { + return nil, errors.MissingRequiredFieldError{Name: "EndTime"} + } + if query.ServiceName != "" { + allQuery.Set("service_name", query.ServiceName) + } + if len(query.EventNames) > 0 { + for _, value := range query.EventNames { + allQuery.Add("event_names", value) + } + } + if query.PrincipalId != "" { + allQuery.Set("principal_id", query.PrincipalId) + } + if query.AccessKeyId != "" { + allQuery.Set("access_key_id", query.AccessKeyId) + } + if query.Limit != 0 { + allQuery.Set("limit", strconv.FormatInt(query.Limit, 10)) + } + if query.NextMark != "" { + allQuery.Set("next_mark", query.NextMark) + } + return allQuery, nil +} + +type QueryLogRequest = querylog.Request +type QueryLogResponse = querylog.Response + +// 审计日志查询 +func (audit *Audit) QueryLog(ctx context.Context, request *QueryLogRequest, options *Options) (*QueryLogResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerQueryLogRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && audit.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 2) + pathSegments = append(pathSegments, "audit", "log-query") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("queryLog", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = audit.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && audit.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = audit.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: audit.client.UseInsecureProtocol(), HostFreezeDuration: audit.client.GetHostFreezeDuration(), Resolver: audit.client.GetResolver(), Chooser: audit.client.GetChooser(), BeforeSign: audit.client.GetBeforeSignCallback(), AfterSign: audit.client.GetAfterSignCallback(), SignError: audit.client.GetSignErrorCallback(), BeforeResolve: audit.client.GetBeforeResolveCallback(), AfterResolve: audit.client.GetAfterResolveCallback(), ResolveError: audit.client.GetResolveErrorCallback(), BeforeBackoff: audit.client.GetBeforeBackoffCallback(), AfterBackoff: audit.client.GetAfterBackoffCallback(), BeforeRequest: audit.client.GetBeforeRequestCallback(), AfterResponse: audit.client.GetAfterResponseCallback()} + if hostRetryConfig := audit.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = audit.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody QueryLogResponse + if err := audit.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/audit/apis/apis.go b/audit/apis/apis.go new file mode 100644 index 00000000..56634edb --- /dev/null +++ b/audit/apis/apis.go @@ -0,0 +1,27 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" +) + +// API 客户端 +type Audit struct { + client *httpclient.Client +} + +// 创建 API 客户端 +func NewAudit(options *httpclient.Options) *Audit { + return &Audit{client: httpclient.NewClient(options)} +} + +// API 客户端选项 +type Options struct { + OverwrittenBucketHosts region.EndpointsProvider + OverwrittenBucketName string + OverwrittenEndpoints region.EndpointsProvider + OverwrittenRegion region.RegionsProvider + OnRequestProgress func(uint64, uint64) +} diff --git a/audit/apis/query_log/api.go b/audit/apis/query_log/api.go new file mode 100644 index 00000000..e2ae5762 --- /dev/null +++ b/audit/apis/query_log/api.go @@ -0,0 +1,241 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 审计日志查询 +package query_log + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + StartTime string // 检索日志的开始时间,日期格式按照 ISO8601 标准,并使用 UTC 时间 + EndTime string // 检索日志的结束时间,日期格式按照 ISO8601 标准,并使用 UTC 时间 + ServiceName string // 服务名称,参考 https://developer.qiniu.com/af/12434/audit-log-events + EventNames []string // 事件名称集合,参考 https://developer.qiniu.com/af/12434/audit-log-events + PrincipalId string // 请求者的 ID,参考 https://developer.qiniu.com/af/manual/12433/audit-log-object + AccessKeyId string // 请求身份所属的 AccessKey ID + Limit int64 // 允许返回的最大结果数目,取值范围:1~50,不传值默认为:20 + NextMark string // 用于请求下一页检索的结果 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + NextMark string // 用于请求下一页检索的结果 + AuditLogInfos LogInfos // 日志集合 +} + +// 请求者的身份信息 +type UserIdentity struct { + AccountId string // 当前请求所属的七牛云账号 ID + PrincipalId string // 当前请求者的 ID,需结合 principal_type 来确认请求者身份 + PrincipalType string // 请求者身份类型,仅支持 UNKNOWN 表示未知,ROOT_USER 表示七牛云账户 ID,IAM_USER 表示 IAM 子账户 ID,QINIU_ACCOUNT 表示当七牛云账号跨账号操作时,记录七牛云账号 ID + AccessKeyId string // 当前请求身份所属的 AccessKey ID +} + +// 返回的请求者的身份信息 +type UserIdentify = UserIdentity +type jsonUserIdentity struct { + AccountId string `json:"account_id"` // 当前请求所属的七牛云账号 ID + PrincipalId string `json:"principal_id"` // 当前请求者的 ID,需结合 principal_type 来确认请求者身份 + PrincipalType string `json:"principal_type"` // 请求者身份类型,仅支持 UNKNOWN 表示未知,ROOT_USER 表示七牛云账户 ID,IAM_USER 表示 IAM 子账户 ID,QINIU_ACCOUNT 表示当七牛云账号跨账号操作时,记录七牛云账号 ID + AccessKeyId string `json:"access_key_id"` // 当前请求身份所属的 AccessKey ID +} + +func (j *UserIdentity) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonUserIdentity{AccountId: j.AccountId, PrincipalId: j.PrincipalId, PrincipalType: j.PrincipalType, AccessKeyId: j.AccessKeyId}) +} +func (j *UserIdentity) UnmarshalJSON(data []byte) error { + var nj jsonUserIdentity + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.AccountId = nj.AccountId + j.PrincipalId = nj.PrincipalId + j.PrincipalType = nj.PrincipalType + j.AccessKeyId = nj.AccessKeyId + return nil +} +func (j *UserIdentity) validate() error { + if j.AccountId == "" { + return errors.MissingRequiredFieldError{Name: "AccountId"} + } + if j.PrincipalId == "" { + return errors.MissingRequiredFieldError{Name: "PrincipalId"} + } + if j.PrincipalType == "" { + return errors.MissingRequiredFieldError{Name: "PrincipalType"} + } + if j.AccessKeyId == "" { + return errors.MissingRequiredFieldError{Name: "AccessKeyId"} + } + return nil +} + +// 返回的操作的资源名称列表 +type ResourceNames = []string + +// 返回的审计日志 +type LogInfo struct { + EventId string // 日志 ID + EventType string // 事件类型,仅支持 UNKNOWN 表示未知,CONSOLE 表示控制台事件,API 表示 API 事件 + EventTime string // 事件发生时间(UTC 格式) + UserIdentity UserIdentify // 请求者的身份信息 + EventRw string // 读写类型,仅支持 UNKNOWN 表示未知,READ 表示读,WRITE 表示写 + ServiceName string // 服务名称 + EventName string // 事件名称 + SourceIp string // 源 IP 地址 + UserAgent string // 客户端代理 + ResourceNames ResourceNames // 操作的资源名称列表 + RequestId string // 请求 ID + RequestUrl string // 请求 URL + RequestParams string // 请求的输入参数 + ResponseData string // 请求的返回数据 + ResponseCode int64 // 请求的返回码 + ResponseMessage string // 请求的返回信息 + AdditionalEventData string // 额外备注信息 +} +type jsonLogInfo struct { + EventId string `json:"event_id"` // 日志 ID + EventType string `json:"event_type"` // 事件类型,仅支持 UNKNOWN 表示未知,CONSOLE 表示控制台事件,API 表示 API 事件 + EventTime string `json:"event_time"` // 事件发生时间(UTC 格式) + UserIdentity UserIdentify `json:"user_identity"` // 请求者的身份信息 + EventRw string `json:"event_rw"` // 读写类型,仅支持 UNKNOWN 表示未知,READ 表示读,WRITE 表示写 + ServiceName string `json:"service_name"` // 服务名称 + EventName string `json:"event_name"` // 事件名称 + SourceIp string `json:"source_ip"` // 源 IP 地址 + UserAgent string `json:"user_agent"` // 客户端代理 + ResourceNames ResourceNames `json:"resource_names"` // 操作的资源名称列表 + RequestId string `json:"request_id"` // 请求 ID + RequestUrl string `json:"request_url"` // 请求 URL + RequestParams string `json:"request_params"` // 请求的输入参数 + ResponseData string `json:"response_data"` // 请求的返回数据 + ResponseCode int64 `json:"response_code"` // 请求的返回码 + ResponseMessage string `json:"response_message"` // 请求的返回信息 + AdditionalEventData string `json:"additional_event_data"` // 额外备注信息 +} + +func (j *LogInfo) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonLogInfo{EventId: j.EventId, EventType: j.EventType, EventTime: j.EventTime, UserIdentity: j.UserIdentity, EventRw: j.EventRw, ServiceName: j.ServiceName, EventName: j.EventName, SourceIp: j.SourceIp, UserAgent: j.UserAgent, ResourceNames: j.ResourceNames, RequestId: j.RequestId, RequestUrl: j.RequestUrl, RequestParams: j.RequestParams, ResponseData: j.ResponseData, ResponseCode: j.ResponseCode, ResponseMessage: j.ResponseMessage, AdditionalEventData: j.AdditionalEventData}) +} +func (j *LogInfo) UnmarshalJSON(data []byte) error { + var nj jsonLogInfo + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.EventId = nj.EventId + j.EventType = nj.EventType + j.EventTime = nj.EventTime + j.UserIdentity = nj.UserIdentity + j.EventRw = nj.EventRw + j.ServiceName = nj.ServiceName + j.EventName = nj.EventName + j.SourceIp = nj.SourceIp + j.UserAgent = nj.UserAgent + j.ResourceNames = nj.ResourceNames + j.RequestId = nj.RequestId + j.RequestUrl = nj.RequestUrl + j.RequestParams = nj.RequestParams + j.ResponseData = nj.ResponseData + j.ResponseCode = nj.ResponseCode + j.ResponseMessage = nj.ResponseMessage + j.AdditionalEventData = nj.AdditionalEventData + return nil +} +func (j *LogInfo) validate() error { + if j.EventId == "" { + return errors.MissingRequiredFieldError{Name: "EventId"} + } + if j.EventType == "" { + return errors.MissingRequiredFieldError{Name: "EventType"} + } + if j.EventTime == "" { + return errors.MissingRequiredFieldError{Name: "EventTime"} + } + if err := j.UserIdentity.validate(); err != nil { + return err + } + if j.EventRw == "" { + return errors.MissingRequiredFieldError{Name: "EventRw"} + } + if j.ServiceName == "" { + return errors.MissingRequiredFieldError{Name: "ServiceName"} + } + if j.EventName == "" { + return errors.MissingRequiredFieldError{Name: "EventName"} + } + if j.SourceIp == "" { + return errors.MissingRequiredFieldError{Name: "SourceIp"} + } + if j.UserAgent == "" { + return errors.MissingRequiredFieldError{Name: "UserAgent"} + } + if len(j.ResourceNames) == 0 { + return errors.MissingRequiredFieldError{Name: "ResourceNames"} + } + if j.RequestId == "" { + return errors.MissingRequiredFieldError{Name: "RequestId"} + } + if j.RequestUrl == "" { + return errors.MissingRequiredFieldError{Name: "RequestUrl"} + } + if j.RequestParams == "" { + return errors.MissingRequiredFieldError{Name: "RequestParams"} + } + if j.ResponseData == "" { + return errors.MissingRequiredFieldError{Name: "ResponseData"} + } + if j.ResponseCode == 0 { + return errors.MissingRequiredFieldError{Name: "ResponseCode"} + } + if j.ResponseMessage == "" { + return errors.MissingRequiredFieldError{Name: "ResponseMessage"} + } + if j.AdditionalEventData == "" { + return errors.MissingRequiredFieldError{Name: "AdditionalEventData"} + } + return nil +} + +// 返回的审计日志列表 +type LogInfos = []LogInfo +type jsonResponse struct { + NextMark string `json:"next_mark,omitempty"` // 用于请求下一页检索的结果 + AuditLogInfos LogInfos `json:"audit_log_infos"` // 日志集合 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{NextMark: j.NextMark, AuditLogInfos: j.AuditLogInfos}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.NextMark = nj.NextMark + j.AuditLogInfos = nj.AuditLogInfos + return nil +} +func (j *Response) validate() error { + if len(j.AuditLogInfos) == 0 { + return errors.MissingRequiredFieldError{Name: "AuditLogInfos"} + } + for _, value := range j.AuditLogInfos { + if err := value.validate(); err != nil { + return err + } + } + return nil +} diff --git a/audit/doc.go b/audit/doc.go new file mode 100644 index 00000000..cf67c1dc --- /dev/null +++ b/audit/doc.go @@ -0,0 +1,5 @@ +// audit 包提供了账号审计等功能。 +package audit + +//go:generate go run ../internal/api-generator -- --api-specs=../api-specs/audit --output=apis/ --struct-name=Audit --api-package=github.com/qiniu/go-sdk/v7/audit/apis +//go:generate go build ./apis/... diff --git a/conf/conf.go b/conf/conf.go index f59b1f4b..2f90b7ce 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -4,7 +4,7 @@ import ( "github.com/qiniu/go-sdk/v7/internal/env" ) -const Version = "7.22.0" +const Version = "7.23.0" const ( CONTENT_TYPE_JSON = "application/json" diff --git a/go.mod b/go.mod index 97c0184b..05741f50 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,7 @@ require ( github.com/gofrs/flock v0.8.1 github.com/gorilla/mux v1.8.1 // indirect github.com/iancoleman/strcase v0.3.0 + github.com/jessevdk/go-flags v1.4.0 // indirect github.com/kr/pretty v0.3.0 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/matishsiao/goInfo v0.0.0-20210923090445-da2e3fa8d45f diff --git a/go.sum b/go.sum index d53b5b6b..30b3d6c4 100644 --- a/go.sum +++ b/go.sum @@ -33,9 +33,10 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= -github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 h1:rp+c0RAYOWj8l6qbCUTSiRLG/iKnW3K3/QfPPuSsBt4= github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901/go.mod h1:Z86h9688Y0wesXCyonoVr47MasHilkuLMqGhRZ4Hpak= +github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= diff --git a/iam/apis/api_create_group.go b/iam/apis/api_create_group.go new file mode 100644 index 00000000..0274dee6 --- /dev/null +++ b/iam/apis/api_create_group.go @@ -0,0 +1,93 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + creategroup "github.com/qiniu/go-sdk/v7/iam/apis/create_group" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerCreateGroupRequest creategroup.Request + +func (j *innerCreateGroupRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*creategroup.Request)(j)) +} +func (j *innerCreateGroupRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*creategroup.Request)(j)) +} + +type CreateGroupRequest = creategroup.Request +type CreateGroupResponse = creategroup.Response + +// 新建用户分组 +func (iam *Iam) CreateGroup(ctx context.Context, request *CreateGroupRequest, options *Options) (*CreateGroupResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerCreateGroupRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "groups") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("createGroup", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody CreateGroupResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_create_policy.go b/iam/apis/api_create_policy.go new file mode 100644 index 00000000..c41e3e12 --- /dev/null +++ b/iam/apis/api_create_policy.go @@ -0,0 +1,93 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + createpolicy "github.com/qiniu/go-sdk/v7/iam/apis/create_policy" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerCreatePolicyRequest createpolicy.Request + +func (j *innerCreatePolicyRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*createpolicy.Request)(j)) +} +func (j *innerCreatePolicyRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*createpolicy.Request)(j)) +} + +type CreatePolicyRequest = createpolicy.Request +type CreatePolicyResponse = createpolicy.Response + +// 新建授权策略 +func (iam *Iam) CreatePolicy(ctx context.Context, request *CreatePolicyRequest, options *Options) (*CreatePolicyResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerCreatePolicyRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("createPolicy", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody CreatePolicyResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_create_user.go b/iam/apis/api_create_user.go new file mode 100644 index 00000000..79426e25 --- /dev/null +++ b/iam/apis/api_create_user.go @@ -0,0 +1,93 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + createuser "github.com/qiniu/go-sdk/v7/iam/apis/create_user" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerCreateUserRequest createuser.Request + +func (j *innerCreateUserRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*createuser.Request)(j)) +} +func (j *innerCreateUserRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*createuser.Request)(j)) +} + +type CreateUserRequest = createuser.Request +type CreateUserResponse = createuser.Response + +// 创建 IAM 子账号 +func (iam *Iam) CreateUser(ctx context.Context, request *CreateUserRequest, options *Options) (*CreateUserResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerCreateUserRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("createUser", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody CreateUserResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_create_user_keypairs.go b/iam/apis/api_create_user_keypairs.go new file mode 100644 index 00000000..23183850 --- /dev/null +++ b/iam/apis/api_create_user_keypairs.go @@ -0,0 +1,97 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + createuserkeypairs "github.com/qiniu/go-sdk/v7/iam/apis/create_user_keypairs" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerCreateUserKeypairsRequest createuserkeypairs.Request + +func (path *innerCreateUserKeypairsRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type CreateUserKeypairsRequest = createuserkeypairs.Request +type CreateUserKeypairsResponse = createuserkeypairs.Response + +// 创建 IAM 子账号密钥 +func (iam *Iam) CreateUserKeypairs(ctx context.Context, request *CreateUserKeypairsRequest, options *Options) (*CreateUserKeypairsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerCreateUserKeypairsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "keypairs") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("createUserKeypairs", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody CreateUserKeypairsResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_delete_group.go b/iam/apis/api_delete_group.go new file mode 100644 index 00000000..3f4d1c91 --- /dev/null +++ b/iam/apis/api_delete_group.go @@ -0,0 +1,96 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + deletegroup "github.com/qiniu/go-sdk/v7/iam/apis/delete_group" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDeleteGroupRequest deletegroup.Request + +func (path *innerDeleteGroupRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type DeleteGroupRequest = deletegroup.Request +type DeleteGroupResponse = deletegroup.Response + +// 删除用户分组 +func (iam *Iam) DeleteGroup(ctx context.Context, request *DeleteGroupRequest, options *Options) (*DeleteGroupResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDeleteGroupRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("deleteGroup", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DeleteGroupResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_delete_group_policies.go b/iam/apis/api_delete_group_policies.go new file mode 100644 index 00000000..1e4ba25e --- /dev/null +++ b/iam/apis/api_delete_group_policies.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + deletegrouppolicies "github.com/qiniu/go-sdk/v7/iam/apis/delete_group_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDeleteGroupPoliciesRequest deletegrouppolicies.Request + +func (path *innerDeleteGroupPoliciesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerDeleteGroupPoliciesRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*deletegrouppolicies.Request)(j)) +} +func (j *innerDeleteGroupPoliciesRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*deletegrouppolicies.Request)(j)) +} + +type DeleteGroupPoliciesRequest = deletegrouppolicies.Request +type DeleteGroupPoliciesResponse = deletegrouppolicies.Response + +// 从用户分组中删除授权策略 +func (iam *Iam) DeleteGroupPolicies(ctx context.Context, request *DeleteGroupPoliciesRequest, options *Options) (*DeleteGroupPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDeleteGroupPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("deleteGroupPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "PATCH", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DeleteGroupPoliciesResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_delete_group_users.go b/iam/apis/api_delete_group_users.go new file mode 100644 index 00000000..611938b5 --- /dev/null +++ b/iam/apis/api_delete_group_users.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + deletegroupusers "github.com/qiniu/go-sdk/v7/iam/apis/delete_group_users" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDeleteGroupUsersRequest deletegroupusers.Request + +func (path *innerDeleteGroupUsersRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerDeleteGroupUsersRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*deletegroupusers.Request)(j)) +} +func (j *innerDeleteGroupUsersRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*deletegroupusers.Request)(j)) +} + +type DeleteGroupUsersRequest = deletegroupusers.Request +type DeleteGroupUsersResponse = deletegroupusers.Response + +// 从用户分组中删除 IAM 子账号 +func (iam *Iam) DeleteGroupUsers(ctx context.Context, request *DeleteGroupUsersRequest, options *Options) (*DeleteGroupUsersResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDeleteGroupUsersRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("deleteGroupUsers", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DeleteGroupUsersResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_delete_policy.go b/iam/apis/api_delete_policy.go new file mode 100644 index 00000000..fee516ce --- /dev/null +++ b/iam/apis/api_delete_policy.go @@ -0,0 +1,96 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + deletepolicy "github.com/qiniu/go-sdk/v7/iam/apis/delete_policy" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDeletePolicyRequest deletepolicy.Request + +func (path *innerDeletePolicyRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type DeletePolicyRequest = deletepolicy.Request +type DeletePolicyResponse = deletepolicy.Response + +// 删除指定的授权策略 +func (iam *Iam) DeletePolicy(ctx context.Context, request *DeletePolicyRequest, options *Options) (*DeletePolicyResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDeletePolicyRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "policies") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("deletePolicy", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DeletePolicyResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_delete_user.go b/iam/apis/api_delete_user.go new file mode 100644 index 00000000..1bbe7876 --- /dev/null +++ b/iam/apis/api_delete_user.go @@ -0,0 +1,96 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + deleteuser "github.com/qiniu/go-sdk/v7/iam/apis/delete_user" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDeleteUserRequest deleteuser.Request + +func (path *innerDeleteUserRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type DeleteUserRequest = deleteuser.Request +type DeleteUserResponse = deleteuser.Response + +// 删除 IAM 子账号 +func (iam *Iam) DeleteUser(ctx context.Context, request *DeleteUserRequest, options *Options) (*DeleteUserResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDeleteUserRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("deleteUser", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DeleteUserResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_delete_user_keypair.go b/iam/apis/api_delete_user_keypair.go new file mode 100644 index 00000000..80221960 --- /dev/null +++ b/iam/apis/api_delete_user_keypair.go @@ -0,0 +1,101 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + deleteuserkeypair "github.com/qiniu/go-sdk/v7/iam/apis/delete_user_keypair" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDeleteUserKeypairRequest deleteuserkeypair.Request + +func (path *innerDeleteUserKeypairRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 3) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + if path.AccessKey != "" { + allSegments = append(allSegments, "keypairs", path.AccessKey) + } else { + return nil, errors.MissingRequiredFieldError{Name: "AccessKey"} + } + return allSegments, nil +} + +type DeleteUserKeypairRequest = deleteuserkeypair.Request +type DeleteUserKeypairResponse = deleteuserkeypair.Response + +// 删除 IAM 子账号密钥 +func (iam *Iam) DeleteUserKeypair(ctx context.Context, request *DeleteUserKeypairRequest, options *Options) (*DeleteUserKeypairResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDeleteUserKeypairRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 6) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("deleteUserKeypair", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DeleteUserKeypairResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_delete_user_policy.go b/iam/apis/api_delete_user_policy.go new file mode 100644 index 00000000..8cf3fb31 --- /dev/null +++ b/iam/apis/api_delete_user_policy.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + deleteuserpolicy "github.com/qiniu/go-sdk/v7/iam/apis/delete_user_policy" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDeleteUserPolicyRequest deleteuserpolicy.Request + +func (path *innerDeleteUserPolicyRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerDeleteUserPolicyRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*deleteuserpolicy.Request)(j)) +} +func (j *innerDeleteUserPolicyRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*deleteuserpolicy.Request)(j)) +} + +type DeleteUserPolicyRequest = deleteuserpolicy.Request +type DeleteUserPolicyResponse = deleteuserpolicy.Response + +// 删除 IAM 子账号特定的授权策略 +func (iam *Iam) DeleteUserPolicy(ctx context.Context, request *DeleteUserPolicyRequest, options *Options) (*DeleteUserPolicyResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDeleteUserPolicyRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("deleteUserPolicy", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DeleteUserPolicyResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_disable_user_keypair.go b/iam/apis/api_disable_user_keypair.go new file mode 100644 index 00000000..728ea113 --- /dev/null +++ b/iam/apis/api_disable_user_keypair.go @@ -0,0 +1,102 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + disableuserkeypair "github.com/qiniu/go-sdk/v7/iam/apis/disable_user_keypair" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerDisableUserKeypairRequest disableuserkeypair.Request + +func (path *innerDisableUserKeypairRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 3) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + if path.AccessKey != "" { + allSegments = append(allSegments, "keypairs", path.AccessKey) + } else { + return nil, errors.MissingRequiredFieldError{Name: "AccessKey"} + } + return allSegments, nil +} + +type DisableUserKeypairRequest = disableuserkeypair.Request +type DisableUserKeypairResponse = disableuserkeypair.Response + +// 禁用 IAM 子账号密钥 +func (iam *Iam) DisableUserKeypair(ctx context.Context, request *DisableUserKeypairRequest, options *Options) (*DisableUserKeypairResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerDisableUserKeypairRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 7) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "disable") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("disableUserKeypair", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &DisableUserKeypairResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_enable_user_keypair.go b/iam/apis/api_enable_user_keypair.go new file mode 100644 index 00000000..431c4981 --- /dev/null +++ b/iam/apis/api_enable_user_keypair.go @@ -0,0 +1,102 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + enableuserkeypair "github.com/qiniu/go-sdk/v7/iam/apis/enable_user_keypair" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerEnableUserKeypairRequest enableuserkeypair.Request + +func (path *innerEnableUserKeypairRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 3) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + if path.AccessKey != "" { + allSegments = append(allSegments, "keypairs", path.AccessKey) + } else { + return nil, errors.MissingRequiredFieldError{Name: "AccessKey"} + } + return allSegments, nil +} + +type EnableUserKeypairRequest = enableuserkeypair.Request +type EnableUserKeypairResponse = enableuserkeypair.Response + +// 启用 IAM 子账号密钥 +func (iam *Iam) EnableUserKeypair(ctx context.Context, request *EnableUserKeypairRequest, options *Options) (*EnableUserKeypairResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerEnableUserKeypairRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 7) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "enable") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("enableUserKeypair", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &EnableUserKeypairResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_get_actions.go b/iam/apis/api_get_actions.go new file mode 100644 index 00000000..b9d5fc44 --- /dev/null +++ b/iam/apis/api_get_actions.go @@ -0,0 +1,102 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getactions "github.com/qiniu/go-sdk/v7/iam/apis/get_actions" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetActionsRequest getactions.Request + +func (query *innerGetActionsRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Service != "" { + allQuery.Set("service", query.Service) + } + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetActionsRequest = getactions.Request +type GetActionsResponse = getactions.Response + +// 查询 IAM 的操作 +func (iam *Iam) GetActions(ctx context.Context, request *GetActionsRequest, options *Options) (*GetActionsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetActionsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "actions") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getActions", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetActionsResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_audits.go b/iam/apis/api_get_audits.go new file mode 100644 index 00000000..71bea73b --- /dev/null +++ b/iam/apis/api_get_audits.go @@ -0,0 +1,117 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getaudits "github.com/qiniu/go-sdk/v7/iam/apis/get_audits" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetAuditsRequest getaudits.Request + +func (query *innerGetAuditsRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Iuid != 0 { + allQuery.Set("iuid", strconv.FormatInt(query.Iuid, 10)) + } + if query.Service != "" { + allQuery.Set("service", query.Service) + } + if query.Action != "" { + allQuery.Set("action", query.Action) + } + if query.Resource != "" { + allQuery.Set("resource", query.Resource) + } + if query.StartTime != "" { + allQuery.Set("start_time", query.StartTime) + } + if query.EndTime != "" { + allQuery.Set("end_time", query.EndTime) + } + if query.Marker != "" { + allQuery.Set("marker", query.Marker) + } + if query.Limit != 0 { + allQuery.Set("limit", strconv.FormatInt(query.Limit, 10)) + } + return allQuery, nil +} + +type GetAuditsRequest = getaudits.Request +type GetAuditsResponse = getaudits.Response + +// 查询审计日志列表 +func (iam *Iam) GetAudits(ctx context.Context, request *GetAuditsRequest, options *Options) (*GetAuditsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetAuditsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "audits") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getAudits", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetAuditsResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_group.go b/iam/apis/api_get_group.go new file mode 100644 index 00000000..4d51ba84 --- /dev/null +++ b/iam/apis/api_get_group.go @@ -0,0 +1,96 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getgroup "github.com/qiniu/go-sdk/v7/iam/apis/get_group" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerGetGroupRequest getgroup.Request + +func (path *innerGetGroupRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type GetGroupRequest = getgroup.Request +type GetGroupResponse = getgroup.Response + +// 查询指定用户分组详情 +func (iam *Iam) GetGroup(ctx context.Context, request *GetGroupRequest, options *Options) (*GetGroupResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetGroupRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("getGroup", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetGroupResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_group_policies.go b/iam/apis/api_get_group_policies.go new file mode 100644 index 00000000..344c9f03 --- /dev/null +++ b/iam/apis/api_get_group_policies.go @@ -0,0 +1,114 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getgrouppolicies "github.com/qiniu/go-sdk/v7/iam/apis/get_group_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetGroupPoliciesRequest getgrouppolicies.Request + +func (path *innerGetGroupPoliciesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (query *innerGetGroupPoliciesRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetGroupPoliciesRequest = getgrouppolicies.Request +type GetGroupPoliciesResponse = getgrouppolicies.Response + +// 查询用户分组下分配的授权策略 +func (iam *Iam) GetGroupPolicies(ctx context.Context, request *GetGroupPoliciesRequest, options *Options) (*GetGroupPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetGroupPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getGroupPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetGroupPoliciesResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_group_service_action_resources.go b/iam/apis/api_get_group_service_action_resources.go new file mode 100644 index 00000000..ae3b104a --- /dev/null +++ b/iam/apis/api_get_group_service_action_resources.go @@ -0,0 +1,107 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getgroupserviceactionresources "github.com/qiniu/go-sdk/v7/iam/apis/get_group_service_action_resources" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerGetGroupServiceActionResourcesRequest getgroupserviceactionresources.Request + +func (path *innerGetGroupServiceActionResourcesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 5) + if path.GroupAlias != "" { + allSegments = append(allSegments, path.GroupAlias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "GroupAlias"} + } + if path.Service != "" { + allSegments = append(allSegments, "services", path.Service) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Service"} + } + if path.ActionAlias != "" { + allSegments = append(allSegments, "actions", path.ActionAlias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "ActionAlias"} + } + return allSegments, nil +} + +type GetGroupServiceActionResourcesRequest = getgroupserviceactionresources.Request +type GetGroupServiceActionResourcesResponse = getgroupserviceactionresources.Response + +// 列举用户分组指定服务操作下的可访问资源 +func (iam *Iam) GetGroupServiceActionResources(ctx context.Context, request *GetGroupServiceActionResourcesRequest, options *Options) (*GetGroupServiceActionResourcesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetGroupServiceActionResourcesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 9) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "resources") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("getGroupServiceActionResources", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetGroupServiceActionResourcesResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_group_users.go b/iam/apis/api_get_group_users.go new file mode 100644 index 00000000..c4292722 --- /dev/null +++ b/iam/apis/api_get_group_users.go @@ -0,0 +1,114 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getgroupusers "github.com/qiniu/go-sdk/v7/iam/apis/get_group_users" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetGroupUsersRequest getgroupusers.Request + +func (path *innerGetGroupUsersRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (query *innerGetGroupUsersRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetGroupUsersRequest = getgroupusers.Request +type GetGroupUsersResponse = getgroupusers.Response + +// 查询用户分组下的 IAM 子账户列表 +func (iam *Iam) GetGroupUsers(ctx context.Context, request *GetGroupUsersRequest, options *Options) (*GetGroupUsersResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetGroupUsersRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getGroupUsers", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetGroupUsersResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_groups.go b/iam/apis/api_get_groups.go new file mode 100644 index 00000000..79357de5 --- /dev/null +++ b/iam/apis/api_get_groups.go @@ -0,0 +1,99 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getgroups "github.com/qiniu/go-sdk/v7/iam/apis/get_groups" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetGroupsRequest getgroups.Request + +func (query *innerGetGroupsRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetGroupsRequest = getgroups.Request +type GetGroupsResponse = getgroups.Response + +// 列举用户分组列表 +func (iam *Iam) GetGroups(ctx context.Context, request *GetGroupsRequest, options *Options) (*GetGroupsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetGroupsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "groups") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getGroups", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetGroupsResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_policies.go b/iam/apis/api_get_policies.go new file mode 100644 index 00000000..8625172c --- /dev/null +++ b/iam/apis/api_get_policies.go @@ -0,0 +1,99 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getpolicies "github.com/qiniu/go-sdk/v7/iam/apis/get_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetPoliciesRequest getpolicies.Request + +func (query *innerGetPoliciesRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetPoliciesRequest = getpolicies.Request +type GetPoliciesResponse = getpolicies.Response + +// 列举授权策略列表 +func (iam *Iam) GetPolicies(ctx context.Context, request *GetPoliciesRequest, options *Options) (*GetPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetPoliciesResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_policy.go b/iam/apis/api_get_policy.go new file mode 100644 index 00000000..75ca228f --- /dev/null +++ b/iam/apis/api_get_policy.go @@ -0,0 +1,96 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getpolicy "github.com/qiniu/go-sdk/v7/iam/apis/get_policy" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerGetPolicyRequest getpolicy.Request + +func (path *innerGetPolicyRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type GetPolicyRequest = getpolicy.Request +type GetPolicyResponse = getpolicy.Response + +// 查询指定授权策略详情 +func (iam *Iam) GetPolicy(ctx context.Context, request *GetPolicyRequest, options *Options) (*GetPolicyResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetPolicyRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "policies") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("getPolicy", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetPolicyResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_policy_groups.go b/iam/apis/api_get_policy_groups.go new file mode 100644 index 00000000..7dd05104 --- /dev/null +++ b/iam/apis/api_get_policy_groups.go @@ -0,0 +1,114 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getpolicygroups "github.com/qiniu/go-sdk/v7/iam/apis/get_policy_groups" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetPolicyGroupsRequest getpolicygroups.Request + +func (path *innerGetPolicyGroupsRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (query *innerGetPolicyGroupsRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetPolicyGroupsRequest = getpolicygroups.Request +type GetPolicyGroupsResponse = getpolicygroups.Response + +// 查询授权策略分配的用户分组列表 +func (iam *Iam) GetPolicyGroups(ctx context.Context, request *GetPolicyGroupsRequest, options *Options) (*GetPolicyGroupsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetPolicyGroupsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "policies") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "groups") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getPolicyGroups", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetPolicyGroupsResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_policy_users.go b/iam/apis/api_get_policy_users.go new file mode 100644 index 00000000..3a32d620 --- /dev/null +++ b/iam/apis/api_get_policy_users.go @@ -0,0 +1,114 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getpolicyusers "github.com/qiniu/go-sdk/v7/iam/apis/get_policy_users" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetPolicyUsersRequest getpolicyusers.Request + +func (path *innerGetPolicyUsersRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (query *innerGetPolicyUsersRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetPolicyUsersRequest = getpolicyusers.Request +type GetPolicyUsersResponse = getpolicyusers.Response + +// 查询授权策略分配的用 IAM 子账号列表 +func (iam *Iam) GetPolicyUsers(ctx context.Context, request *GetPolicyUsersRequest, options *Options) (*GetPolicyUsersResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetPolicyUsersRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "policies") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getPolicyUsers", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetPolicyUsersResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_services.go b/iam/apis/api_get_services.go new file mode 100644 index 00000000..47638f92 --- /dev/null +++ b/iam/apis/api_get_services.go @@ -0,0 +1,99 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getservices "github.com/qiniu/go-sdk/v7/iam/apis/get_services" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetServicesRequest getservices.Request + +func (query *innerGetServicesRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetServicesRequest = getservices.Request +type GetServicesResponse = getservices.Response + +// 查询 IAM 的服务列表 +func (iam *Iam) GetServices(ctx context.Context, request *GetServicesRequest, options *Options) (*GetServicesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetServicesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "services") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getServices", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetServicesResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_user.go b/iam/apis/api_get_user.go new file mode 100644 index 00000000..e07e543d --- /dev/null +++ b/iam/apis/api_get_user.go @@ -0,0 +1,96 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getuser "github.com/qiniu/go-sdk/v7/iam/apis/get_user" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerGetUserRequest getuser.Request + +func (path *innerGetUserRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type GetUserRequest = getuser.Request +type GetUserResponse = getuser.Response + +// 获取 IAM 子账号 +func (iam *Iam) GetUser(ctx context.Context, request *GetUserRequest, options *Options) (*GetUserResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetUserRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("getUser", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetUserResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_user_available_services.go b/iam/apis/api_get_user_available_services.go new file mode 100644 index 00000000..9853b99e --- /dev/null +++ b/iam/apis/api_get_user_available_services.go @@ -0,0 +1,97 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getuseravailableservices "github.com/qiniu/go-sdk/v7/iam/apis/get_user_available_services" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerGetUserAvailableServicesRequest getuseravailableservices.Request + +func (path *innerGetUserAvailableServicesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} + +type GetUserAvailableServicesRequest = getuseravailableservices.Request +type GetUserAvailableServicesResponse = getuseravailableservices.Response + +// 列举子账号可用服务 +func (iam *Iam) GetUserAvailableServices(ctx context.Context, request *GetUserAvailableServicesRequest, options *Options) (*GetUserAvailableServicesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetUserAvailableServicesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "services") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("getUserAvailableServices", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetUserAvailableServicesResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_user_groups.go b/iam/apis/api_get_user_groups.go new file mode 100644 index 00000000..7f27dec2 --- /dev/null +++ b/iam/apis/api_get_user_groups.go @@ -0,0 +1,114 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getusergroups "github.com/qiniu/go-sdk/v7/iam/apis/get_user_groups" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetUserGroupsRequest getusergroups.Request + +func (path *innerGetUserGroupsRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (query *innerGetUserGroupsRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetUserGroupsRequest = getusergroups.Request +type GetUserGroupsResponse = getusergroups.Response + +// 查询子账号所属用户分组列表 +func (iam *Iam) GetUserGroups(ctx context.Context, request *GetUserGroupsRequest, options *Options) (*GetUserGroupsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetUserGroupsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "groups") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getUserGroups", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetUserGroupsResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_user_keypairs.go b/iam/apis/api_get_user_keypairs.go new file mode 100644 index 00000000..ea997919 --- /dev/null +++ b/iam/apis/api_get_user_keypairs.go @@ -0,0 +1,114 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getuserkeypairs "github.com/qiniu/go-sdk/v7/iam/apis/get_user_keypairs" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetUserKeypairsRequest getuserkeypairs.Request + +func (path *innerGetUserKeypairsRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (query *innerGetUserKeypairsRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetUserKeypairsRequest = getuserkeypairs.Request +type GetUserKeypairsResponse = getuserkeypairs.Response + +// 列举 IAM 子账号密钥 +func (iam *Iam) GetUserKeypairs(ctx context.Context, request *GetUserKeypairsRequest, options *Options) (*GetUserKeypairsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetUserKeypairsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "keypairs") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getUserKeypairs", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetUserKeypairsResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_user_policies.go b/iam/apis/api_get_user_policies.go new file mode 100644 index 00000000..72aab8a8 --- /dev/null +++ b/iam/apis/api_get_user_policies.go @@ -0,0 +1,114 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getuserpolicies "github.com/qiniu/go-sdk/v7/iam/apis/get_user_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetUserPoliciesRequest getuserpolicies.Request + +func (path *innerGetUserPoliciesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (query *innerGetUserPoliciesRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetUserPoliciesRequest = getuserpolicies.Request +type GetUserPoliciesResponse = getuserpolicies.Response + +// 查询子账号下的授权策略 +func (iam *Iam) GetUserPolicies(ctx context.Context, request *GetUserPoliciesRequest, options *Options) (*GetUserPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetUserPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getUserPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetUserPoliciesResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_user_service_action_resources.go b/iam/apis/api_get_user_service_action_resources.go new file mode 100644 index 00000000..a24ca1c6 --- /dev/null +++ b/iam/apis/api_get_user_service_action_resources.go @@ -0,0 +1,107 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getuserserviceactionresources "github.com/qiniu/go-sdk/v7/iam/apis/get_user_service_action_resources" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerGetUserServiceActionResourcesRequest getuserserviceactionresources.Request + +func (path *innerGetUserServiceActionResourcesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 5) + if path.UserAlias != "" { + allSegments = append(allSegments, path.UserAlias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "UserAlias"} + } + if path.Service != "" { + allSegments = append(allSegments, "services", path.Service) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Service"} + } + if path.ActionAlias != "" { + allSegments = append(allSegments, "actions", path.ActionAlias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "ActionAlias"} + } + return allSegments, nil +} + +type GetUserServiceActionResourcesRequest = getuserserviceactionresources.Request +type GetUserServiceActionResourcesResponse = getuserserviceactionresources.Response + +// 列举子账号指定服务操作下的可访问资源 +func (iam *Iam) GetUserServiceActionResources(ctx context.Context, request *GetUserServiceActionResourcesRequest, options *Options) (*GetUserServiceActionResourcesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetUserServiceActionResourcesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 9) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "resources") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + uplogInterceptor, err := uplog.NewRequestUplog("getUserServiceActionResources", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetUserServiceActionResourcesResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_get_users.go b/iam/apis/api_get_users.go new file mode 100644 index 00000000..0082be96 --- /dev/null +++ b/iam/apis/api_get_users.go @@ -0,0 +1,102 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + getusers "github.com/qiniu/go-sdk/v7/iam/apis/get_users" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerGetUsersRequest getusers.Request + +func (query *innerGetUsersRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Alias != "" { + allQuery.Set("alias", query.Alias) + } + if query.Page != 0 { + allQuery.Set("page", strconv.FormatInt(query.Page, 10)) + } + if query.PageSize != 0 { + allQuery.Set("page_size", strconv.FormatInt(query.PageSize, 10)) + } + return allQuery, nil +} + +type GetUsersRequest = getusers.Request +type GetUsersResponse = getusers.Response + +// 列举 IAM 子账号 +func (iam *Iam) GetUsers(ctx context.Context, request *GetUsersRequest, options *Options) (*GetUsersResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerGetUsersRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "iam", "v1", "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("getUsers", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody GetUsersResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_modify_group.go b/iam/apis/api_modify_group.go new file mode 100644 index 00000000..b10ca053 --- /dev/null +++ b/iam/apis/api_modify_group.go @@ -0,0 +1,107 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + modifygroup "github.com/qiniu/go-sdk/v7/iam/apis/modify_group" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerModifyGroupRequest modifygroup.Request + +func (path *innerModifyGroupRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerModifyGroupRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*modifygroup.Request)(j)) +} +func (j *innerModifyGroupRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*modifygroup.Request)(j)) +} + +type ModifyGroupRequest = modifygroup.Request +type ModifyGroupResponse = modifygroup.Response + +// 更新用户分组信息 +func (iam *Iam) ModifyGroup(ctx context.Context, request *ModifyGroupRequest, options *Options) (*ModifyGroupResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerModifyGroupRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("modifyGroup", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "PATCH", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &ModifyGroupResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_modify_group_policies.go b/iam/apis/api_modify_group_policies.go new file mode 100644 index 00000000..c0d60bb5 --- /dev/null +++ b/iam/apis/api_modify_group_policies.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + modifygrouppolicies "github.com/qiniu/go-sdk/v7/iam/apis/modify_group_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerModifyGroupPoliciesRequest modifygrouppolicies.Request + +func (path *innerModifyGroupPoliciesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerModifyGroupPoliciesRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*modifygrouppolicies.Request)(j)) +} +func (j *innerModifyGroupPoliciesRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*modifygrouppolicies.Request)(j)) +} + +type ModifyGroupPoliciesRequest = modifygrouppolicies.Request +type ModifyGroupPoliciesResponse = modifygrouppolicies.Response + +// 添加授权策略到用户分组 +func (iam *Iam) ModifyGroupPolicies(ctx context.Context, request *ModifyGroupPoliciesRequest, options *Options) (*ModifyGroupPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerModifyGroupPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("modifyGroupPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "PATCH", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &ModifyGroupPoliciesResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_modify_group_users.go b/iam/apis/api_modify_group_users.go new file mode 100644 index 00000000..8940b8ef --- /dev/null +++ b/iam/apis/api_modify_group_users.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + modifygroupusers "github.com/qiniu/go-sdk/v7/iam/apis/modify_group_users" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerModifyGroupUsersRequest modifygroupusers.Request + +func (path *innerModifyGroupUsersRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerModifyGroupUsersRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*modifygroupusers.Request)(j)) +} +func (j *innerModifyGroupUsersRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*modifygroupusers.Request)(j)) +} + +type ModifyGroupUsersRequest = modifygroupusers.Request +type ModifyGroupUsersResponse = modifygroupusers.Response + +// 添加 IAM 子账号到用户分组 +func (iam *Iam) ModifyGroupUsers(ctx context.Context, request *ModifyGroupUsersRequest, options *Options) (*ModifyGroupUsersResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerModifyGroupUsersRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("modifyGroupUsers", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "PATCH", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &ModifyGroupUsersResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_modify_policy.go b/iam/apis/api_modify_policy.go new file mode 100644 index 00000000..6708fe15 --- /dev/null +++ b/iam/apis/api_modify_policy.go @@ -0,0 +1,107 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + modifypolicy "github.com/qiniu/go-sdk/v7/iam/apis/modify_policy" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerModifyPolicyRequest modifypolicy.Request + +func (path *innerModifyPolicyRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerModifyPolicyRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*modifypolicy.Request)(j)) +} +func (j *innerModifyPolicyRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*modifypolicy.Request)(j)) +} + +type ModifyPolicyRequest = modifypolicy.Request +type ModifyPolicyResponse = modifypolicy.Response + +// 修改授权策略 +func (iam *Iam) ModifyPolicy(ctx context.Context, request *ModifyPolicyRequest, options *Options) (*ModifyPolicyResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerModifyPolicyRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "policies") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("modifyPolicy", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "PATCH", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody ModifyPolicyResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_modify_user.go b/iam/apis/api_modify_user.go new file mode 100644 index 00000000..2b7e0f2c --- /dev/null +++ b/iam/apis/api_modify_user.go @@ -0,0 +1,107 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + modifyuser "github.com/qiniu/go-sdk/v7/iam/apis/modify_user" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerModifyUserRequest modifyuser.Request + +func (path *innerModifyUserRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerModifyUserRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*modifyuser.Request)(j)) +} +func (j *innerModifyUserRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*modifyuser.Request)(j)) +} + +type ModifyUserRequest = modifyuser.Request +type ModifyUserResponse = modifyuser.Response + +// 修改 IAM 子账号 +func (iam *Iam) ModifyUser(ctx context.Context, request *ModifyUserRequest, options *Options) (*ModifyUserResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerModifyUserRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 4) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("modifyUser", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "PATCH", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody ModifyUserResponse + if err := iam.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/iam/apis/api_modify_user_policies.go b/iam/apis/api_modify_user_policies.go new file mode 100644 index 00000000..08e28b79 --- /dev/null +++ b/iam/apis/api_modify_user_policies.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + modifyuserpolicies "github.com/qiniu/go-sdk/v7/iam/apis/modify_user_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerModifyUserPoliciesRequest modifyuserpolicies.Request + +func (path *innerModifyUserPoliciesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerModifyUserPoliciesRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*modifyuserpolicies.Request)(j)) +} +func (j *innerModifyUserPoliciesRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*modifyuserpolicies.Request)(j)) +} + +type ModifyUserPoliciesRequest = modifyuserpolicies.Request +type ModifyUserPoliciesResponse = modifyuserpolicies.Response + +// 为子账号添加授权策略 +func (iam *Iam) ModifyUserPolicies(ctx context.Context, request *ModifyUserPoliciesRequest, options *Options) (*ModifyUserPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerModifyUserPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("modifyUserPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "PATCH", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &ModifyUserPoliciesResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_update_group_policies.go b/iam/apis/api_update_group_policies.go new file mode 100644 index 00000000..2c5299c6 --- /dev/null +++ b/iam/apis/api_update_group_policies.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + updategrouppolicies "github.com/qiniu/go-sdk/v7/iam/apis/update_group_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerUpdateGroupPoliciesRequest updategrouppolicies.Request + +func (path *innerUpdateGroupPoliciesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerUpdateGroupPoliciesRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*updategrouppolicies.Request)(j)) +} +func (j *innerUpdateGroupPoliciesRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*updategrouppolicies.Request)(j)) +} + +type UpdateGroupPoliciesRequest = updategrouppolicies.Request +type UpdateGroupPoliciesResponse = updategrouppolicies.Response + +// 为用户分组重新分配授权策略 +func (iam *Iam) UpdateGroupPolicies(ctx context.Context, request *UpdateGroupPoliciesRequest, options *Options) (*UpdateGroupPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerUpdateGroupPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("updateGroupPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &UpdateGroupPoliciesResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_update_group_users.go b/iam/apis/api_update_group_users.go new file mode 100644 index 00000000..6da55163 --- /dev/null +++ b/iam/apis/api_update_group_users.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + updategroupusers "github.com/qiniu/go-sdk/v7/iam/apis/update_group_users" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerUpdateGroupUsersRequest updategroupusers.Request + +func (path *innerUpdateGroupUsersRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerUpdateGroupUsersRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*updategroupusers.Request)(j)) +} +func (j *innerUpdateGroupUsersRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*updategroupusers.Request)(j)) +} + +type UpdateGroupUsersRequest = updategroupusers.Request +type UpdateGroupUsersResponse = updategroupusers.Response + +// 为用户分组中重新分配 IAM 子账号 +func (iam *Iam) UpdateGroupUsers(ctx context.Context, request *UpdateGroupUsersRequest, options *Options) (*UpdateGroupUsersResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerUpdateGroupUsersRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "groups") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("updateGroupUsers", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &UpdateGroupUsersResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_update_policy_groups.go b/iam/apis/api_update_policy_groups.go new file mode 100644 index 00000000..3dd9761c --- /dev/null +++ b/iam/apis/api_update_policy_groups.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + updatepolicygroups "github.com/qiniu/go-sdk/v7/iam/apis/update_policy_groups" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerUpdatePolicyGroupsRequest updatepolicygroups.Request + +func (path *innerUpdatePolicyGroupsRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerUpdatePolicyGroupsRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*updatepolicygroups.Request)(j)) +} +func (j *innerUpdatePolicyGroupsRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*updatepolicygroups.Request)(j)) +} + +type UpdatePolicyGroupsRequest = updatepolicygroups.Request +type UpdatePolicyGroupsResponse = updatepolicygroups.Response + +// 重新分配用户分组给指定策略 +func (iam *Iam) UpdatePolicyGroups(ctx context.Context, request *UpdatePolicyGroupsRequest, options *Options) (*UpdatePolicyGroupsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerUpdatePolicyGroupsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "policies") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "groups") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("updatePolicyGroups", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &UpdatePolicyGroupsResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_update_policy_users.go b/iam/apis/api_update_policy_users.go new file mode 100644 index 00000000..e05d6080 --- /dev/null +++ b/iam/apis/api_update_policy_users.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + updatepolicyusers "github.com/qiniu/go-sdk/v7/iam/apis/update_policy_users" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerUpdatePolicyUsersRequest updatepolicyusers.Request + +func (path *innerUpdatePolicyUsersRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerUpdatePolicyUsersRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*updatepolicyusers.Request)(j)) +} +func (j *innerUpdatePolicyUsersRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*updatepolicyusers.Request)(j)) +} + +type UpdatePolicyUsersRequest = updatepolicyusers.Request +type UpdatePolicyUsersResponse = updatepolicyusers.Response + +// 重新分配用户给指定授权策略 +func (iam *Iam) UpdatePolicyUsers(ctx context.Context, request *UpdatePolicyUsersRequest, options *Options) (*UpdatePolicyUsersResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerUpdatePolicyUsersRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "policies") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "users") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("updatePolicyUsers", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &UpdatePolicyUsersResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_update_user_groups.go b/iam/apis/api_update_user_groups.go new file mode 100644 index 00000000..16395803 --- /dev/null +++ b/iam/apis/api_update_user_groups.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + updateusergroups "github.com/qiniu/go-sdk/v7/iam/apis/update_user_groups" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerUpdateUserGroupsRequest updateusergroups.Request + +func (path *innerUpdateUserGroupsRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerUpdateUserGroupsRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*updateusergroups.Request)(j)) +} +func (j *innerUpdateUserGroupsRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*updateusergroups.Request)(j)) +} + +type UpdateUserGroupsRequest = updateusergroups.Request +type UpdateUserGroupsResponse = updateusergroups.Response + +// 为用户重新分配分组 +func (iam *Iam) UpdateUserGroups(ctx context.Context, request *UpdateUserGroupsRequest, options *Options) (*UpdateUserGroupsResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerUpdateUserGroupsRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "groups") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("updateUserGroups", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &UpdateUserGroupsResponse{}, resp.Body.Close() +} diff --git a/iam/apis/api_update_user_policies.go b/iam/apis/api_update_user_policies.go new file mode 100644 index 00000000..94f63afd --- /dev/null +++ b/iam/apis/api_update_user_policies.go @@ -0,0 +1,108 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + updateuserpolicies "github.com/qiniu/go-sdk/v7/iam/apis/update_user_policies" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerUpdateUserPoliciesRequest updateuserpolicies.Request + +func (path *innerUpdateUserPoliciesRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.Alias != "" { + allSegments = append(allSegments, path.Alias) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Alias"} + } + return allSegments, nil +} +func (j *innerUpdateUserPoliciesRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*updateuserpolicies.Request)(j)) +} +func (j *innerUpdateUserPoliciesRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*updateuserpolicies.Request)(j)) +} + +type UpdateUserPoliciesRequest = updateuserpolicies.Request +type UpdateUserPoliciesResponse = updateuserpolicies.Response + +// 为子账号重新分配授权策略 +func (iam *Iam) UpdateUserPolicies(ctx context.Context, request *UpdateUserPoliciesRequest, options *Options) (*UpdateUserPoliciesResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerUpdateUserPoliciesRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && iam.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 5) + pathSegments = append(pathSegments, "iam", "v1", "users") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "policies") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("updateUserPolicies", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && iam.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = iam.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: iam.client.UseInsecureProtocol(), HostFreezeDuration: iam.client.GetHostFreezeDuration(), Resolver: iam.client.GetResolver(), Chooser: iam.client.GetChooser(), BeforeSign: iam.client.GetBeforeSignCallback(), AfterSign: iam.client.GetAfterSignCallback(), SignError: iam.client.GetSignErrorCallback(), BeforeResolve: iam.client.GetBeforeResolveCallback(), AfterResolve: iam.client.GetAfterResolveCallback(), ResolveError: iam.client.GetResolveErrorCallback(), BeforeBackoff: iam.client.GetBeforeBackoffCallback(), AfterBackoff: iam.client.GetAfterBackoffCallback(), BeforeRequest: iam.client.GetBeforeRequestCallback(), AfterResponse: iam.client.GetAfterResponseCallback()} + if hostRetryConfig := iam.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = iam.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + resp, err := iam.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &UpdateUserPoliciesResponse{}, resp.Body.Close() +} diff --git a/iam/apis/apis.go b/iam/apis/apis.go new file mode 100644 index 00000000..dd6fab1d --- /dev/null +++ b/iam/apis/apis.go @@ -0,0 +1,27 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" +) + +// API 客户端 +type Iam struct { + client *httpclient.Client +} + +// 创建 API 客户端 +func NewIam(options *httpclient.Options) *Iam { + return &Iam{client: httpclient.NewClient(options)} +} + +// API 客户端选项 +type Options struct { + OverwrittenBucketHosts region.EndpointsProvider + OverwrittenBucketName string + OverwrittenEndpoints region.EndpointsProvider + OverwrittenRegion region.RegionsProvider + OnRequestProgress func(uint64, uint64) +} diff --git a/iam/apis/create_group/api.go b/iam/apis/create_group/api.go new file mode 100644 index 00000000..5c5e1407 --- /dev/null +++ b/iam/apis/create_group/api.go @@ -0,0 +1,140 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 新建用户分组 +package create_group + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + Alias string // 用户分组别名,由 `A-Za-z0-9` 组成 + Description string // 用户分组描述 +} + +// 创建用户分组参数 +type CreateGroupParam = Request +type jsonRequest struct { + Alias string `json:"alias,omitempty"` // 用户分组别名,由 `A-Za-z0-9` 组成 + Description string `json:"description,omitempty"` // 用户分组描述 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{Alias: j.Alias, Description: j.Description}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Alias = nj.Alias + j.Description = nj.Description + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct { + Data CreatedGroupData // 用户分组信息 +} + +// 用户分组信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 用户分组别名 + Description string // 用户分组描述 + Enabled bool // 用户分组是否启用 + CreatedAt string // 用户分组创建时间 + UpdatedAt string // 用户分组上次更新时间 +} + +// 返回的用户分组信息 +type CreatedGroupData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 用户分组别名 + Description string `json:"description"` // 用户分组描述 + Enabled bool `json:"enabled"` // 用户分组是否启用 + CreatedAt string `json:"created_at"` // 用户分组创建时间 + UpdatedAt string `json:"updated_at"` // 用户分组上次更新时间 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + return nil +} + +// 返回的用户分组响应 +type CreatedGroupResp = Response +type jsonResponse struct { + Data CreatedGroupData `json:"data"` // 用户分组信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/create_policy/api.go b/iam/apis/create_policy/api.go new file mode 100644 index 00000000..4a3c17ea --- /dev/null +++ b/iam/apis/create_policy/api.go @@ -0,0 +1,265 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 新建授权策略 +package create_policy + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + Alias string // 授权策略别名,由 `A-Za-z0-9` 组成 + EditType int64 // 1:是通过自定义 JSON 编辑的策略 2:是通过 UI 编辑的策略 + Description string // 授权策略描述 + Statement CreateStatements // 授权策略规则集合 +} + +// 授权策略规则的操作集合 +type CreateActions = []string + +// 授权策略规则的资源集合 +type CreateResources = []string + +// 授权策略规则 +type CreateStatement struct { + Actions CreateActions // 授权策略规则的操作集合,action 查询参考 action 接口,格式为 service/action_alias + Resources CreateResources // 授权策略规则的资源集合,格式为 qrn:product:region:uid:[resource-type/]resource-id ;可以简写为 qrn:product:::resource-id + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonCreateStatement struct { + Actions CreateActions `json:"action"` // 授权策略规则的操作集合,action 查询参考 action 接口,格式为 service/action_alias + Resources CreateResources `json:"resource"` // 授权策略规则的资源集合,格式为 qrn:product:region:uid:[resource-type/]resource-id ;可以简写为 qrn:product:::resource-id + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *CreateStatement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonCreateStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *CreateStatement) UnmarshalJSON(data []byte) error { + var nj jsonCreateStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *CreateStatement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type CreateStatements = []CreateStatement + +// 创建授权策略参数 +type CreatePolicyParam = Request +type jsonRequest struct { + Alias string `json:"alias,omitempty"` // 授权策略别名,由 `A-Za-z0-9` 组成 + EditType int64 `json:"edit_type,omitempty"` // 1:是通过自定义 JSON 编辑的策略 2:是通过 UI 编辑的策略 + Description string `json:"description,omitempty"` // 授权策略描述 + Statement CreateStatements `json:"statement"` // 授权策略规则集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{Alias: j.Alias, EditType: j.EditType, Description: j.Description, Statement: j.Statement}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Alias = nj.Alias + j.EditType = nj.EditType + j.Description = nj.Description + j.Statement = nj.Statement + return nil +} +func (j *Request) validate() error { + if len(j.Statement) == 0 { + return errors.MissingRequiredFieldError{Name: "Statement"} + } + for _, value := range j.Statement { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 获取 API 所用的响应 +type Response struct { + Data CreatedPolicyData // 授权策略信息 +} + +// 授权策略规则的操作集合 +type CreatedActions = []string + +// 授权策略规则的资源集合 +type CreatedResources = []string + +// 授权策略规则 +type CreatedStatement struct { + Actions CreatedActions // 授权策略规则的操作集合 + Resources CreatedResources // 授权策略规则的资源集合 + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonCreatedStatement struct { + Actions CreatedActions `json:"action"` // 授权策略规则的操作集合 + Resources CreatedResources `json:"resource"` // 授权策略规则的资源集合 + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *CreatedStatement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonCreatedStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *CreatedStatement) UnmarshalJSON(data []byte) error { + var nj jsonCreatedStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *CreatedStatement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type CreatedStatements = []CreatedStatement + +// 授权策略信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 授权策略别名 + Description string // 授权策略描述 + Enabled bool // 授权策略是否启用 + CreatedAt string // 授权策略创建时间 + UpdatedAt string // 授权策略上次更新时间 + Statement CreatedStatements // 授权策略规则集合 +} + +// 返回的授权策略信息 +type CreatedPolicyData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 授权策略别名 + Description string `json:"description"` // 授权策略描述 + Enabled bool `json:"enabled"` // 授权策略是否启用 + CreatedAt string `json:"created_at"` // 授权策略创建时间 + UpdatedAt string `json:"updated_at"` // 授权策略上次更新时间 + Statement CreatedStatements `json:"statement"` // 授权策略规则集合 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, Statement: j.Statement}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.Statement = nj.Statement + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if len(j.Statement) == 0 { + return errors.MissingRequiredFieldError{Name: "Statement"} + } + for _, value := range j.Statement { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的授权策略响应 +type CreatedPolicyResp = Response +type jsonResponse struct { + Data CreatedPolicyData `json:"data"` // 授权策略信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/create_user/api.go b/iam/apis/create_user/api.go new file mode 100644 index 00000000..2b87c613 --- /dev/null +++ b/iam/apis/create_user/api.go @@ -0,0 +1,152 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 创建 IAM 子账号 +package create_user + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + Alias string // 子账号别名 + Password string // 子账号密码 +} + +// 创建 IAM 子账号参数 +type CreateIamUserParam = Request +type jsonRequest struct { + Alias string `json:"alias"` // 子账号别名 + Password string `json:"password"` // 子账号密码 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{Alias: j.Alias, Password: j.Password}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Alias = nj.Alias + j.Password = nj.Password + return nil +} +func (j *Request) validate() error { + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Password == "" { + return errors.MissingRequiredFieldError{Name: "Password"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct { + Data CreatedIamUserData // IAM 子账号信息 +} + +// IAM 子账号信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Iuid int64 // 子账号 uid + Alias string // 子账号别名 + CreatedAt string // 子账号创建时间 + UpdatedAt string // 子账号上次更新时间 + LastLoginTime string // 子账号上次更新时间 + Enabled bool // 子账号是否启用 +} + +// 返回的 IAM 子账号信息 +type CreatedIamUserData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Iuid int64 `json:"iuid"` // 子账号 uid + Alias string `json:"alias"` // 子账号别名 + CreatedAt string `json:"created_at"` // 子账号创建时间 + UpdatedAt string `json:"updated_at"` // 子账号上次更新时间 + LastLoginTime string `json:"last_login_time"` // 子账号上次更新时间 + Enabled bool `json:"enabled"` // 子账号是否启用 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Iuid: j.Iuid, Alias: j.Alias, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, LastLoginTime: j.LastLoginTime, Enabled: j.Enabled}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Iuid = nj.Iuid + j.Alias = nj.Alias + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.LastLoginTime = nj.LastLoginTime + j.Enabled = nj.Enabled + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Iuid == 0 { + return errors.MissingRequiredFieldError{Name: "Iuid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if j.LastLoginTime == "" { + return errors.MissingRequiredFieldError{Name: "LastLoginTime"} + } + return nil +} + +// 返回的 IAM 子账号响应 +type CreatedIamUserResp = Response +type jsonResponse struct { + Data CreatedIamUserData `json:"data"` // IAM 子账号信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/create_user_keypairs/api.go b/iam/apis/create_user_keypairs/api.go new file mode 100644 index 00000000..ee58a1af --- /dev/null +++ b/iam/apis/create_user_keypairs/api.go @@ -0,0 +1,107 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 创建 IAM 子账号密钥 +package create_user_keypairs + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data CreatedIamUserKeyPairData // IAM 子账号密钥信息 +} + +// IAM 子账号密钥信息 +type Data struct { + Id string // 记录 ID + AccessKey string // IAM 子账号 Access Key + SecretKey string // IAM 子账号 Secret Key + UserId string // 关联用户的记录 ID + CreatedAt string // 密钥创建时间 + Enabled bool // 密钥是否启用 +} + +// 返回的 IAM 子账号密钥信息 +type CreatedIamUserKeyPairData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + AccessKey string `json:"access_key"` // IAM 子账号 Access Key + SecretKey string `json:"secret_key"` // IAM 子账号 Secret Key + UserId string `json:"user_id"` // 关联用户的记录 ID + CreatedAt string `json:"created_at"` // 密钥创建时间 + Enabled bool `json:"enabled"` // 密钥是否启用 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, AccessKey: j.AccessKey, SecretKey: j.SecretKey, UserId: j.UserId, CreatedAt: j.CreatedAt, Enabled: j.Enabled}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.AccessKey = nj.AccessKey + j.SecretKey = nj.SecretKey + j.UserId = nj.UserId + j.CreatedAt = nj.CreatedAt + j.Enabled = nj.Enabled + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.AccessKey == "" { + return errors.MissingRequiredFieldError{Name: "AccessKey"} + } + if j.SecretKey == "" { + return errors.MissingRequiredFieldError{Name: "SecretKey"} + } + if j.UserId == "" { + return errors.MissingRequiredFieldError{Name: "UserId"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + return nil +} + +// 返回的 IAM 子账号密钥响应 +type CreatedIamUserKeyPairResp = Response +type jsonResponse struct { + Data CreatedIamUserKeyPairData `json:"data"` // IAM 子账号密钥信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/delete_group/api.go b/iam/apis/delete_group/api.go new file mode 100644 index 00000000..22e9764f --- /dev/null +++ b/iam/apis/delete_group/api.go @@ -0,0 +1,15 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 删除用户分组 +package delete_group + +import credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/delete_group_policies/api.go b/iam/apis/delete_group_policies/api.go new file mode 100644 index 00000000..b466b6dd --- /dev/null +++ b/iam/apis/delete_group_policies/api.go @@ -0,0 +1,50 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 从用户分组中删除授权策略 +package delete_group_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + PolicyAliases PolicyAliases // 授权策略别名集合 +} + +// 从用户分组中删除的授权策略别名集合 +type PolicyAliases = []string + +// 从用户分组中删除授权策略参数 +type DeletedGroupIamPoliciesParam = Request +type jsonRequest struct { + PolicyAliases PolicyAliases `json:"policy_aliases"` // 授权策略别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{PolicyAliases: j.PolicyAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PolicyAliases = nj.PolicyAliases + return nil +} +func (j *Request) validate() error { + if len(j.PolicyAliases) == 0 { + return errors.MissingRequiredFieldError{Name: "PolicyAliases"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/delete_group_users/api.go b/iam/apis/delete_group_users/api.go new file mode 100644 index 00000000..f6271263 --- /dev/null +++ b/iam/apis/delete_group_users/api.go @@ -0,0 +1,50 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 从用户分组中删除 IAM 子账号 +package delete_group_users + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + UserAliases UserAliases // IAM 子账号别名集合 +} + +// 从用户分组中删除 IAM 子账号别名集合 +type UserAliases = []string + +// 从用户分组删除 IAM 子账号参数 +type DeletedGroupIamUsersParam = Request +type jsonRequest struct { + UserAliases UserAliases `json:"user_aliases"` // IAM 子账号别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{UserAliases: j.UserAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.UserAliases = nj.UserAliases + return nil +} +func (j *Request) validate() error { + if len(j.UserAliases) == 0 { + return errors.MissingRequiredFieldError{Name: "UserAliases"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/delete_policy/api.go b/iam/apis/delete_policy/api.go new file mode 100644 index 00000000..a41a2648 --- /dev/null +++ b/iam/apis/delete_policy/api.go @@ -0,0 +1,15 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 删除指定的授权策略 +package delete_policy + +import credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + +// 调用 API 所用的请求 +type Request struct { + Alias string // 授权策略别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/delete_user/api.go b/iam/apis/delete_user/api.go new file mode 100644 index 00000000..4129e7da --- /dev/null +++ b/iam/apis/delete_user/api.go @@ -0,0 +1,15 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 删除 IAM 子账号 +package delete_user + +import credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/delete_user_keypair/api.go b/iam/apis/delete_user_keypair/api.go new file mode 100644 index 00000000..e96ca724 --- /dev/null +++ b/iam/apis/delete_user_keypair/api.go @@ -0,0 +1,16 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 删除 IAM 子账号密钥 +package delete_user_keypair + +import credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + AccessKey string // IAM 子账号 Access Key + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/delete_user_policy/api.go b/iam/apis/delete_user_policy/api.go new file mode 100644 index 00000000..73f8ca22 --- /dev/null +++ b/iam/apis/delete_user_policy/api.go @@ -0,0 +1,50 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 删除 IAM 子账号特定的授权策略 +package delete_user_policy + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + PolicyAliases PolicyAliases // 授权策略别名集合 +} + +// 删除用户的授权策略别名集合 +type PolicyAliases = []string + +// 为子账号删除授权策略参数 +type DeletedIamUserPoliciesParam = Request +type jsonRequest struct { + PolicyAliases PolicyAliases `json:"policy_aliases"` // 授权策略别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{PolicyAliases: j.PolicyAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PolicyAliases = nj.PolicyAliases + return nil +} +func (j *Request) validate() error { + if len(j.PolicyAliases) == 0 { + return errors.MissingRequiredFieldError{Name: "PolicyAliases"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/disable_user_keypair/api.go b/iam/apis/disable_user_keypair/api.go new file mode 100644 index 00000000..9e4682e3 --- /dev/null +++ b/iam/apis/disable_user_keypair/api.go @@ -0,0 +1,16 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 禁用 IAM 子账号密钥 +package disable_user_keypair + +import credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + AccessKey string // IAM 子账号 Access Key + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/enable_user_keypair/api.go b/iam/apis/enable_user_keypair/api.go new file mode 100644 index 00000000..01c3a52d --- /dev/null +++ b/iam/apis/enable_user_keypair/api.go @@ -0,0 +1,16 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 启用 IAM 子账号密钥 +package enable_user_keypair + +import credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + AccessKey string // IAM 子账号 Access Key + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/get_actions/api.go b/iam/apis/get_actions/api.go new file mode 100644 index 00000000..41d4b2b6 --- /dev/null +++ b/iam/apis/get_actions/api.go @@ -0,0 +1,164 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询 IAM 的操作 +package get_actions + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Service string // 操作对应的服务别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetActionsData // 接口操作信息 +} + +// 返回的接口操作 +type GetAction struct { + Id string // 记录 ID + Name string // 接口操作名称 + Alias string // 接口操作别名 + Service string // 接口操作对应的服务 + Scope int64 // 接口操作权限粒度,0: 操作级,不限制资源,1: 资源级,只能访问特定资源 + Enabled bool // 接口操作是否启用 + CreatedAt string // 接口操作创建时间 + UpdatedAt string // 接口操作上次更新时间 +} +type jsonGetAction struct { + Id string `json:"id"` // 记录 ID + Name string `json:"name"` // 接口操作名称 + Alias string `json:"alias"` // 接口操作别名 + Service string `json:"service"` // 接口操作对应的服务 + Scope int64 `json:"scope"` // 接口操作权限粒度,0: 操作级,不限制资源,1: 资源级,只能访问特定资源 + Enabled bool `json:"enabled"` // 接口操作是否启用 + CreatedAt string `json:"created_at"` // 接口操作创建时间 + UpdatedAt string `json:"updated_at"` // 接口操作上次更新时间 +} + +func (j *GetAction) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGetAction{Id: j.Id, Name: j.Name, Alias: j.Alias, Service: j.Service, Scope: j.Scope, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt}) +} +func (j *GetAction) UnmarshalJSON(data []byte) error { + var nj jsonGetAction + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.Name = nj.Name + j.Alias = nj.Alias + j.Service = nj.Service + j.Scope = nj.Scope + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + return nil +} +func (j *GetAction) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.Name == "" { + return errors.MissingRequiredFieldError{Name: "Name"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Service == "" { + return errors.MissingRequiredFieldError{Name: "Service"} + } + if j.Scope == 0 { + return errors.MissingRequiredFieldError{Name: "Scope"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + return nil +} + +// 返回的接口操作列表 +type GetActions = []GetAction + +// 接口操作信息 +type Data struct { + Count int64 // 接口操作数量 + List GetActions // 接口操作列表 +} + +// 返回的接口操作列表信息 +type GetActionsData = Data +type jsonData struct { + Count int64 `json:"count"` // 接口操作数量 + List GetActions `json:"list"` // 接口操作列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的接口操作列表响应 +type GetActionsResp = Response +type jsonResponse struct { + Data GetActionsData `json:"data"` // 接口操作信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_audits/api.go b/iam/apis/get_audits/api.go new file mode 100644 index 00000000..7ff9d444 --- /dev/null +++ b/iam/apis/get_audits/api.go @@ -0,0 +1,196 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询审计日志列表 +package get_audits + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Iuid int64 // IAM 子账号 UID + Service string // 操作对应的服务别名 + Action string // 操作别名 + Resource string // 操作别名 + StartTime string // 操作开始时间 + EndTime string // 操作截止时间 + Marker string // 下页标记 + Limit int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetAuditLogsData // 审计日志信息 +} + +// 返回的审计日志 +type GetAuditLog struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Iuid int64 // 子账号 uid + Service string // 接口操作对应的服务 + Action string // 接口操作别名 + CreatedAt string // 日志创建时间 + EventTime string // 请求发生时间 + DurationMs int64 // 请求持续时间,毫秒 + SourceIp string // 源 IP + UserEvent string // 用户代理 + ErrorCode int64 // 错误码 + ErrorMessage string // 错误消息 +} +type jsonGetAuditLog struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Iuid int64 `json:"iuid"` // 子账号 uid + Service string `json:"service"` // 接口操作对应的服务 + Action string `json:"action"` // 接口操作别名 + CreatedAt string `json:"created_at"` // 日志创建时间 + EventTime string `json:"event_time"` // 请求发生时间 + DurationMs int64 `json:"duration_ms"` // 请求持续时间,毫秒 + SourceIp string `json:"source_ip"` // 源 IP + UserEvent string `json:"user_event"` // 用户代理 + ErrorCode int64 `json:"error_code"` // 错误码 + ErrorMessage string `json:"error_message"` // 错误消息 +} + +func (j *GetAuditLog) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGetAuditLog{Id: j.Id, RootUid: j.RootUid, Iuid: j.Iuid, Service: j.Service, Action: j.Action, CreatedAt: j.CreatedAt, EventTime: j.EventTime, DurationMs: j.DurationMs, SourceIp: j.SourceIp, UserEvent: j.UserEvent, ErrorCode: j.ErrorCode, ErrorMessage: j.ErrorMessage}) +} +func (j *GetAuditLog) UnmarshalJSON(data []byte) error { + var nj jsonGetAuditLog + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Iuid = nj.Iuid + j.Service = nj.Service + j.Action = nj.Action + j.CreatedAt = nj.CreatedAt + j.EventTime = nj.EventTime + j.DurationMs = nj.DurationMs + j.SourceIp = nj.SourceIp + j.UserEvent = nj.UserEvent + j.ErrorCode = nj.ErrorCode + j.ErrorMessage = nj.ErrorMessage + return nil +} +func (j *GetAuditLog) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Iuid == 0 { + return errors.MissingRequiredFieldError{Name: "Iuid"} + } + if j.Service == "" { + return errors.MissingRequiredFieldError{Name: "Service"} + } + if j.Action == "" { + return errors.MissingRequiredFieldError{Name: "Action"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.EventTime == "" { + return errors.MissingRequiredFieldError{Name: "EventTime"} + } + if j.DurationMs == 0 { + return errors.MissingRequiredFieldError{Name: "DurationMs"} + } + if j.SourceIp == "" { + return errors.MissingRequiredFieldError{Name: "SourceIp"} + } + if j.UserEvent == "" { + return errors.MissingRequiredFieldError{Name: "UserEvent"} + } + if j.ErrorCode == 0 { + return errors.MissingRequiredFieldError{Name: "ErrorCode"} + } + if j.ErrorMessage == "" { + return errors.MissingRequiredFieldError{Name: "ErrorMessage"} + } + return nil +} + +// 返回的审计日志列表 +type GetAuditLogs = []GetAuditLog + +// 审计日志信息 +type Data struct { + Marker string // 下页标记 + List GetAuditLogs // 审计日志列表 +} + +// 返回的审计日志列表信息 +type GetAuditLogsData = Data +type jsonData struct { + Marker string `json:"marker"` // 下页标记 + List GetAuditLogs `json:"list"` // 审计日志列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Marker: j.Marker, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Marker = nj.Marker + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Marker == "" { + return errors.MissingRequiredFieldError{Name: "Marker"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的审计日志列表响应 +type GetAuditLogsResp = Response +type jsonResponse struct { + Data GetAuditLogsData `json:"data"` // 审计日志信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_group/api.go b/iam/apis/get_group/api.go new file mode 100644 index 00000000..398b83fd --- /dev/null +++ b/iam/apis/get_group/api.go @@ -0,0 +1,113 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询指定用户分组详情 +package get_group + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetGroupData // 用户分组信息 +} + +// 用户分组信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 用户分组别名 + Description string // 用户分组描述 + Enabled bool // 用户分组是否启用 + CreatedAt string // 用户分组创建时间 + UpdatedAt string // 用户分组上次更新时间 +} + +// 返回的用户分组信息 +type GetGroupData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 用户分组别名 + Description string `json:"description"` // 用户分组描述 + Enabled bool `json:"enabled"` // 用户分组是否启用 + CreatedAt string `json:"created_at"` // 用户分组创建时间 + UpdatedAt string `json:"updated_at"` // 用户分组上次更新时间 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + return nil +} + +// 返回的用户分组响应 +type GetGroupResp = Response +type jsonResponse struct { + Data GetGroupData `json:"data"` // 用户分组信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_group_policies/api.go b/iam/apis/get_group_policies/api.go new file mode 100644 index 00000000..45a6d13c --- /dev/null +++ b/iam/apis/get_group_policies/api.go @@ -0,0 +1,219 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询用户分组下分配的授权策略 +package get_group_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetGroupPoliciesData // 用户分组下的授权策略信息 +} + +// 授权策略规则的操作集合 +type Actions = []string + +// 授权策略规则的资源集合 +type Resources = []string + +// 授权策略规则 +type Statement struct { + Actions Actions // 授权策略规则的操作集合 + Resources Resources // 授权策略规则的资源集合 + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonStatement struct { + Actions Actions `json:"action"` // 授权策略规则的操作集合 + Resources Resources `json:"resource"` // 授权策略规则的资源集合 + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *Statement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *Statement) UnmarshalJSON(data []byte) error { + var nj jsonStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *Statement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type Statements = []Statement + +// 返回的用户分组下的授权策略 +type GroupPolicy struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 授权策略别名 + Description string // 授权策略描述 + Enabled bool // 授权策略是否启用 + CreatedAt string // 授权策略创建时间 + UpdatedAt string // 授权策略上次更新时间 + Statement Statements // 授权策略规则集合 +} +type jsonGroupPolicy struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 授权策略别名 + Description string `json:"description"` // 授权策略描述 + Enabled bool `json:"enabled"` // 授权策略是否启用 + CreatedAt string `json:"created_at"` // 授权策略创建时间 + UpdatedAt string `json:"updated_at"` // 授权策略上次更新时间 + Statement Statements `json:"statement"` // 授权策略规则集合 +} + +func (j *GroupPolicy) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGroupPolicy{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, Statement: j.Statement}) +} +func (j *GroupPolicy) UnmarshalJSON(data []byte) error { + var nj jsonGroupPolicy + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.Statement = nj.Statement + return nil +} +func (j *GroupPolicy) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if len(j.Statement) == 0 { + return errors.MissingRequiredFieldError{Name: "Statement"} + } + for _, value := range j.Statement { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的用户分组下的授权策略列表 +type GetGroupPolicies = []GroupPolicy + +// 用户分组下的授权策略信息 +type Data struct { + Count int64 // 用户分组下的授权策略数量 + List GetGroupPolicies // 用户分组下的授权策略列表 +} + +// 返回的用户分组下的授权策略列表信息 +type GetGroupPoliciesData = Data +type jsonData struct { + Count int64 `json:"count"` // 用户分组下的授权策略数量 + List GetGroupPolicies `json:"list"` // 用户分组下的授权策略列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的用户分组下的授权策略列表响应 +type GetGroupPoliciesResp = Response +type jsonResponse struct { + Data GetGroupPoliciesData `json:"data"` // 用户分组下的授权策略信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_group_service_action_resources/api.go b/iam/apis/get_group_service_action_resources/api.go new file mode 100644 index 00000000..f3147c15 --- /dev/null +++ b/iam/apis/get_group_service_action_resources/api.go @@ -0,0 +1,94 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 列举用户分组指定服务操作下的可访问资源 +package get_group_service_action_resources + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + GroupAlias string // 用户分组别名 + Service string // 资源操作关联的服务 + ActionAlias string // 资源操作别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetGroupServiceActionResources // 用户分组指定服务操作下的可访问资源列表信息 +} + +// 可用资源列表 +type AllowedResources = []string + +// 禁用资源列表 +type DeniedResources = []string + +// 用户分组指定服务操作下的可访问资源列表信息 +type Data struct { + AllowedResources AllowedResources // 可用资源 + DeniedResources DeniedResources // 禁用资源 +} + +// 返回的用户分组指定服务操作下的可访问资源列表信息 +type GetGroupServiceActionResources = Data +type jsonData struct { + AllowedResources AllowedResources `json:"allow"` // 可用资源 + DeniedResources DeniedResources `json:"deny"` // 禁用资源 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{AllowedResources: j.AllowedResources, DeniedResources: j.DeniedResources}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.AllowedResources = nj.AllowedResources + j.DeniedResources = nj.DeniedResources + return nil +} +func (j *Data) validate() error { + if len(j.AllowedResources) == 0 { + return errors.MissingRequiredFieldError{Name: "AllowedResources"} + } + if len(j.DeniedResources) == 0 { + return errors.MissingRequiredFieldError{Name: "DeniedResources"} + } + return nil +} + +// 返回的用户分组指定服务操作下的可访问资源列表响应 +type GetGroupServiceActionResourcesResp = Response +type jsonResponse struct { + Data GetGroupServiceActionResources `json:"data"` // 用户分组指定服务操作下的可访问资源列表信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_group_users/api.go b/iam/apis/get_group_users/api.go new file mode 100644 index 00000000..47c60e28 --- /dev/null +++ b/iam/apis/get_group_users/api.go @@ -0,0 +1,164 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询用户分组下的 IAM 子账户列表 +package get_group_users + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetGroupIamUsersData // 用户分组下的 IAM 子账号信息 +} + +// 返回的用户分组下的 IAM 子账号 +type GroupIamUser struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Iuid int64 // 子账号 uid + Alias string // 子账号别名 + CreatedAt string // 子账号创建时间 + UpdatedAt string // 子账号上次更新时间 + LastLoginTime string // 子账号上次更新时间 + Enabled bool // 子账号是否启用 +} +type jsonGroupIamUser struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Iuid int64 `json:"iuid"` // 子账号 uid + Alias string `json:"alias"` // 子账号别名 + CreatedAt string `json:"created_at"` // 子账号创建时间 + UpdatedAt string `json:"updated_at"` // 子账号上次更新时间 + LastLoginTime string `json:"last_login_time"` // 子账号上次更新时间 + Enabled bool `json:"enabled"` // 子账号是否启用 +} + +func (j *GroupIamUser) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGroupIamUser{Id: j.Id, RootUid: j.RootUid, Iuid: j.Iuid, Alias: j.Alias, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, LastLoginTime: j.LastLoginTime, Enabled: j.Enabled}) +} +func (j *GroupIamUser) UnmarshalJSON(data []byte) error { + var nj jsonGroupIamUser + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Iuid = nj.Iuid + j.Alias = nj.Alias + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.LastLoginTime = nj.LastLoginTime + j.Enabled = nj.Enabled + return nil +} +func (j *GroupIamUser) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Iuid == 0 { + return errors.MissingRequiredFieldError{Name: "Iuid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if j.LastLoginTime == "" { + return errors.MissingRequiredFieldError{Name: "LastLoginTime"} + } + return nil +} + +// 返回的用户分组下的 IAM 子账号列表 +type GetGroupIamUsers = []GroupIamUser + +// 用户分组下的 IAM 子账号信息 +type Data struct { + Count int64 // 用户分组下的 IAM 子账号数量 + List GetGroupIamUsers // 用户分组下的 IAM 子账号列表 +} + +// 返回的用户分组下的 IAM 子账号列表信息 +type GetGroupIamUsersData = Data +type jsonData struct { + Count int64 `json:"count"` // 用户分组下的 IAM 子账号数量 + List GetGroupIamUsers `json:"list"` // 用户分组下的 IAM 子账号列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的用户分组下的 IAM 子账号列表响应 +type GetGroupIamUsersResp = Response +type jsonResponse struct { + Data GetGroupIamUsersData `json:"data"` // 用户分组下的 IAM 子账号信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_groups/api.go b/iam/apis/get_groups/api.go new file mode 100644 index 00000000..3bb9c91d --- /dev/null +++ b/iam/apis/get_groups/api.go @@ -0,0 +1,157 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 列举用户分组列表 +package get_groups + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetGroupsData // 用户分组信息 +} + +// 返回的用户分组 +type GetGroup struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 用户分组别名 + Description string // 用户分组描述 + Enabled bool // 用户分组是否启用 + CreatedAt string // 用户分组创建时间 + UpdatedAt string // 用户分组上次更新时间 +} +type jsonGetGroup struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 用户分组别名 + Description string `json:"description"` // 用户分组描述 + Enabled bool `json:"enabled"` // 用户分组是否启用 + CreatedAt string `json:"created_at"` // 用户分组创建时间 + UpdatedAt string `json:"updated_at"` // 用户分组上次更新时间 +} + +func (j *GetGroup) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGetGroup{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt}) +} +func (j *GetGroup) UnmarshalJSON(data []byte) error { + var nj jsonGetGroup + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + return nil +} +func (j *GetGroup) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + return nil +} + +// 返回的用户分组列表 +type GetGroups = []GetGroup + +// 用户分组信息 +type Data struct { + Count int64 // 用户分组数量 + List GetGroups // 用户分组列表 +} + +// 返回的用户分组列表信息 +type GetGroupsData = Data +type jsonData struct { + Count int64 `json:"count"` // 用户分组数量 + List GetGroups `json:"list"` // 用户分组列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的用户分组列表响应 +type GetGroupsResp = Response +type jsonResponse struct { + Data GetGroupsData `json:"data"` // 用户分组信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_policies/api.go b/iam/apis/get_policies/api.go new file mode 100644 index 00000000..b7b1a581 --- /dev/null +++ b/iam/apis/get_policies/api.go @@ -0,0 +1,218 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 列举授权策略列表 +package get_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetPoliciesData // 授权策略信息 +} + +// 授权策略规则的操作集合 +type Actions = []string + +// 授权策略规则的资源集合 +type Resources = []string + +// 授权策略规则 +type Statement struct { + Actions Actions // 授权策略规则的操作集合 + Resources Resources // 授权策略规则的资源集合 + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonStatement struct { + Actions Actions `json:"action"` // 授权策略规则的操作集合 + Resources Resources `json:"resource"` // 授权策略规则的资源集合 + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *Statement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *Statement) UnmarshalJSON(data []byte) error { + var nj jsonStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *Statement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type Statements = []Statement + +// 返回的授权策略 +type Policy struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 授权策略别名 + Description string // 授权策略描述 + Enabled bool // 授权策略是否启用 + CreatedAt string // 授权策略创建时间 + UpdatedAt string // 授权策略上次更新时间 + Statement Statements // 授权策略规则集合 +} +type jsonPolicy struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 授权策略别名 + Description string `json:"description"` // 授权策略描述 + Enabled bool `json:"enabled"` // 授权策略是否启用 + CreatedAt string `json:"created_at"` // 授权策略创建时间 + UpdatedAt string `json:"updated_at"` // 授权策略上次更新时间 + Statement Statements `json:"statement"` // 授权策略规则集合 +} + +func (j *Policy) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonPolicy{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, Statement: j.Statement}) +} +func (j *Policy) UnmarshalJSON(data []byte) error { + var nj jsonPolicy + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.Statement = nj.Statement + return nil +} +func (j *Policy) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if len(j.Statement) == 0 { + return errors.MissingRequiredFieldError{Name: "Statement"} + } + for _, value := range j.Statement { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的授权策略列表 +type GetPolicies = []Policy + +// 授权策略信息 +type Data struct { + Count int64 // 授权策略数量 + List GetPolicies // 授权策略列表 +} + +// 返回的授权策略列表信息 +type GetPoliciesData = Data +type jsonData struct { + Count int64 `json:"count"` // 授权策略数量 + List GetPolicies `json:"list"` // 授权策略列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的授权策略列表响应 +type GetPoliciesResp = Response +type jsonResponse struct { + Data GetPoliciesData `json:"data"` // 授权策略信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_policy/api.go b/iam/apis/get_policy/api.go new file mode 100644 index 00000000..cec8c992 --- /dev/null +++ b/iam/apis/get_policy/api.go @@ -0,0 +1,174 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询指定授权策略详情 +package get_policy + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 授权策略别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetPolicyData // 授权策略信息 +} + +// 授权策略规则的操作集合 +type Actions = []string + +// 授权策略规则的资源集合 +type Resources = []string + +// 授权策略规则 +type Statement struct { + Actions Actions // 授权策略规则的操作集合 + Resources Resources // 授权策略规则的资源集合 + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonStatement struct { + Actions Actions `json:"action"` // 授权策略规则的操作集合 + Resources Resources `json:"resource"` // 授权策略规则的资源集合 + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *Statement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *Statement) UnmarshalJSON(data []byte) error { + var nj jsonStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *Statement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type Statements = []Statement + +// 授权策略信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 授权策略别名 + Description string // 授权策略描述 + Enabled bool // 授权策略是否启用 + CreatedAt string // 授权策略创建时间 + UpdatedAt string // 授权策略上次更新时间 + Statement Statements // 授权策略规则集合 +} + +// 返回的授权策略信息 +type GetPolicyData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 授权策略别名 + Description string `json:"description"` // 授权策略描述 + Enabled bool `json:"enabled"` // 授权策略是否启用 + CreatedAt string `json:"created_at"` // 授权策略创建时间 + UpdatedAt string `json:"updated_at"` // 授权策略上次更新时间 + Statement Statements `json:"statement"` // 授权策略规则集合 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, Statement: j.Statement}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.Statement = nj.Statement + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if len(j.Statement) == 0 { + return errors.MissingRequiredFieldError{Name: "Statement"} + } + for _, value := range j.Statement { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的授权策略响应 +type GetPolicyResp = Response +type jsonResponse struct { + Data GetPolicyData `json:"data"` // 授权策略信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_policy_groups/api.go b/iam/apis/get_policy_groups/api.go new file mode 100644 index 00000000..bce8f47c --- /dev/null +++ b/iam/apis/get_policy_groups/api.go @@ -0,0 +1,158 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询授权策略分配的用户分组列表 +package get_policy_groups + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 授权策略别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetPolicyGroupsData // 授权策略分配的用户分组信息 +} + +// 返回的授权策略分配的用户分组 +type GetPolicyGroup struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 用户分组别名 + Description string // 用户分组描述 + Enabled bool // 用户分组是否启用 + CreatedAt string // 用户分组创建时间 + UpdatedAt string // 用户分组上次更新时间 +} +type jsonGetPolicyGroup struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 用户分组别名 + Description string `json:"description"` // 用户分组描述 + Enabled bool `json:"enabled"` // 用户分组是否启用 + CreatedAt string `json:"created_at"` // 用户分组创建时间 + UpdatedAt string `json:"updated_at"` // 用户分组上次更新时间 +} + +func (j *GetPolicyGroup) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGetPolicyGroup{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt}) +} +func (j *GetPolicyGroup) UnmarshalJSON(data []byte) error { + var nj jsonGetPolicyGroup + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + return nil +} +func (j *GetPolicyGroup) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + return nil +} + +// 返回的授权策略分配的用户分组列表 +type GetPolicyGroups = []GetPolicyGroup + +// 授权策略分配的用户分组信息 +type Data struct { + Count int64 // 授权策略分配的用户分组数量 + List GetPolicyGroups // 授权策略分配的用户分组列表 +} + +// 返回的授权策略分配的用户分组列表信息 +type GetPolicyGroupsData = Data +type jsonData struct { + Count int64 `json:"count"` // 授权策略分配的用户分组数量 + List GetPolicyGroups `json:"list"` // 授权策略分配的用户分组列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的授权策略分配的用户分组列表响应 +type GetPolicyGroupsResp = Response +type jsonResponse struct { + Data GetPolicyGroupsData `json:"data"` // 授权策略分配的用户分组信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_policy_users/api.go b/iam/apis/get_policy_users/api.go new file mode 100644 index 00000000..4df817c9 --- /dev/null +++ b/iam/apis/get_policy_users/api.go @@ -0,0 +1,164 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询授权策略分配的用 IAM 子账号列表 +package get_policy_users + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 授权策略别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetPolicyIamUsersData // 授权策略分配的 IAM 子账号信息 +} + +// 返回的授权策略分配的 IAM 子账号 +type PolicyIamUser struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Iuid int64 // 子账号 uid + Alias string // 子账号别名 + CreatedAt string // 子账号创建时间 + UpdatedAt string // 子账号上次更新时间 + LastLoginTime string // 子账号上次更新时间 + Enabled bool // 子账号是否启用 +} +type jsonPolicyIamUser struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Iuid int64 `json:"iuid"` // 子账号 uid + Alias string `json:"alias"` // 子账号别名 + CreatedAt string `json:"created_at"` // 子账号创建时间 + UpdatedAt string `json:"updated_at"` // 子账号上次更新时间 + LastLoginTime string `json:"last_login_time"` // 子账号上次更新时间 + Enabled bool `json:"enabled"` // 子账号是否启用 +} + +func (j *PolicyIamUser) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonPolicyIamUser{Id: j.Id, RootUid: j.RootUid, Iuid: j.Iuid, Alias: j.Alias, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, LastLoginTime: j.LastLoginTime, Enabled: j.Enabled}) +} +func (j *PolicyIamUser) UnmarshalJSON(data []byte) error { + var nj jsonPolicyIamUser + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Iuid = nj.Iuid + j.Alias = nj.Alias + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.LastLoginTime = nj.LastLoginTime + j.Enabled = nj.Enabled + return nil +} +func (j *PolicyIamUser) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Iuid == 0 { + return errors.MissingRequiredFieldError{Name: "Iuid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if j.LastLoginTime == "" { + return errors.MissingRequiredFieldError{Name: "LastLoginTime"} + } + return nil +} + +// 返回的授权策略分配的 IAM 子账号列表 +type GetPolicyIamUsers = []PolicyIamUser + +// 授权策略分配的 IAM 子账号信息 +type Data struct { + Count int64 // 授权策略分配的 IAM 子账号数量 + List GetPolicyIamUsers // 授权策略分配的 IAM 子账号列表 +} + +// 返回的授权策略分配的 IAM 子账号列表信息 +type GetPolicyIamUsersData = Data +type jsonData struct { + Count int64 `json:"count"` // 授权策略分配的 IAM 子账号数量 + List GetPolicyIamUsers `json:"list"` // 授权策略分配的 IAM 子账号列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的授权策略分配的 IAM 子账号列表响应 +type GetPolicyIamUsersResp = Response +type jsonResponse struct { + Data GetPolicyIamUsersData `json:"data"` // 授权策略分配的 IAM 子账号信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_services/api.go b/iam/apis/get_services/api.go new file mode 100644 index 00000000..feafa363 --- /dev/null +++ b/iam/apis/get_services/api.go @@ -0,0 +1,52 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询 IAM 的服务列表 +package get_services + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data Services // 服务列表信息 +} + +// 服务列表 +type Services = []string + +// 返回的服务列表响应 +type GetServicesResp = Response +type jsonResponse struct { + Data Services `json:"data"` // 服务列表信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if len(j.Data) == 0 { + return errors.MissingRequiredFieldError{Name: "Data"} + } + return nil +} diff --git a/iam/apis/get_user/api.go b/iam/apis/get_user/api.go new file mode 100644 index 00000000..3a81fc86 --- /dev/null +++ b/iam/apis/get_user/api.go @@ -0,0 +1,119 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 获取 IAM 子账号 +package get_user + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetIamUserData // IAM 子账号信息 +} + +// IAM 子账号信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Iuid int64 // 子账号 uid + Alias string // 子账号别名 + CreatedAt string // 子账号创建时间 + UpdatedAt string // 子账号上次更新时间 + LastLoginTime string // 子账号上次更新时间 + Enabled bool // 子账号是否启用 +} + +// 返回的 IAM 子账号信息 +type GetIamUserData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Iuid int64 `json:"iuid"` // 子账号 uid + Alias string `json:"alias"` // 子账号别名 + CreatedAt string `json:"created_at"` // 子账号创建时间 + UpdatedAt string `json:"updated_at"` // 子账号上次更新时间 + LastLoginTime string `json:"last_login_time"` // 子账号上次更新时间 + Enabled bool `json:"enabled"` // 子账号是否启用 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Iuid: j.Iuid, Alias: j.Alias, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, LastLoginTime: j.LastLoginTime, Enabled: j.Enabled}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Iuid = nj.Iuid + j.Alias = nj.Alias + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.LastLoginTime = nj.LastLoginTime + j.Enabled = nj.Enabled + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Iuid == 0 { + return errors.MissingRequiredFieldError{Name: "Iuid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if j.LastLoginTime == "" { + return errors.MissingRequiredFieldError{Name: "LastLoginTime"} + } + return nil +} + +// 返回的 IAM 子账号响应 +type GetIamUserResp = Response +type jsonResponse struct { + Data GetIamUserData `json:"data"` // IAM 子账号信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_user_available_services/api.go b/iam/apis/get_user_available_services/api.go new file mode 100644 index 00000000..38762f89 --- /dev/null +++ b/iam/apis/get_user_available_services/api.go @@ -0,0 +1,51 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 列举子账号可用服务 +package get_user_available_services + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data Services // IAM 子账号可用服务信息 +} + +// 可用服务列表 +type Services = []string + +// 返回的 IAM 子账号可用服务列表响应 +type GetIamUserAvailableServicesResp = Response +type jsonResponse struct { + Data Services `json:"data"` // IAM 子账号可用服务信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if len(j.Data) == 0 { + return errors.MissingRequiredFieldError{Name: "Data"} + } + return nil +} diff --git a/iam/apis/get_user_groups/api.go b/iam/apis/get_user_groups/api.go new file mode 100644 index 00000000..589dc10c --- /dev/null +++ b/iam/apis/get_user_groups/api.go @@ -0,0 +1,158 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询子账号所属用户分组列表 +package get_user_groups + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetIamUserGroupsData // IAM 子账号分组信息 +} + +// 返回的 IAM 子账号分组 +type IamUserGroup struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 用户分组别名 + Description string // 用户分组描述 + Enabled bool // 用户分组是否启用 + CreatedAt string // 用户分组创建时间 + UpdatedAt string // 用户分组上次更新时间 +} +type jsonIamUserGroup struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 用户分组别名 + Description string `json:"description"` // 用户分组描述 + Enabled bool `json:"enabled"` // 用户分组是否启用 + CreatedAt string `json:"created_at"` // 用户分组创建时间 + UpdatedAt string `json:"updated_at"` // 用户分组上次更新时间 +} + +func (j *IamUserGroup) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonIamUserGroup{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt}) +} +func (j *IamUserGroup) UnmarshalJSON(data []byte) error { + var nj jsonIamUserGroup + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + return nil +} +func (j *IamUserGroup) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + return nil +} + +// 返回的 IAM 子账号分组列表 +type GetIamUserGroups = []IamUserGroup + +// IAM 子账号分组信息 +type Data struct { + Count int64 // IAM 子账号分组数量 + List GetIamUserGroups // IAM 子账号分组列表 +} + +// 返回的 IAM 子账号分组列表信息 +type GetIamUserGroupsData = Data +type jsonData struct { + Count int64 `json:"count"` // IAM 子账号分组数量 + List GetIamUserGroups `json:"list"` // IAM 子账号分组列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的 IAM 子账号分组列表响应 +type GetIamUserGroupsResp = Response +type jsonResponse struct { + Data GetIamUserGroupsData `json:"data"` // IAM 子账号分组信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_user_keypairs/api.go b/iam/apis/get_user_keypairs/api.go new file mode 100644 index 00000000..85532ec0 --- /dev/null +++ b/iam/apis/get_user_keypairs/api.go @@ -0,0 +1,152 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 列举 IAM 子账号密钥 +package get_user_keypairs + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetIamUserKeyPairsData // IAM 子账号密钥信息 +} + +// 返回的 IAM 子账号密钥 +type GetIamUserKeyPair struct { + Id string // 记录 ID + AccessKey string // IAM 子账号 Access Key + SecretKey string // IAM 子账号 Secret Key + UserId string // 关联用户的记录 ID + CreatedAt string // 密钥创建时间 + Enabled bool // 密钥是否启用 +} +type jsonGetIamUserKeyPair struct { + Id string `json:"id"` // 记录 ID + AccessKey string `json:"access_key"` // IAM 子账号 Access Key + SecretKey string `json:"secret_key"` // IAM 子账号 Secret Key + UserId string `json:"user_id"` // 关联用户的记录 ID + CreatedAt string `json:"created_at"` // 密钥创建时间 + Enabled bool `json:"enabled"` // 密钥是否启用 +} + +func (j *GetIamUserKeyPair) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGetIamUserKeyPair{Id: j.Id, AccessKey: j.AccessKey, SecretKey: j.SecretKey, UserId: j.UserId, CreatedAt: j.CreatedAt, Enabled: j.Enabled}) +} +func (j *GetIamUserKeyPair) UnmarshalJSON(data []byte) error { + var nj jsonGetIamUserKeyPair + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.AccessKey = nj.AccessKey + j.SecretKey = nj.SecretKey + j.UserId = nj.UserId + j.CreatedAt = nj.CreatedAt + j.Enabled = nj.Enabled + return nil +} +func (j *GetIamUserKeyPair) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.AccessKey == "" { + return errors.MissingRequiredFieldError{Name: "AccessKey"} + } + if j.SecretKey == "" { + return errors.MissingRequiredFieldError{Name: "SecretKey"} + } + if j.UserId == "" { + return errors.MissingRequiredFieldError{Name: "UserId"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + return nil +} + +// 返回的 IAM 子账号密钥列表 +type GetIamUserKeyPairs = []GetIamUserKeyPair + +// IAM 子账号密钥信息 +type Data struct { + Count int64 // IAM 子账号密钥数量 + List GetIamUserKeyPairs // IAM 子账号密钥列表 +} + +// 返回的 IAM 子账号密钥列表信息 +type GetIamUserKeyPairsData = Data +type jsonData struct { + Count int64 `json:"count"` // IAM 子账号密钥数量 + List GetIamUserKeyPairs `json:"list"` // IAM 子账号密钥列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的 IAM 子账号密钥列表响应 +type GetIamUserKeyPairsResp = Response +type jsonResponse struct { + Data GetIamUserKeyPairsData `json:"data"` // IAM 子账号密钥信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_user_policies/api.go b/iam/apis/get_user_policies/api.go new file mode 100644 index 00000000..93c94430 --- /dev/null +++ b/iam/apis/get_user_policies/api.go @@ -0,0 +1,219 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询子账号下的授权策略 +package get_user_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetIamUserPoliciesData // IAM 子账号的授权策略信息 +} + +// 授权策略规则的操作集合 +type Actions = []string + +// 授权策略规则的资源集合 +type Resources = []string + +// 授权策略规则 +type Statement struct { + Actions Actions // 授权策略规则的操作集合 + Resources Resources // 授权策略规则的资源集合 + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonStatement struct { + Actions Actions `json:"action"` // 授权策略规则的操作集合 + Resources Resources `json:"resource"` // 授权策略规则的资源集合 + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *Statement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *Statement) UnmarshalJSON(data []byte) error { + var nj jsonStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *Statement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type Statements = []Statement + +// 返回的 IAM 子账号的授权策略 +type GetIamUserPolicy struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 授权策略别名 + Description string // 授权策略描述 + Enabled bool // 授权策略是否启用 + CreatedAt string // 授权策略创建时间 + UpdatedAt string // 授权策略上次更新时间 + Statement Statements // 授权策略规则集合 +} +type jsonGetIamUserPolicy struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 授权策略别名 + Description string `json:"description"` // 授权策略描述 + Enabled bool `json:"enabled"` // 授权策略是否启用 + CreatedAt string `json:"created_at"` // 授权策略创建时间 + UpdatedAt string `json:"updated_at"` // 授权策略上次更新时间 + Statement Statements `json:"statement"` // 授权策略规则集合 +} + +func (j *GetIamUserPolicy) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGetIamUserPolicy{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, Statement: j.Statement}) +} +func (j *GetIamUserPolicy) UnmarshalJSON(data []byte) error { + var nj jsonGetIamUserPolicy + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.Statement = nj.Statement + return nil +} +func (j *GetIamUserPolicy) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if len(j.Statement) == 0 { + return errors.MissingRequiredFieldError{Name: "Statement"} + } + for _, value := range j.Statement { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的 IAM 子账号的授权策略列表 +type GetIamUserPolicies = []GetIamUserPolicy + +// IAM 子账号的授权策略信息 +type Data struct { + Count int64 // IAM 子账号的授权策略数量 + List GetIamUserPolicies // IAM 子账号的授权策略列表 +} + +// 返回的 IAM 子账号的授权策略列表信息 +type GetIamUserPoliciesData = Data +type jsonData struct { + Count int64 `json:"count"` // IAM 子账号的授权策略数量 + List GetIamUserPolicies `json:"list"` // IAM 子账号的授权策略列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的 IAM 子账号的授权策略列表响应 +type GetIamUserPoliciesResp = Response +type jsonResponse struct { + Data GetIamUserPoliciesData `json:"data"` // IAM 子账号的授权策略信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_user_service_action_resources/api.go b/iam/apis/get_user_service_action_resources/api.go new file mode 100644 index 00000000..f5b98b9d --- /dev/null +++ b/iam/apis/get_user_service_action_resources/api.go @@ -0,0 +1,94 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 列举子账号指定服务操作下的可访问资源 +package get_user_service_action_resources + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + UserAlias string // 子账号别名 + Service string // 资源操作关联的服务 + ActionAlias string // 资源操作别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetIamUserServiceActionResources // IAM 子账号指定服务操作下的可访问资源列表信息 +} + +// 可用资源列表 +type AllowedResources = []string + +// 禁用资源列表 +type DeniedResources = []string + +// IAM 子账号指定服务操作下的可访问资源列表信息 +type Data struct { + AllowedResources AllowedResources // 可用资源 + DeniedResources DeniedResources // 禁用资源 +} + +// 返回的 IAM 子账号指定服务操作下的可访问资源列表信息 +type GetIamUserServiceActionResources = Data +type jsonData struct { + AllowedResources AllowedResources `json:"allow"` // 可用资源 + DeniedResources DeniedResources `json:"deny"` // 禁用资源 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{AllowedResources: j.AllowedResources, DeniedResources: j.DeniedResources}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.AllowedResources = nj.AllowedResources + j.DeniedResources = nj.DeniedResources + return nil +} +func (j *Data) validate() error { + if len(j.AllowedResources) == 0 { + return errors.MissingRequiredFieldError{Name: "AllowedResources"} + } + if len(j.DeniedResources) == 0 { + return errors.MissingRequiredFieldError{Name: "DeniedResources"} + } + return nil +} + +// 返回的 IAM 子账号指定服务操作下的可访问资源列表响应 +type GetIamUserServiceActionResourcesResp = Response +type jsonResponse struct { + Data GetIamUserServiceActionResources `json:"data"` // IAM 子账号指定服务操作下的可访问资源列表信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/get_users/api.go b/iam/apis/get_users/api.go new file mode 100644 index 00000000..520a55f9 --- /dev/null +++ b/iam/apis/get_users/api.go @@ -0,0 +1,164 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 列举 IAM 子账号 +package get_users + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Page int64 // 分页页号,从 1 开始,默认 1 + PageSize int64 // 分页大小,默认 20,最大 2000 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + Data GetIamUsersData // IAM 子账号信息 +} + +// 返回的 IAM 子账号 +type GetIamUser struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Iuid int64 // 子账号 uid + Alias string // 子账号别名 + CreatedAt string // 子账号创建时间 + UpdatedAt string // 子账号上次更新时间 + LastLoginTime string // 子账号上次更新时间 + Enabled bool // 子账号是否启用 +} +type jsonGetIamUser struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Iuid int64 `json:"iuid"` // 子账号 uid + Alias string `json:"alias"` // 子账号别名 + CreatedAt string `json:"created_at"` // 子账号创建时间 + UpdatedAt string `json:"updated_at"` // 子账号上次更新时间 + LastLoginTime string `json:"last_login_time"` // 子账号上次更新时间 + Enabled bool `json:"enabled"` // 子账号是否启用 +} + +func (j *GetIamUser) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonGetIamUser{Id: j.Id, RootUid: j.RootUid, Iuid: j.Iuid, Alias: j.Alias, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, LastLoginTime: j.LastLoginTime, Enabled: j.Enabled}) +} +func (j *GetIamUser) UnmarshalJSON(data []byte) error { + var nj jsonGetIamUser + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Iuid = nj.Iuid + j.Alias = nj.Alias + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.LastLoginTime = nj.LastLoginTime + j.Enabled = nj.Enabled + return nil +} +func (j *GetIamUser) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Iuid == 0 { + return errors.MissingRequiredFieldError{Name: "Iuid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if j.LastLoginTime == "" { + return errors.MissingRequiredFieldError{Name: "LastLoginTime"} + } + return nil +} + +// 返回的 IAM 子账号列表 +type GetIamUsers = []GetIamUser + +// IAM 子账号信息 +type Data struct { + Count int64 // IAM 子账号数量 + List GetIamUsers // IAM 子账号列表 +} + +// 返回的 IAM 子账号列表信息 +type GetIamUsersData = Data +type jsonData struct { + Count int64 `json:"count"` // IAM 子账号数量 + List GetIamUsers `json:"list"` // IAM 子账号列表 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Count: j.Count, List: j.List}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Count = nj.Count + j.List = nj.List + return nil +} +func (j *Data) validate() error { + if j.Count == 0 { + return errors.MissingRequiredFieldError{Name: "Count"} + } + if len(j.List) == 0 { + return errors.MissingRequiredFieldError{Name: "List"} + } + for _, value := range j.List { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的 IAM 子账号列表响应 +type GetIamUsersResp = Response +type jsonResponse struct { + Data GetIamUsersData `json:"data"` // IAM 子账号信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/modify_group/api.go b/iam/apis/modify_group/api.go new file mode 100644 index 00000000..6c394101 --- /dev/null +++ b/iam/apis/modify_group/api.go @@ -0,0 +1,46 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 更新用户分组信息 +package modify_group + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + NewAlias string // 新的用户分组别名,由 `A-Za-z0-9` 组成 + Description string // 用户分组描述 +} + +// 修改用户分组参数 +type ModifyGroupParam = Request +type jsonRequest struct { + NewAlias string `json:"alias,omitempty"` // 新的用户分组别名,由 `A-Za-z0-9` 组成 + Description string `json:"description,omitempty"` // 用户分组描述 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{NewAlias: j.NewAlias, Description: j.Description}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.NewAlias = nj.NewAlias + j.Description = nj.Description + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/modify_group_policies/api.go b/iam/apis/modify_group_policies/api.go new file mode 100644 index 00000000..f9651736 --- /dev/null +++ b/iam/apis/modify_group_policies/api.go @@ -0,0 +1,50 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 添加授权策略到用户分组 +package modify_group_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + PolicyAliases PolicyAliases // 授权策略别名集合 +} + +// 添加给用户分组的授权策略别名集合 +type PolicyAliases = []string + +// 为用户分组修改授权策略参数 +type ModifiedGroupIamPoliciesParam = Request +type jsonRequest struct { + PolicyAliases PolicyAliases `json:"policy_aliases"` // 授权策略别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{PolicyAliases: j.PolicyAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PolicyAliases = nj.PolicyAliases + return nil +} +func (j *Request) validate() error { + if len(j.PolicyAliases) == 0 { + return errors.MissingRequiredFieldError{Name: "PolicyAliases"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/modify_group_users/api.go b/iam/apis/modify_group_users/api.go new file mode 100644 index 00000000..6ba06ff7 --- /dev/null +++ b/iam/apis/modify_group_users/api.go @@ -0,0 +1,50 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 添加 IAM 子账号到用户分组 +package modify_group_users + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + UserAliases UserAliases // IAM 子账号别名集合 +} + +// 添加给用户分组的 IAM 子账号别名集合 +type UserAliases = []string + +// 为用户分组修改 IAM 子账号参数 +type ModifiedGroupIamUsersParam = Request +type jsonRequest struct { + UserAliases UserAliases `json:"user_aliases"` // IAM 子账号别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{UserAliases: j.UserAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.UserAliases = nj.UserAliases + return nil +} +func (j *Request) validate() error { + if len(j.UserAliases) == 0 { + return errors.MissingRequiredFieldError{Name: "UserAliases"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/modify_policy/api.go b/iam/apis/modify_policy/api.go new file mode 100644 index 00000000..dc263f9d --- /dev/null +++ b/iam/apis/modify_policy/api.go @@ -0,0 +1,255 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 修改授权策略 +package modify_policy + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 授权策略别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + NewAlias string // 授权策略别名,由 `A-Za-z0-9` 组成 + Description string // 授权策略描述 + Statement ModifyStatements // 授权策略规则集合 +} + +// 授权策略规则的操作集合 +type ModifyActions = []string + +// 授权策略规则的资源集合 +type ModifyResources = []string + +// 授权策略规则 +type ModifyStatement struct { + Actions ModifyActions // 授权策略规则的操作集合,action 查询参考 action 接口,格式为 service/action_alias + Resources ModifyResources // 授权策略规则的资源集合,格式为 qrn:product:region:uid:[resource-type/]resource-id ;可以简写为 qrn:product:::resource-id + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonModifyStatement struct { + Actions ModifyActions `json:"action"` // 授权策略规则的操作集合,action 查询参考 action 接口,格式为 service/action_alias + Resources ModifyResources `json:"resource"` // 授权策略规则的资源集合,格式为 qrn:product:region:uid:[resource-type/]resource-id ;可以简写为 qrn:product:::resource-id + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *ModifyStatement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonModifyStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *ModifyStatement) UnmarshalJSON(data []byte) error { + var nj jsonModifyStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *ModifyStatement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type ModifyStatements = []ModifyStatement + +// 修改授权策略参数 +type ModifyPolicyParam = Request +type jsonRequest struct { + NewAlias string `json:"alias,omitempty"` // 授权策略别名,由 `A-Za-z0-9` 组成 + Description string `json:"description,omitempty"` // 授权策略描述 + Statement ModifyStatements `json:"statement,omitempty"` // 授权策略规则集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{NewAlias: j.NewAlias, Description: j.Description, Statement: j.Statement}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.NewAlias = nj.NewAlias + j.Description = nj.Description + j.Statement = nj.Statement + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct { + Data ModifiedPolicyData // 授权策略信息 +} + +// 授权策略规则的操作集合 +type ModifiedActions = []string + +// 授权策略规则的资源集合 +type ModifiedResources = []string + +// 授权策略规则 +type ModifiedStatement struct { + Actions ModifiedActions // 授权策略规则的操作集合 + Resources ModifiedResources // 授权策略规则的资源集合 + Effect string // 授权策略规则的生效类型,允许访问或拒绝访问 +} +type jsonModifiedStatement struct { + Actions ModifiedActions `json:"action"` // 授权策略规则的操作集合 + Resources ModifiedResources `json:"resource"` // 授权策略规则的资源集合 + Effect string `json:"effect"` // 授权策略规则的生效类型,允许访问或拒绝访问 +} + +func (j *ModifiedStatement) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonModifiedStatement{Actions: j.Actions, Resources: j.Resources, Effect: j.Effect}) +} +func (j *ModifiedStatement) UnmarshalJSON(data []byte) error { + var nj jsonModifiedStatement + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Actions = nj.Actions + j.Resources = nj.Resources + j.Effect = nj.Effect + return nil +} +func (j *ModifiedStatement) validate() error { + if len(j.Actions) == 0 { + return errors.MissingRequiredFieldError{Name: "Actions"} + } + if len(j.Resources) == 0 { + return errors.MissingRequiredFieldError{Name: "Resources"} + } + if j.Effect == "" { + return errors.MissingRequiredFieldError{Name: "Effect"} + } + return nil +} + +// 授权策略规则集合 +type ModifiedStatements = []ModifiedStatement + +// 授权策略信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Alias string // 授权策略别名 + Description string // 授权策略描述 + Enabled bool // 授权策略是否启用 + CreatedAt string // 授权策略创建时间 + UpdatedAt string // 授权策略上次更新时间 + Statement ModifiedStatements // 授权策略规则集合 +} + +// 返回的授权策略信息 +type ModifiedPolicyData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Alias string `json:"alias"` // 授权策略别名 + Description string `json:"description"` // 授权策略描述 + Enabled bool `json:"enabled"` // 授权策略是否启用 + CreatedAt string `json:"created_at"` // 授权策略创建时间 + UpdatedAt string `json:"updated_at"` // 授权策略上次更新时间 + Statement ModifiedStatements `json:"statement"` // 授权策略规则集合 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Alias: j.Alias, Description: j.Description, Enabled: j.Enabled, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, Statement: j.Statement}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Alias = nj.Alias + j.Description = nj.Description + j.Enabled = nj.Enabled + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.Statement = nj.Statement + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if len(j.Statement) == 0 { + return errors.MissingRequiredFieldError{Name: "Statement"} + } + for _, value := range j.Statement { + if err := value.validate(); err != nil { + return err + } + } + return nil +} + +// 返回的授权策略响应 +type ModifiedPolicyResp = Response +type jsonResponse struct { + Data ModifiedPolicyData `json:"data"` // 授权策略信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/modify_user/api.go b/iam/apis/modify_user/api.go new file mode 100644 index 00000000..1a2e4a89 --- /dev/null +++ b/iam/apis/modify_user/api.go @@ -0,0 +1,147 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 修改 IAM 子账号 +package modify_user + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + Enabled bool // 子账号是否启用 + Password string // 子账号密码 +} + +// 修改 IAM 子账号参数 +type ModifiedIamUserParam = Request +type jsonRequest struct { + Enabled bool `json:"enabled"` // 子账号是否启用 + Password string `json:"password,omitempty"` // 子账号密码 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{Enabled: j.Enabled, Password: j.Password}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Enabled = nj.Enabled + j.Password = nj.Password + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct { + Data ModifiedIamUserData // IAM 子账号信息 +} + +// IAM 子账号信息 +type Data struct { + Id string // 记录 ID + RootUid int64 // 根用户 uid + Iuid int64 // 子账号 uid + Alias string // 子账号别名 + CreatedAt string // 子账号创建时间 + UpdatedAt string // 子账号上次更新时间 + LastLoginTime string // 子账号上次更新时间 + Enabled bool // 子账号是否启用 +} + +// 返回的 IAM 子账号信息 +type ModifiedIamUserData = Data +type jsonData struct { + Id string `json:"id"` // 记录 ID + RootUid int64 `json:"root_uid"` // 根用户 uid + Iuid int64 `json:"iuid"` // 子账号 uid + Alias string `json:"alias"` // 子账号别名 + CreatedAt string `json:"created_at"` // 子账号创建时间 + UpdatedAt string `json:"updated_at"` // 子账号上次更新时间 + LastLoginTime string `json:"last_login_time"` // 子账号上次更新时间 + Enabled bool `json:"enabled"` // 子账号是否启用 +} + +func (j *Data) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonData{Id: j.Id, RootUid: j.RootUid, Iuid: j.Iuid, Alias: j.Alias, CreatedAt: j.CreatedAt, UpdatedAt: j.UpdatedAt, LastLoginTime: j.LastLoginTime, Enabled: j.Enabled}) +} +func (j *Data) UnmarshalJSON(data []byte) error { + var nj jsonData + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.RootUid = nj.RootUid + j.Iuid = nj.Iuid + j.Alias = nj.Alias + j.CreatedAt = nj.CreatedAt + j.UpdatedAt = nj.UpdatedAt + j.LastLoginTime = nj.LastLoginTime + j.Enabled = nj.Enabled + return nil +} +func (j *Data) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.RootUid == 0 { + return errors.MissingRequiredFieldError{Name: "RootUid"} + } + if j.Iuid == 0 { + return errors.MissingRequiredFieldError{Name: "Iuid"} + } + if j.Alias == "" { + return errors.MissingRequiredFieldError{Name: "Alias"} + } + if j.CreatedAt == "" { + return errors.MissingRequiredFieldError{Name: "CreatedAt"} + } + if j.UpdatedAt == "" { + return errors.MissingRequiredFieldError{Name: "UpdatedAt"} + } + if j.LastLoginTime == "" { + return errors.MissingRequiredFieldError{Name: "LastLoginTime"} + } + return nil +} + +// 返回的 IAM 子账号响应 +type ModifiedIamUserResp = Response +type jsonResponse struct { + Data ModifiedIamUserData `json:"data"` // IAM 子账号信息 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Data: j.Data}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Data = nj.Data + return nil +} +func (j *Response) validate() error { + if err := j.Data.validate(); err != nil { + return err + } + return nil +} diff --git a/iam/apis/modify_user_policies/api.go b/iam/apis/modify_user_policies/api.go new file mode 100644 index 00000000..47dfba9a --- /dev/null +++ b/iam/apis/modify_user_policies/api.go @@ -0,0 +1,50 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 为子账号添加授权策略 +package modify_user_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + PolicyAliases PolicyAliases // 授权策略别名集合 +} + +// 添加给用户的授权策略别名集合 +type PolicyAliases = []string + +// 为子账号修改授权策略参数 +type ModifiedIamUserPoliciesParam = Request +type jsonRequest struct { + PolicyAliases PolicyAliases `json:"policy_aliases"` // 授权策略别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{PolicyAliases: j.PolicyAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PolicyAliases = nj.PolicyAliases + return nil +} +func (j *Request) validate() error { + if len(j.PolicyAliases) == 0 { + return errors.MissingRequiredFieldError{Name: "PolicyAliases"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/update_group_policies/api.go b/iam/apis/update_group_policies/api.go new file mode 100644 index 00000000..944aa1c1 --- /dev/null +++ b/iam/apis/update_group_policies/api.go @@ -0,0 +1,46 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 为用户分组重新分配授权策略 +package update_group_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + PolicyAliases PolicyAliases // 授权策略别名集合 +} + +// 为用户分组重新分配的授权策略别名集合 +type PolicyAliases = []string + +// 为用户分组重新分配授权策略参数 +type UpdatedGroupIamPoliciesParam = Request +type jsonRequest struct { + PolicyAliases PolicyAliases `json:"policy_aliases,omitempty"` // 授权策略别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{PolicyAliases: j.PolicyAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PolicyAliases = nj.PolicyAliases + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/update_group_users/api.go b/iam/apis/update_group_users/api.go new file mode 100644 index 00000000..b085316f --- /dev/null +++ b/iam/apis/update_group_users/api.go @@ -0,0 +1,46 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 为用户分组中重新分配 IAM 子账号 +package update_group_users + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 用户分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + UserAliases UserAliases // IAM 子账号别名集合 +} + +// 为用户分组重新分配 IAM 子账号别名集合 +type UserAliases = []string + +// 为用户分组重新分配 IAM 子账号参数 +type UpdatedGroupIamUsersParam = Request +type jsonRequest struct { + UserAliases UserAliases `json:"user_aliases,omitempty"` // IAM 子账号别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{UserAliases: j.UserAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.UserAliases = nj.UserAliases + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/update_policy_groups/api.go b/iam/apis/update_policy_groups/api.go new file mode 100644 index 00000000..16346a1f --- /dev/null +++ b/iam/apis/update_policy_groups/api.go @@ -0,0 +1,46 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 重新分配用户分组给指定策略 +package update_policy_groups + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + GroupAliases GroupAliases // 分组别名集合 +} + +// 重新分配给授权策略的分组别名集合 +type GroupAliases = []string + +// 为授权策略重新分配分组参数 +type UpdatedPolicyGroupsParam = Request +type jsonRequest struct { + GroupAliases GroupAliases `json:"group_aliases,omitempty"` // 分组别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{GroupAliases: j.GroupAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.GroupAliases = nj.GroupAliases + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/update_policy_users/api.go b/iam/apis/update_policy_users/api.go new file mode 100644 index 00000000..82fecc41 --- /dev/null +++ b/iam/apis/update_policy_users/api.go @@ -0,0 +1,46 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 重新分配用户给指定授权策略 +package update_policy_users + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 授权策略分组别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + UserAliases UserAliases // IAM 子账号别名集合 +} + +// 为授权策略重新分配 IAM 子账号别名集合 +type UserAliases = []string + +// 为授权策略重新分配 IAM 子账号参数 +type UpdatedPolicyIamUsersParam = Request +type jsonRequest struct { + UserAliases UserAliases `json:"user_aliases,omitempty"` // IAM 子账号别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{UserAliases: j.UserAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.UserAliases = nj.UserAliases + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/update_user_groups/api.go b/iam/apis/update_user_groups/api.go new file mode 100644 index 00000000..1ee81878 --- /dev/null +++ b/iam/apis/update_user_groups/api.go @@ -0,0 +1,46 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 为用户重新分配分组 +package update_user_groups + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + GroupAliases GroupAliases // 分组别名集合 +} + +// 重新分配给用户的分组别名集合 +type GroupAliases = []string + +// 为用户重新分配分组参数 +type UpdatedIamUserGroupsParam = Request +type jsonRequest struct { + GroupAliases GroupAliases `json:"group_aliases,omitempty"` // 分组别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{GroupAliases: j.GroupAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.GroupAliases = nj.GroupAliases + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/apis/update_user_policies/api.go b/iam/apis/update_user_policies/api.go new file mode 100644 index 00000000..fcfae4ca --- /dev/null +++ b/iam/apis/update_user_policies/api.go @@ -0,0 +1,46 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 为子账号重新分配授权策略 +package update_user_policies + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +// 调用 API 所用的请求 +type Request struct { + Alias string // 子账号别名 + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + PolicyAliases PolicyAliases // 授权策略别名集合 +} + +// 重新分配给用户的授权策略别名集合 +type PolicyAliases = []string + +// 为子账号重新分配授权策略参数 +type UpdatedIamUserPoliciesParam = Request +type jsonRequest struct { + PolicyAliases PolicyAliases `json:"policy_aliases,omitempty"` // 授权策略别名集合 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{PolicyAliases: j.PolicyAliases}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PolicyAliases = nj.PolicyAliases + return nil +} +func (j *Request) validate() error { + return nil +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/iam/doc.go b/iam/doc.go new file mode 100644 index 00000000..4ed7757c --- /dev/null +++ b/iam/doc.go @@ -0,0 +1,5 @@ +// iam 包提供了 IAM 子账号管理等功能。 +package iam + +//go:generate go run ../internal/api-generator -- --api-specs=../api-specs/iam --output=apis/ --struct-name=IAM --api-package=github.com/qiniu/go-sdk/v7/iam/apis +//go:generate go build ./apis/... diff --git a/storagev2/internal/api-generator/client.go b/internal/api-generator/client.go similarity index 60% rename from storagev2/internal/api-generator/client.go rename to internal/api-generator/client.go index 4ad33bd3..0e6fcd2e 100644 --- a/storagev2/internal/api-generator/client.go +++ b/internal/api-generator/client.go @@ -59,7 +59,7 @@ func (description *ApiDetailedDescription) generateSubPackages(group *jen.Group, } func (description *ApiDetailedDescription) generatePackage(group *jen.Group, options CodeGeneratorOptions) (err error) { - packageName := PackageNameApis + "/" + options.Name + packageName := flags.ApiPackagePath + "/" + options.Name innerStructName := "inner" + options.camelCaseName() + "Request" reexportedRequestStructName := options.camelCaseName() + "Request" reexportedResponseStructName := options.camelCaseName() + "Response" @@ -77,17 +77,23 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt return } } - if err = description.Request.generateGetAccessKeyFunc(group, innerStructName); err != nil { - return + if isStorageAPIs() && !description.isBucketService() { + if err = description.Request.generateGetAccessKeyFunc(group, innerStructName); err != nil { + return + } } group.Add(jen.Type().Id(reexportedRequestStructName).Op("=").Qual(packageName, "Request")) group.Add(jen.Type().Id(reexportedResponseStructName).Op("=").Qual(packageName, "Response")) if options.Documentation != "" { group.Add(jen.Comment(options.Documentation)) } + + structName := strcase.ToCamel(flags.StructName) + fieldName := strcase.ToLowerCamel(structName) + group.Add( jen.Func(). - Params(jen.Id("storage").Op("*").Id("Storage")). + Params(jen.Id(fieldName).Op("*").Id(structName)). Id(options.camelCaseName()). Params( jen.Id("ctx").Qual("context", "Context"), @@ -123,7 +129,7 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt case AuthorizationQbox, AuthorizationQiniu: group.Add(jen.If( jen.Id("innerRequest").Dot("Credentials").Op("==").Nil().Op("&&"). - Id("storage").Dot("client").Dot("GetCredentials").Call().Op("==").Nil()). + Id(fieldName).Dot("client").Dot("GetCredentials").Call().Op("==").Nil()). BlockFunc(func(group *jen.Group) { group.Add(jen.Return( jen.Nil(), @@ -157,14 +163,35 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt }), ) } - group.Add(jen.Var().Id("pathSegments").Index().String()) + guessPathSegmentsCount := 0 if description.BasePath != "" { - group.Add(jen.Id("pathSegments").Op("=").AppendFunc(func(group *jen.Group) { - group.Add(jen.Id("pathSegments")) - for _, pathSegment := range description.getBasePathSegments() { - group.Add(jen.Lit(pathSegment)) + guessPathSegmentsCount += len(description.getBasePathSegments()) + } + if description.PathSuffix != "" { + guessPathSegmentsCount += len(description.getPathSuffixSegments()) + } + if pp := description.Request.PathParams; pp != nil { + for _, namedPathParam := range pp.Named { + guessPathSegmentsCount += 1 + if namedPathParam.PathSegment != "" { + guessPathSegmentsCount += 1 } - })) + } + } + if guessPathSegmentsCount > 0 { + group.Add(jen.Id("pathSegments").Op(":=").Make(jen.Index().String(), jen.Lit(0), jen.Lit(guessPathSegmentsCount))) + } else { + group.Add(jen.Id("pathSegments").Op(":=").Make(jen.Index().String(), jen.Lit(0))) + } + if description.BasePath != "" { + if basePathSegments := description.getBasePathSegments(); len(basePathSegments) > 0 { + group.Add(jen.Id("pathSegments").Op("=").AppendFunc(func(group *jen.Group) { + group.Add(jen.Id("pathSegments")) + for _, pathSegment := range basePathSegments { + group.Add(jen.Lit(pathSegment)) + } + })) + } } if description.Request.PathParams != nil { group.Add( @@ -186,14 +213,19 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt ) } if description.PathSuffix != "" { - group.Add(jen.Id("pathSegments").Op("=").AppendFunc(func(group *jen.Group) { - group.Add(jen.Id("pathSegments")) - for _, pathSegment := range description.getPathSuffixSegments() { - group.Add(jen.Lit(pathSegment)) - } - })) + if suffixSegments := description.getPathSuffixSegments(); len(suffixSegments) > 0 { + group.Add(jen.Id("pathSegments").Op("=").AppendFunc(func(group *jen.Group) { + group.Add(jen.Id("pathSegments")) + for _, pathSegment := range suffixSegments { + group.Add(jen.Lit(pathSegment)) + } + })) + } } group.Add(jen.Id("path").Op(":=").Lit("/").Op("+").Qual("strings", "Join").Call(jen.Id("pathSegments"), jen.Lit("/"))) + if description.PathSuffix == "/" { + group.Add(jen.Id("path").Op("+=").Lit("/")) + } if description.Command != "" { group.Add(jen.Id("rawQuery").Op(":=").Lit(description.Command + "&")) } else { @@ -271,27 +303,37 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt ) } } - group.Add(jen.Id("bucketName").Op(":=").Id("options").Dot("OverwrittenBucketName")) - if getBucketNameGenerated { - group.Add( - jen.If(jen.Id("bucketName").Op("==").Lit("")).BlockFunc(func(group *jen.Group) { - group.Add(jen.Var().Id("err").Error()) - group.Add( - jen.If( - jen.List(jen.Id("bucketName"), jen.Err()).Op("=").Id("innerRequest").Dot("getBucketName").Call(jen.Id("ctx")), - jen.Err().Op("!=").Nil(), - ).BlockFunc(func(group *jen.Group) { - group.Return(jen.Nil(), jen.Err()) - }), - ) - }), - ) + if isStorageAPIs() { + group.Add(jen.Id("bucketName").Op(":=").Id("options").Dot("OverwrittenBucketName")) + if getBucketNameGenerated { + group.Add( + jen.If(jen.Id("bucketName").Op("==").Lit("")).BlockFunc(func(group *jen.Group) { + group.Add(jen.Var().Id("err").Error()) + group.Add( + jen.If( + jen.List(jen.Id("bucketName"), jen.Err()).Op("=").Id("innerRequest").Dot("getBucketName").Call(jen.Id("ctx")), + jen.Err().Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Return(jen.Nil(), jen.Err()) + }), + ) + }), + ) + } } - - if getObjectNameGenerated { + if isStorageAPIs() && getObjectNameGenerated { group.Add(jen.Id("objectName").Op(":=").Id("innerRequest").Dot("getObjectName").Call()) - } else { - group.Add(jen.Var().Id("objectName").String()) + } + + var ( + bucketNameVar jen.Code = jen.Lit("") + objectNameVar jen.Code = jen.Lit("") + ) + if isStorageAPIs() { + bucketNameVar = jen.Id("bucketName") + if getObjectNameGenerated { + objectNameVar = jen.Id("objectName") + } } var getUpTokenFunc jen.Code @@ -307,7 +349,7 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt group.Add( jen.Id("credentials"). Op("="). - Id("storage"). + Id(fieldName). Dot("client"). Dot("GetCredentials"). Call()) @@ -316,7 +358,7 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt jen.List(jen.Id("putPolicy"), jen.Err()). Op(":="). Qual(PackageNameUpToken, "NewPutPolicy"). - Call(jen.Id("bucketName"), jen.Qual("time", "Now").Call().Dot("Add").Call(jen.Qual("time", "Hour")))) + Call(bucketNameVar, jen.Qual("time", "Now").Call().Dot("Add").Call(jen.Qual("time", "Hour")))) group.Add(jen.If(jen.Err().Op("!=").Nil()).BlockFunc(func(group *jen.Group) { group.Return(jen.List(jen.Lit(""), jen.Err())) })) @@ -337,8 +379,8 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt Op(":="). Qual(PackageNameUplog, "NewRequestUplog").Call( jen.Lit(strcase.ToLowerCamel(options.camelCaseName())), - jen.Id("bucketName"), - jen.Id("objectName"), + bucketNameVar, + objectNameVar, getUpTokenFunc, ), ) @@ -346,7 +388,8 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt group.Return(jen.Nil(), jen.Err()) })) - method, err := description.Method.ToString() + var method string + method, err = description.Method.ToString() if err != nil { return } @@ -413,127 +456,205 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt jen.If( jen.Id("options").Dot("OverwrittenEndpoints").Op("==").Nil().Op("&&"). Id("options").Dot("OverwrittenRegion").Op("==").Nil().Op("&&"). - Id("storage").Dot("client").Dot("GetRegions").Call().Op("==").Nil()). + Id(fieldName).Dot("client").Dot("GetRegions").Call().Op("==").Nil()). BlockFunc(func(group *jen.Group) { - group.Add(jen.Id("query").Op(":=").Id("storage").Dot("client").Dot("GetBucketQuery").Call()) - group.Add( - jen.If(jen.Id("query").Op("==").Nil()).BlockFunc(func(group *jen.Group) { - group.Add(jen.Id("bucketHosts").Op(":=").Qual(PackageNameHTTPClient, "DefaultBucketHosts").Call()) - if description.isBucketService() { - group.Add( - jen.If(jen.Id("options").Dot("OverwrittenBucketHosts").Op("!=").Nil()). - BlockFunc(func(group *jen.Group) { - group.Add(jen.Id("req").Dot("Endpoints").Op("=").Id("options").Dot("OverwrittenBucketHosts")) - }). - Else(). - BlockFunc(func(group *jen.Group) { - group.Add(jen.Id("req").Dot("Endpoints").Op("=").Id("bucketHosts")) + group.Add(jen.Id("bucketHosts").Op(":=").Qual(PackageNameHTTPClient, "DefaultBucketHosts").Call()) + if description.isBucketService() { + group.Add( + jen.If(jen.Id("options").Dot("OverwrittenBucketHosts").Op("!=").Nil()). + BlockFunc(func(group *jen.Group) { + group.Add(jen.Id("req").Dot("Endpoints").Op("=").Id("options").Dot("OverwrittenBucketHosts")) + }). + Else(). + BlockFunc(func(group *jen.Group) { + group.Add(jen.Id("req").Dot("Endpoints").Op("=").Id("bucketHosts")) + }), + ) + } else { + ifBucketIsNotEmptyStmt := jen.If(jen.Id("bucketName").Op("!=").Lit("")).BlockFunc(func(group *jen.Group) { + group.Add(jen.Id("query").Op(":=").Id(fieldName).Dot("client").Dot("GetBucketQuery").Call()) + group.Add( + jen.If(jen.Id("query").Op("==").Nil()).BlockFunc(func(group *jen.Group) { + group.Add( + jen.If(jen.Id("options").Dot("OverwrittenBucketHosts").Op("!=").Nil()).BlockFunc(func(group *jen.Group) { + group.Add( + jen.If( + jen.List(jen.Id("bucketHosts"), jen.Err()). + Op("="). + Id("options"). + Dot("OverwrittenBucketHosts"). + Dot("GetEndpoints"). + Call(jen.Id("ctx")), + jen.Err().Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Add(jen.Return(jen.Nil(), jen.Err())) + }), + ) }), - ) - } else { - group.Add( - jen.If(jen.Id("options").Dot("OverwrittenBucketHosts").Op("!=").Nil()).BlockFunc(func(group *jen.Group) { - group.Add( - jen.If( - jen.List(jen.Id("bucketHosts"), jen.Err()). - Op("="). - Id("options"). - Dot("OverwrittenBucketHosts"). - Dot("GetEndpoints"). - Call(jen.Id("ctx")), - jen.Err().Op("!=").Nil(), - ).BlockFunc(func(group *jen.Group) { - group.Add(jen.Return(jen.Nil(), jen.Err())) + ) + group.Add( + jen.Id("queryOptions"). + Op(":="). + Qual(PackageNameRegion, "BucketRegionsQueryOptions"). + ValuesFunc(func(group *jen.Group) { + group.Add(jen.Id("UseInsecureProtocol").Op(":").Id(fieldName).Dot("client").Dot("UseInsecureProtocol").Call()) + group.Add(jen.Id("AccelerateUploading").Op(":").Id(fieldName).Dot("client").Dot("AccelerateUploadingEnabled").Call()) + group.Add(jen.Id("HostFreezeDuration").Op(":").Id(fieldName).Dot("client").Dot("GetHostFreezeDuration").Call()) + group.Add(jen.Id("Resolver").Op(":").Id(fieldName).Dot("client").Dot("GetResolver").Call()) + group.Add(jen.Id("Chooser").Op(":").Id(fieldName).Dot("client").Dot("GetChooser").Call()) + group.Add(jen.Id("BeforeResolve").Op(":").Id(fieldName).Dot("client").Dot("GetBeforeResolveCallback").Call()) + group.Add(jen.Id("AfterResolve").Op(":").Id(fieldName).Dot("client").Dot("GetAfterResolveCallback").Call()) + group.Add(jen.Id("ResolveError").Op(":").Id(fieldName).Dot("client").Dot("GetResolveErrorCallback").Call()) + group.Add(jen.Id("BeforeBackoff").Op(":").Id(fieldName).Dot("client").Dot("GetBeforeBackoffCallback").Call()) + group.Add(jen.Id("AfterBackoff").Op(":").Id(fieldName).Dot("client").Dot("GetAfterBackoffCallback").Call()) + group.Add(jen.Id("BeforeRequest").Op(":").Id(fieldName).Dot("client").Dot("GetBeforeRequestCallback").Call()) + group.Add(jen.Id("AfterResponse").Op(":").Id(fieldName).Dot("client").Dot("GetAfterResponseCallback").Call()) }), - ) - }), - ) - group.Add( - jen.Id("queryOptions"). - Op(":="). - Qual(PackageNameRegion, "BucketRegionsQueryOptions"). - ValuesFunc(func(group *jen.Group) { - group.Add(jen.Id("UseInsecureProtocol").Op(":").Id("storage").Dot("client").Dot("UseInsecureProtocol").Call()) - group.Add(jen.Id("HostFreezeDuration").Op(":").Id("storage").Dot("client").Dot("GetHostFreezeDuration").Call()) - group.Add(jen.Id("Client").Op(":").Id("storage").Dot("client").Dot("GetClient").Call()) - group.Add(jen.Id("Resolver").Op(":").Id("storage").Dot("client").Dot("GetResolver").Call()) - group.Add(jen.Id("Chooser").Op(":").Id("storage").Dot("client").Dot("GetChooser").Call()) - group.Add(jen.Id("BeforeResolve").Op(":").Id("storage").Dot("client").Dot("GetBeforeResolveCallback").Call()) - group.Add(jen.Id("AfterResolve").Op(":").Id("storage").Dot("client").Dot("GetAfterResolveCallback").Call()) - group.Add(jen.Id("ResolveError").Op(":").Id("storage").Dot("client").Dot("GetResolveErrorCallback").Call()) - group.Add(jen.Id("BeforeBackoff").Op(":").Id("storage").Dot("client").Dot("GetBeforeBackoffCallback").Call()) - group.Add(jen.Id("AfterBackoff").Op(":").Id("storage").Dot("client").Dot("GetAfterBackoffCallback").Call()) - group.Add(jen.Id("BeforeRequest").Op(":").Id("storage").Dot("client").Dot("GetBeforeRequestCallback").Call()) - group.Add(jen.Id("AfterResponse").Op(":").Id("storage").Dot("client").Dot("GetAfterResponseCallback").Call()) + ) + group.Add( + jen.If( + jen.Id("hostRetryConfig").Op(":=").Id(fieldName).Dot("client").Dot("GetHostRetryConfig").Call(), + jen.Id("hostRetryConfig").Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Id("queryOptions").Dot("RetryMax").Op("=").Id("hostRetryConfig").Dot("RetryMax") + group.Id("queryOptions").Dot("Backoff").Op("=").Id("hostRetryConfig").Dot("Backoff") }), - ) - group.Add( - jen.If( - jen.Id("hostRetryConfig").Op(":=").Id("storage").Dot("client").Dot("GetHostRetryConfig").Call(), - jen.Id("hostRetryConfig").Op("!=").Nil(), - ).BlockFunc(func(group *jen.Group) { - group.Id("queryOptions").Dot("RetryMax").Op("=").Id("hostRetryConfig").Dot("RetryMax") - group.Id("queryOptions").Dot("Backoff").Op("=").Id("hostRetryConfig").Dot("Backoff") - }), - ) - group.Add( - jen.If( - jen.List(jen.Id("query"), jen.Err()). - Op("="). - Qual(PackageNameRegion, "NewBucketRegionsQuery"). - Call(jen.Id("bucketHosts"), jen.Op("&").Id("queryOptions")), - jen.Err().Op("!=").Nil(), - ).BlockFunc(func(group *jen.Group) { - group.Add(jen.Return(jen.Nil(), jen.Err())) - }), - ) - } - }), - ) - group.Add( - jen.If(jen.Id("query").Op("!=").Nil()).BlockFunc(func(group *jen.Group) { - group.Add(jen.Var().Id("accessKey").String()) - group.Add(jen.Var().Err().Error()) - group.Add( - jen.If( - jen.List(jen.Id("accessKey"), jen.Err()).Op("=").Id("innerRequest").Dot("getAccessKey").Call(jen.Id("ctx")), - jen.Err().Op("!=").Nil(), - ).BlockFunc(func(group *jen.Group) { - group.Return(jen.Nil(), jen.Err()) + ) + group.Add( + jen.If( + jen.List(jen.Id("query"), jen.Err()). + Op("="). + Qual(PackageNameRegion, "NewBucketRegionsQuery"). + Call(jen.Id("bucketHosts"), jen.Op("&").Id("queryOptions")), + jen.Err().Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Add(jen.Return(jen.Nil(), jen.Err())) + }), + ) }), ) group.Add( - jen.If(jen.Id("accessKey").Op("==").Lit("")). - BlockFunc(func(group *jen.Group) { - group.Add(jen.If( - jen.Id("credentialsProvider").Op(":=").Id("storage").Dot("client").Dot("GetCredentials").Call(), - jen.Id("credentialsProvider").Op("!=").Nil(), + jen.If(jen.Id("query").Op("!=").Nil()).BlockFunc(func(group *jen.Group) { + group.Add(jen.Var().Id("accessKey").String()) + group.Add(jen.Var().Err().Error()) + group.Add( + jen.If( + jen.List(jen.Id("accessKey"), jen.Err()).Op("=").Id("innerRequest").Dot("getAccessKey").Call(jen.Id("ctx")), + jen.Err().Op("!=").Nil(), ).BlockFunc(func(group *jen.Group) { - group.If( - jen.List(jen.Id("creds"), jen.Err()). - Op(":="). - Id("credentialsProvider"). - Dot("Get"). - Call(jen.Id("ctx")), - jen.Err().Op("!=").Nil(), - ).BlockFunc(func(group *jen.Group) { - group.Return(jen.Nil(), jen.Err()) - }).Else(). - If(jen.Id("creds").Op("!=").Nil()). - BlockFunc(func(group *jen.Group) { - group.Id("accessKey").Op("=").Id("creds").Dot("AccessKey") - }) - })) - }), + group.Return(jen.Nil(), jen.Err()) + }), + ) + group.Add( + jen.If(jen.Id("accessKey").Op("==").Lit("")). + BlockFunc(func(group *jen.Group) { + group.Add(jen.If( + jen.Id("credentialsProvider").Op(":=").Id(fieldName).Dot("client").Dot("GetCredentials").Call(), + jen.Id("credentialsProvider").Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.If( + jen.List(jen.Id("creds"), jen.Err()). + Op(":="). + Id("credentialsProvider"). + Dot("Get"). + Call(jen.Id("ctx")), + jen.Err().Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Return(jen.Nil(), jen.Err()) + }).Else(). + If(jen.Id("creds").Op("!=").Nil()). + BlockFunc(func(group *jen.Group) { + group.Id("accessKey").Op("=").Id("creds").Dot("AccessKey") + }) + })) + }), + ) + group.Add( + jen.If(jen.Id("accessKey").Op("!=").Lit("")). + BlockFunc(func(group *jen.Group) { + group.Id("req").Dot("Region").Op("=").Id("query").Dot("Query").Call(jen.Id("accessKey"), jen.Id("bucketName")) + }), + ) + }), ) + }) + ifBucketIsEmptyStmt := jen.CustomFunc(jen.Options{Multi: true}, func(group *jen.Group) { + group.Add(jen.Id("req").Dot("Region").Op("=").Id(fieldName).Dot("client").Dot("GetAllRegions").Call()) group.Add( - jen.If(jen.Id("accessKey").Op("!=").Lit("").Op("&&").Id("bucketName").Op("!=").Lit("")). - BlockFunc(func(group *jen.Group) { - group.Id("req").Dot("Region").Op("=").Id("query").Dot("Query").Call(jen.Id("accessKey"), jen.Id("bucketName")) - }), + jen.If(jen.Id("req").Dot("Region").Op("==").Nil()).BlockFunc(func(group *jen.Group) { + group.Add( + jen.If(jen.Id("options").Dot("OverwrittenBucketHosts").Op("!=").Nil()).BlockFunc(func(group *jen.Group) { + group.Add( + jen.If( + jen.List(jen.Id("bucketHosts"), jen.Err()). + Op("="). + Id("options"). + Dot("OverwrittenBucketHosts"). + Dot("GetEndpoints"). + Call(jen.Id("ctx")), + jen.Err().Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Add(jen.Return(jen.Nil(), jen.Err())) + }), + ) + }), + ) + group.Add( + jen.Id("allRegionsOptions"). + Op(":="). + Qual(PackageNameRegion, "AllRegionsProviderOptions"). + ValuesFunc(func(group *jen.Group) { + group.Add(jen.Id("UseInsecureProtocol").Op(":").Id(fieldName).Dot("client").Dot("UseInsecureProtocol").Call()) + group.Add(jen.Id("HostFreezeDuration").Op(":").Id(fieldName).Dot("client").Dot("GetHostFreezeDuration").Call()) + group.Add(jen.Id("Resolver").Op(":").Id(fieldName).Dot("client").Dot("GetResolver").Call()) + group.Add(jen.Id("Chooser").Op(":").Id(fieldName).Dot("client").Dot("GetChooser").Call()) + group.Add(jen.Id("BeforeSign").Op(":").Id(fieldName).Dot("client").Dot("GetBeforeSignCallback").Call()) + group.Add(jen.Id("AfterSign").Op(":").Id(fieldName).Dot("client").Dot("GetAfterSignCallback").Call()) + group.Add(jen.Id("SignError").Op(":").Id(fieldName).Dot("client").Dot("GetSignErrorCallback").Call()) + group.Add(jen.Id("BeforeResolve").Op(":").Id(fieldName).Dot("client").Dot("GetBeforeResolveCallback").Call()) + group.Add(jen.Id("AfterResolve").Op(":").Id(fieldName).Dot("client").Dot("GetAfterResolveCallback").Call()) + group.Add(jen.Id("ResolveError").Op(":").Id(fieldName).Dot("client").Dot("GetResolveErrorCallback").Call()) + group.Add(jen.Id("BeforeBackoff").Op(":").Id(fieldName).Dot("client").Dot("GetBeforeBackoffCallback").Call()) + group.Add(jen.Id("AfterBackoff").Op(":").Id(fieldName).Dot("client").Dot("GetAfterBackoffCallback").Call()) + group.Add(jen.Id("BeforeRequest").Op(":").Id(fieldName).Dot("client").Dot("GetBeforeRequestCallback").Call()) + group.Add(jen.Id("AfterResponse").Op(":").Id(fieldName).Dot("client").Dot("GetAfterResponseCallback").Call()) + }), + ) + group.Add( + jen.If( + jen.Id("hostRetryConfig").Op(":=").Id(fieldName).Dot("client").Dot("GetHostRetryConfig").Call(), + jen.Id("hostRetryConfig").Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Id("allRegionsOptions").Dot("RetryMax").Op("=").Id("hostRetryConfig").Dot("RetryMax") + group.Id("allRegionsOptions").Dot("Backoff").Op("=").Id("hostRetryConfig").Dot("Backoff") + }), + ) + group.Add(jen.Id("credentials").Op(":=").Id("innerRequest").Dot("Credentials")) + group.Add(jen.If(jen.Id("credentials").Op("==").Nil()).BlockFunc(func(group *jen.Group) { + group.Add(jen.Id("credentials").Op("=").Id(fieldName).Dot("client").Dot("GetCredentials").Call()) + })) + group.Add( + jen.If( + jen.List(jen.Id("req").Dot("Region"), jen.Err()). + Op("="). + Qual(PackageNameRegion, "NewAllRegionsProvider"). + Call(jen.Id("credentials"), jen.Id("bucketHosts"), jen.Op("&").Id("allRegionsOptions")), + jen.Err().Op("!=").Nil(), + ).BlockFunc(func(group *jen.Group) { + group.Add(jen.Return(jen.Nil(), jen.Err())) + }), + ) + }), ) - }), - ) + }) + if !isStorageAPIs() { + group.Add(ifBucketIsEmptyStmt) + } else if description.isApiService() { + group.Add(ifBucketIsNotEmptyStmt).Else().Block(ifBucketIsEmptyStmt) + } else { + group.Add(ifBucketIsNotEmptyStmt) + } + } }), ) if description.Request.Authorization.ToAuthorization() == AuthorizationNone { @@ -550,7 +671,7 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt jen.If( jen.Err(). Op(":="). - Id("storage"). + Id(fieldName). Dot("client"). Dot("DoAndAcceptJSON"). Call( @@ -568,7 +689,7 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt group.Add( jen.List(jen.Id("resp"), jen.Err()). Op(":="). - Id("storage"). + Id(fieldName). Dot("client"). Dot("Do"). Call( @@ -597,7 +718,7 @@ func (description *ApiDetailedDescription) generatePackage(group *jen.Group, opt group.Add( jen.List(jen.Id("resp"), jen.Err()). Op(":="). - Id("storage"). + Id(fieldName). Dot("client"). Dot("Do"). Call( @@ -757,13 +878,27 @@ func (description *ApiDetailedDescription) addJsonMarshalerUnmarshaler(group *je func (description *ApiDetailedDescription) getBasePathSegments() []string { basePath := strings.TrimPrefix(description.BasePath, "/") basePath = strings.TrimSuffix(basePath, "/") - return strings.Split(basePath, "/") + segments := strings.Split(basePath, "/") + newSegments := make([]string, 0, len(segments)) + for _, segment := range segments { + if segment != "" { + newSegments = append(newSegments, segment) + } + } + return newSegments } func (description *ApiDetailedDescription) getPathSuffixSegments() []string { pathSuffix := strings.TrimPrefix(description.PathSuffix, "/") pathSuffix = strings.TrimSuffix(pathSuffix, "/") - return strings.Split(pathSuffix, "/") + segments := strings.Split(pathSuffix, "/") + newSegments := make([]string, 0, len(segments)) + for _, segment := range segments { + if segment != "" { + newSegments = append(newSegments, segment) + } + } + return newSegments } func (description *ApiDetailedDescription) isBucketService() bool { @@ -774,3 +909,12 @@ func (description *ApiDetailedDescription) isBucketService() bool { } return false } + +func (description *ApiDetailedDescription) isApiService() bool { + for _, service := range description.ServiceNames { + if service == ServiceNameApi { + return true + } + } + return false +} diff --git a/storagev2/internal/api-generator/form.go b/internal/api-generator/form.go similarity index 98% rename from storagev2/internal/api-generator/form.go rename to internal/api-generator/form.go index dc9f2f15..a35254af 100644 --- a/storagev2/internal/api-generator/form.go +++ b/internal/api-generator/form.go @@ -1,7 +1,6 @@ package main import ( - "errors" "fmt" "github.com/dave/jennifer/jen" @@ -217,9 +216,6 @@ func (form *FormUrlencodedRequestStruct) addSetCall(group *jen.Group, field Form ) fieldName := field.camelCaseName() if field.Multiple { - if field.Optional.ToOptionalType() != OptionalTypeRequired { - return errors.New("multiple field must be required") - } valueConvertCode, err = field.Type.GenerateConvertCodeToString(jen.Id("value")) if err != nil { return err diff --git a/storagev2/internal/api-generator/headers.go b/internal/api-generator/headers.go similarity index 100% rename from storagev2/internal/api-generator/headers.go rename to internal/api-generator/headers.go diff --git a/storagev2/internal/api-generator/json.go b/internal/api-generator/json.go similarity index 100% rename from storagev2/internal/api-generator/json.go rename to internal/api-generator/json.go diff --git a/storagev2/internal/api-generator/main.go b/internal/api-generator/main.go similarity index 59% rename from storagev2/internal/api-generator/main.go rename to internal/api-generator/main.go index 310dd31e..922a76be 100644 --- a/storagev2/internal/api-generator/main.go +++ b/internal/api-generator/main.go @@ -4,10 +4,11 @@ import ( "fmt" "io/ioutil" "os" - "os/exec" "path/filepath" "github.com/dave/jennifer/jen" + "github.com/iancoleman/strcase" + goflags "github.com/jessevdk/go-flags" "gopkg.in/yaml.v3" ) @@ -18,59 +19,52 @@ const ( PackageNameRegion = "github.com/qiniu/go-sdk/v7/storagev2/region" PackageNameUpToken = "github.com/qiniu/go-sdk/v7/storagev2/uptoken" PackageNameErrors = "github.com/qiniu/go-sdk/v7/storagev2/errors" - PackageNameApis = "github.com/qiniu/go-sdk/v7/storagev2/apis" - PackageNameUplog = "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" + PackageNameUplog = "github.com/qiniu/go-sdk/v7/internal/uplog" PackageNameInternalIo = "github.com/qiniu/go-sdk/v7/internal/io" ) +var flags struct { + ApiSpecsPaths []string `long:"api-specs" required:"true"` + OutputDirPath string `long:"output" required:"true"` + ApiPackagePath string `long:"api-package" required:"true"` + StructName string `long:"struct-name" required:"true"` +} + func main() { - rootProjectPath, err := os.Getwd() + _, err := goflags.ParseArgs(&flags, os.Args[2:]) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to get working directory: %s\n", err) + fmt.Fprintf(os.Stderr, "%s\n", err) os.Exit(1) } - - storageApiSpecsPaths := []string{ - filepath.Join(rootProjectPath, "..", "api-specs", "storage"), - filepath.Join(rootProjectPath, "internal", "api-specs"), - } - storageGeneratedDirPath := filepath.Join(rootProjectPath, "apis") - - os.RemoveAll(storageGeneratedDirPath) - - for _, storageApiSpecsPath := range storageApiSpecsPaths { - storageApiSpecEntries, err := ioutil.ReadDir(storageApiSpecsPath) + os.RemoveAll(flags.OutputDirPath) + for _, apiSpecsPath := range flags.ApiSpecsPaths { + entries, err := ioutil.ReadDir(apiSpecsPath) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to read directory %s: %s\n", storageApiSpecsPath, err) + fmt.Fprintf(os.Stderr, "Failed to read directory %s: %s\n", apiSpecsPath, err) os.Exit(1) } - for _, storageApiSpecEntry := range storageApiSpecEntries { - apiSpecName := extractApiSpecName(storageApiSpecEntry.Name()) - apiSpecPath := filepath.Join(storageApiSpecsPath, storageApiSpecEntry.Name()) - generatedDirPath := filepath.Join(storageGeneratedDirPath, apiSpecName) - if err = os.MkdirAll(generatedDirPath, 0755); err != nil { - fmt.Fprintf(os.Stderr, "Failed to create directory %s: %s\n", generatedDirPath, err) + for _, entry := range entries { + apiSpecName := extractApiSpecName(entry.Name()) + generatedApiDirPath := filepath.Join(flags.OutputDirPath, apiSpecName) + if err = os.MkdirAll(generatedApiDirPath, 0755); err != nil { + fmt.Fprintf(os.Stderr, "Failed to create directory %s: %s\n", generatedApiDirPath, err) os.Exit(1) } - if err = writeGolangPackages(apiSpecName, apiSpecPath, storageGeneratedDirPath); err != nil { + if err = writeGolangPackages(apiSpecName, filepath.Join(apiSpecsPath, entry.Name()), flags.OutputDirPath); err != nil { fmt.Fprintf(os.Stderr, "Failed to write go package %s: %s\n", apiSpecName, err) os.Exit(1) } } } - if err = writeApiClient(storageGeneratedDirPath); err != nil { + if err = writeApiClient(flags.OutputDirPath); err != nil { fmt.Fprintf(os.Stderr, "Failed to write api client: %s\n", err) os.Exit(1) } - if err = goBuildPackage("./apis/..."); err != nil { - fmt.Fprintf(os.Stderr, "Failed to build go package ./apis/...: %s\n", err) - os.Exit(1) - } } -func writeGolangPackages(apiSpecName, apiSpecPath, storageGeneratedDirPath string) (err error) { - generatedDirPath := filepath.Join(storageGeneratedDirPath, apiSpecName) +func writeGolangPackages(apiSpecName, apiSpecPath, generatedDirPath string) (err error) { + generatedApiDirPath := filepath.Join(generatedDirPath, apiSpecName) apiSpecFile, err := os.Open(apiSpecPath) if err != nil { return @@ -87,10 +81,10 @@ func writeGolangPackages(apiSpecName, apiSpecPath, storageGeneratedDirPath strin return } - if err = writeSubPackage(apiSpecName, generatedDirPath, &apiSpec); err != nil { + if err = writeSubPackage(apiSpecName, generatedApiDirPath, &apiSpec); err != nil { return } - return writeApiPackage(apiSpecName, storageGeneratedDirPath, &apiSpec) + return writeApiPackage(apiSpecName, generatedDirPath, &apiSpec) } func writeSubPackage(apiSpecName, generatedDirPath string, apiSpec *ApiDetailedDescription) error { @@ -108,7 +102,7 @@ func writeSubPackage(apiSpecName, generatedDirPath string, apiSpec *ApiDetailedD return packageFile.Save(filepath.Join(generatedDirPath, "api.go")) } -func writeApiPackage(apiSpecName, storageGeneratedDirPath string, apiSpec *ApiDetailedDescription) error { +func writeApiPackage(apiSpecName, generatedDirPath string, apiSpec *ApiDetailedDescription) error { apisPackageFile := jen.NewFile("apis") apisPackageFile.HeaderComment("THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY!") if err := apiSpec.generatePackage(apisPackageFile.Group, CodeGeneratorOptions{ @@ -119,38 +113,32 @@ func writeApiPackage(apiSpecName, storageGeneratedDirPath string, apiSpec *ApiDe }); err != nil { return err } - return apisPackageFile.Save(filepath.Join(storageGeneratedDirPath, "api_"+apiSpecName+".go")) -} - -func goBuildPackage(packagePath string) error { - cmd := exec.Command("go", "build", packagePath) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - return cmd.Run() + return apisPackageFile.Save(filepath.Join(generatedDirPath, "api_"+apiSpecName+".go")) } -func writeApiClient(storageGeneratedDirPath string) error { +func writeApiClient(generatedDirPath string) error { apiPackageFile := jen.NewFile("apis") apiPackageFile.HeaderComment("THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY!") generateApiClient(apiPackageFile.Group) - return apiPackageFile.Save(filepath.Join(storageGeneratedDirPath, "apis.go")) + return apiPackageFile.Save(filepath.Join(generatedDirPath, "apis.go")) } func generateApiClient(group *jen.Group) { + structName := strcase.ToCamel(flags.StructName) group.Add(jen.Comment("API 客户端")) group.Add( - jen.Type().Id("Storage").StructFunc(func(group *jen.Group) { + jen.Type().Id(structName).StructFunc(func(group *jen.Group) { group.Add(jen.Id("client").Op("*").Qual(PackageNameHTTPClient, "Client")) }), ) group.Add(jen.Comment("创建 API 客户端")) group.Add( jen.Func(). - Id("NewStorage"). + Id("New" + structName). Params(jen.Id("options").Op("*").Qual(PackageNameHTTPClient, "Options")). - Params(jen.Op("*").Id("Storage")). + Params(jen.Op("*").Id(structName)). BlockFunc(func(group *jen.Group) { - group.Return(jen.Op("&").Id("Storage").ValuesFunc(func(group *jen.Group) { + group.Return(jen.Op("&").Id(structName).ValuesFunc(func(group *jen.Group) { group.Add(jen.Id("client").Op(":").Qual(PackageNameHTTPClient, "NewClient").Call(jen.Id("options"))) })) }), @@ -170,3 +158,8 @@ func generateApiClient(group *jen.Group) { }), ) } + +func isStorageAPIs() bool { + structName := strcase.ToCamel(flags.StructName) + return structName == "Storage" +} diff --git a/storagev2/internal/api-generator/multipart.go b/internal/api-generator/multipart.go similarity index 100% rename from storagev2/internal/api-generator/multipart.go rename to internal/api-generator/multipart.go diff --git a/storagev2/internal/api-generator/path.go b/internal/api-generator/path.go similarity index 97% rename from storagev2/internal/api-generator/path.go rename to internal/api-generator/path.go index 160d0889..842c9c8d 100644 --- a/storagev2/internal/api-generator/path.go +++ b/internal/api-generator/path.go @@ -178,7 +178,14 @@ func (pp *PathParams) addBuildFunc(group *jen.Group, structName string) error { Params(). Params(jen.Index().Add(jen.String()), jen.Error()). BlockFunc(func(group *jen.Group) { - group.Add(jen.Var().Id("allSegments").Index().Add(jen.String())) + guessPathSegmentsCount := 0 + for _, namedPathParam := range pp.Named { + guessPathSegmentsCount += 1 + if namedPathParam.PathSegment != "" { + guessPathSegmentsCount += 1 + } + } + group.Add(jen.Id("allSegments").Op(":=").Make(jen.Index().Add(jen.String()), jen.Lit(0), jen.Lit(guessPathSegmentsCount))) for _, namedPathParam := range pp.Named { var ( code jen.Code diff --git a/storagev2/internal/api-generator/query.go b/internal/api-generator/query.go similarity index 97% rename from storagev2/internal/api-generator/query.go rename to internal/api-generator/query.go index 21a297b2..af2eb9bb 100644 --- a/storagev2/internal/api-generator/query.go +++ b/internal/api-generator/query.go @@ -191,23 +191,22 @@ func (names QueryNames) generateSetCall(group *jen.Group, queryName QueryName, q fieldName := queryName.camelCaseName() field := jen.Id("query").Dot(fieldName) if queryName.Multiple { - if queryName.Optional.ToOptionalType() != OptionalTypeRequired { - return errors.New("multiple field must be required") - } valueConvertCode, err = queryName.QueryType.GenerateConvertCodeToString(jen.Id("value")) if err != nil { return err } - group.Add(jen.If(jen.Len(jen.Id("query").Dot(fieldName)).Op(">").Lit(0)). + code := jen.If(jen.Len(jen.Id("query").Dot(fieldName)).Op(">").Lit(0)). BlockFunc(func(group *jen.Group) { group.Add( jen.For(jen.List(jen.Id("_"), jen.Id("value")).Op(":=").Range().Add(jen.Id("query").Dot(fieldName))).BlockFunc(func(group *jen.Group) { group.Add(jen.Id(queryVarName).Dot("Add").Call(jen.Lit(queryName.QueryName), valueConvertCode)) }), ) - }). - Else(). - BlockFunc(appendMissingRequiredFieldErrorFunc(fieldName))) + }) + if queryName.Optional.ToOptionalType() == OptionalTypeRequired { + code = code.Else().BlockFunc(appendMissingRequiredFieldErrorFunc(fieldName)) + } + group.Add(code) } else { if queryName.Optional.ToOptionalType() == OptionalTypeNullable { valueConvertCode, err = queryName.QueryType.GenerateConvertCodeToString(jen.Op("*").Add(field)) diff --git a/storagev2/internal/api-generator/request.go b/internal/api-generator/request.go similarity index 100% rename from storagev2/internal/api-generator/request.go rename to internal/api-generator/request.go diff --git a/storagev2/internal/api-generator/response.go b/internal/api-generator/response.go similarity index 100% rename from storagev2/internal/api-generator/response.go rename to internal/api-generator/response.go diff --git a/storagev2/internal/api-generator/types.go b/internal/api-generator/types.go similarity index 98% rename from storagev2/internal/api-generator/types.go rename to internal/api-generator/types.go index 98df39cd..09996c1a 100644 --- a/storagev2/internal/api-generator/types.go +++ b/internal/api-generator/types.go @@ -25,6 +25,7 @@ const ( MethodNameGET MethodName = http.MethodGet MethodNamePOST MethodName = http.MethodPost MethodNamePUT MethodName = http.MethodPut + MethodNamePATCH MethodName = http.MethodPatch MethodNameDELETE MethodName = http.MethodDelete ServiceNameUp ServiceName = "up" @@ -82,6 +83,8 @@ func (s MethodName) ToString() (string, error) { return string(MethodNamePOST), nil case "put": return string(MethodNamePUT), nil + case "patch": + return string(MethodNamePATCH), nil case "delete": return string(MethodNameDELETE), nil default: diff --git a/storagev2/internal/api-generator/utils.go b/internal/api-generator/utils.go similarity index 100% rename from storagev2/internal/api-generator/utils.go rename to internal/api-generator/utils.go diff --git a/internal/clientv2/interceptor_auth.go b/internal/clientv2/interceptor_auth.go index 8fee2954..7d070b3b 100644 --- a/internal/clientv2/interceptor_auth.go +++ b/internal/clientv2/interceptor_auth.go @@ -4,11 +4,12 @@ import ( "net/http" "github.com/qiniu/go-sdk/v7/auth" + "github.com/qiniu/go-sdk/v7/storagev2/credentials" ) type AuthConfig struct { // 鉴权参数 - Credentials *auth.Credentials + Credentials credentials.CredentialsProvider // 鉴权类型,不包含上传 TokenType auth.TokenType // 签名前回调函数 @@ -39,10 +40,14 @@ func (interceptor *authInterceptor) Intercept(req *http.Request, handler Handler } if credentials := interceptor.config.Credentials; credentials != nil { + creds, err := credentials.Get(req.Context()) + if err != nil { + return nil, err + } if interceptor.config.BeforeSign != nil { interceptor.config.BeforeSign(req) } - if err := credentials.AddToken(interceptor.config.TokenType, req); err != nil { + if err := creds.AddToken(interceptor.config.TokenType, req); err != nil { if interceptor.config.SignError != nil { interceptor.config.SignError(req, err) } diff --git a/internal/clientv2/interceptor_retry_simple.go b/internal/clientv2/interceptor_retry_simple.go index 91f0e3c1..c3e9d444 100644 --- a/internal/clientv2/interceptor_retry_simple.go +++ b/internal/clientv2/interceptor_retry_simple.go @@ -108,6 +108,10 @@ func (interceptor *simpleRetryInterceptor) Intercept(req *http.Request, handler req, chosenIPs = interceptor.choose(req, resolvedIPs, hostname) resp, err = interceptor.callHandler(req, &retrier.RetrierOptions{Attempts: i}, handler) + if err == nil && resp.StatusCode/100 >= 4 { + err = clientv1.ResponseError(resp) + } + retryDecision := interceptor.config.getRetryDecision(reqBefore, resp, err, i) if retryDecision == retrier.DontRetry { interceptor.feedbackGood(req, hostname, chosenIPs) diff --git a/internal/clientv2/multipart.go b/internal/clientv2/multipart.go index 7e4b402a..69c4cc7c 100644 --- a/internal/clientv2/multipart.go +++ b/internal/clientv2/multipart.go @@ -1,11 +1,13 @@ package clientv2 import ( + "crypto/rand" "fmt" "io" "mime/multipart" "net/textproto" "strings" + "sync" "github.com/qiniu/go-sdk/v7/internal/context" compatible_io "github.com/qiniu/go-sdk/v7/internal/io" @@ -21,11 +23,13 @@ type ( } MultipartForm struct { - values []keyValuePair - files []keyFilePair - ctx context.Context - cancel context.CancelCauseFunc - w *io.PipeWriter + values []keyValuePair + files []keyFilePair + ctx context.Context + cancel context.CancelCauseFunc + w *io.PipeWriter + boundary string + boundaryOnce sync.Once } multipartFormReader struct { @@ -46,10 +50,23 @@ func (f *MultipartForm) SetFile(key, fileName, contentType string, stream compat return f } +func (f *MultipartForm) generateBoundary() string { + f.boundaryOnce.Do(func() { + var buf [30]byte + _, err := io.ReadFull(rand.Reader, buf[:]) + if err != nil { + panic(err) + } + f.boundary = fmt.Sprintf("%x", buf[:]) + }) + return f.boundary +} + func newMultipartFormReader(form *MultipartForm) *multipartFormReader { reader := &multipartFormReader{form: form} reader.r, form.w = io.Pipe() reader.multipartWriter = multipart.NewWriter(form.w) + reader.multipartWriter.SetBoundary(form.generateBoundary()) go func(multipartWriter *multipart.Writer, w *io.PipeWriter, ctx context.Context, cancel context.CancelCauseFunc) { defer w.Close() @@ -91,13 +108,13 @@ func (r *multipartFormReader) Read(p []byte) (int, error) { } } -func (r *multipartFormReader) Close() (err error) { +func (r *multipartFormReader) Close() error { if r.closed { return nil } r.closed = true r.form.cancel(io.ErrClosedPipe) - err = r.r.Close() + err := r.r.Close() for _, pair := range r.form.files { if e := pair.stream.Close(); e != nil && err == nil { err = e @@ -140,7 +157,7 @@ func GetMultipartFormRequestBody(info *MultipartForm) GetRequestBody { } } r := newMultipartFormReader(info) - o.Header.Add("Content-Type", r.formDataContentType()) + o.Header.Set("Content-Type", r.formDataContentType()) return r, nil } } diff --git a/storagev2/internal/uplog/block_uplog.go b/internal/uplog/block_uplog.go similarity index 100% rename from storagev2/internal/uplog/block_uplog.go rename to internal/uplog/block_uplog.go diff --git a/storagev2/internal/uplog/dns1.12.go b/internal/uplog/dns1.12.go similarity index 100% rename from storagev2/internal/uplog/dns1.12.go rename to internal/uplog/dns1.12.go diff --git a/storagev2/internal/uplog/dns1.13.go b/internal/uplog/dns1.13.go similarity index 100% rename from storagev2/internal/uplog/dns1.13.go rename to internal/uplog/dns1.13.go diff --git a/storagev2/internal/uplog/quality_uplog.go b/internal/uplog/quality_uplog.go similarity index 100% rename from storagev2/internal/uplog/quality_uplog.go rename to internal/uplog/quality_uplog.go diff --git a/storagev2/internal/uplog/request_uplog.go b/internal/uplog/request_uplog.go similarity index 100% rename from storagev2/internal/uplog/request_uplog.go rename to internal/uplog/request_uplog.go diff --git a/storagev2/internal/uplog/uplog.go b/internal/uplog/uplog.go similarity index 100% rename from storagev2/internal/uplog/uplog.go rename to internal/uplog/uplog.go diff --git a/storagev2/internal/uplog/uplog_buffer.go b/internal/uplog/uplog_buffer.go similarity index 100% rename from storagev2/internal/uplog/uplog_buffer.go rename to internal/uplog/uplog_buffer.go diff --git a/storagev2/internal/uplog/uplog_buffer_test.go b/internal/uplog/uplog_buffer_test.go similarity index 100% rename from storagev2/internal/uplog/uplog_buffer_test.go rename to internal/uplog/uplog_buffer_test.go diff --git a/storagev2/internal/uplog/uplog_prod_env.go b/internal/uplog/uplog_prod_env.go similarity index 100% rename from storagev2/internal/uplog/uplog_prod_env.go rename to internal/uplog/uplog_prod_env.go diff --git a/storagev2/internal/uplog/uplog_test_env.go b/internal/uplog/uplog_test_env.go similarity index 100% rename from storagev2/internal/uplog/uplog_test_env.go rename to internal/uplog/uplog_test_env.go diff --git a/storagev2/internal/uplog/uplog_upload.go b/internal/uplog/uplog_upload.go similarity index 100% rename from storagev2/internal/uplog/uplog_upload.go rename to internal/uplog/uplog_upload.go diff --git a/storagev2/internal/uplog/utils.go b/internal/uplog/utils.go similarity index 100% rename from storagev2/internal/uplog/utils.go rename to internal/uplog/utils.go diff --git a/media/apis/api_pfop.go b/media/apis/api_pfop.go new file mode 100644 index 00000000..60cc7301 --- /dev/null +++ b/media/apis/api_pfop.go @@ -0,0 +1,119 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + pfop "github.com/qiniu/go-sdk/v7/media/apis/pfop" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strconv" + "strings" + "time" +) + +type innerPfopRequest pfop.Request + +func (form *innerPfopRequest) build() (url.Values, error) { + formValues := make(url.Values) + if form.BucketName != "" { + formValues.Set("bucket", form.BucketName) + } else { + return nil, errors.MissingRequiredFieldError{Name: "BucketName"} + } + if form.ObjectName != "" { + formValues.Set("key", form.ObjectName) + } else { + return nil, errors.MissingRequiredFieldError{Name: "ObjectName"} + } + if form.Fops != "" { + formValues.Set("fops", form.Fops) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Fops"} + } + if form.NotifyUrl != "" { + formValues.Set("notifyURL", form.NotifyUrl) + } + if form.Force != 0 { + formValues.Set("force", strconv.FormatInt(form.Force, 10)) + } + if form.Type != 0 { + formValues.Set("type", strconv.FormatInt(form.Type, 10)) + } + if form.Pipeline != "" { + formValues.Set("pipeline", form.Pipeline) + } + return formValues, nil +} + +type PfopRequest = pfop.Request +type PfopResponse = pfop.Response + +// 触发持久化数据处理命令 +func (media *Media) Pfop(ctx context.Context, request *PfopRequest, options *Options) (*PfopResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerPfopRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && media.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 1) + pathSegments = append(pathSegments, "pfop") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + body, err := innerRequest.build() + if err != nil { + return nil, err + } + uplogInterceptor, err := uplog.NewRequestUplog("pfop", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = media.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: httpclient.GetFormRequestBody(body), OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && media.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = media.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: media.client.UseInsecureProtocol(), HostFreezeDuration: media.client.GetHostFreezeDuration(), Resolver: media.client.GetResolver(), Chooser: media.client.GetChooser(), BeforeSign: media.client.GetBeforeSignCallback(), AfterSign: media.client.GetAfterSignCallback(), SignError: media.client.GetSignErrorCallback(), BeforeResolve: media.client.GetBeforeResolveCallback(), AfterResolve: media.client.GetAfterResolveCallback(), ResolveError: media.client.GetResolveErrorCallback(), BeforeBackoff: media.client.GetBeforeBackoffCallback(), AfterBackoff: media.client.GetAfterBackoffCallback(), BeforeRequest: media.client.GetBeforeRequestCallback(), AfterResponse: media.client.GetAfterResponseCallback()} + if hostRetryConfig := media.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = media.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody PfopResponse + if err := media.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/media/apis/api_prefop.go b/media/apis/api_prefop.go new file mode 100644 index 00000000..eba964d9 --- /dev/null +++ b/media/apis/api_prefop.go @@ -0,0 +1,97 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + prefop "github.com/qiniu/go-sdk/v7/media/apis/prefop" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strings" + "time" +) + +type innerPrefopRequest prefop.Request + +func (query *innerPrefopRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.PersistentId != "" { + allQuery.Set("id", query.PersistentId) + } else { + return nil, errors.MissingRequiredFieldError{Name: "PersistentId"} + } + return allQuery, nil +} + +type PrefopRequest = prefop.Request +type PrefopResponse = prefop.Response + +// 查询持久化数据处理命令的执行状态 +func (media *Media) Prefop(ctx context.Context, request *PrefopRequest, options *Options) (*PrefopResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerPrefopRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && media.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "status", "get", "prefop") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + uplogInterceptor, err := uplog.NewRequestUplog("prefop", "", "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = media.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy("", time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && media.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + + req.Region = media.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: media.client.UseInsecureProtocol(), HostFreezeDuration: media.client.GetHostFreezeDuration(), Resolver: media.client.GetResolver(), Chooser: media.client.GetChooser(), BeforeSign: media.client.GetBeforeSignCallback(), AfterSign: media.client.GetAfterSignCallback(), SignError: media.client.GetSignErrorCallback(), BeforeResolve: media.client.GetBeforeResolveCallback(), AfterResolve: media.client.GetAfterResolveCallback(), ResolveError: media.client.GetResolveErrorCallback(), BeforeBackoff: media.client.GetBeforeBackoffCallback(), AfterBackoff: media.client.GetAfterBackoffCallback(), BeforeRequest: media.client.GetBeforeRequestCallback(), AfterResponse: media.client.GetAfterResponseCallback()} + if hostRetryConfig := media.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = media.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + var respBody PrefopResponse + if err := media.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/media/apis/apis.go b/media/apis/apis.go new file mode 100644 index 00000000..96bfee86 --- /dev/null +++ b/media/apis/apis.go @@ -0,0 +1,27 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" +) + +// API 客户端 +type Media struct { + client *httpclient.Client +} + +// 创建 API 客户端 +func NewMedia(options *httpclient.Options) *Media { + return &Media{client: httpclient.NewClient(options)} +} + +// API 客户端选项 +type Options struct { + OverwrittenBucketHosts region.EndpointsProvider + OverwrittenBucketName string + OverwrittenEndpoints region.EndpointsProvider + OverwrittenRegion region.RegionsProvider + OnRequestProgress func(uint64, uint64) +} diff --git a/media/apis/pfop/api.go b/media/apis/pfop/api.go new file mode 100644 index 00000000..3cc9aae6 --- /dev/null +++ b/media/apis/pfop/api.go @@ -0,0 +1,54 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 触发持久化数据处理命令 +package pfop + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + BucketName string // 空间名称 + ObjectName string // 对象名称 + Fops string // 数据处理命令列表,以 `;` 分隔,可以指定多个数据处理命令 + NotifyUrl string // 处理结果通知接收 URL + Force int64 // 强制执行数据处理,设为 `1`,则可强制执行数据处理并覆盖原结果 + Type int64 // 任务类型,支持 `0` 表示普通任务,`1` 表示闲时任务 + Pipeline string // 对列名,仅适用于普通任务 +} + +// 获取 API 所用的响应 +type Response struct { + PersistentId string // 持久化数据处理任务 ID +} + +// 返回的持久化数据处理任务 ID +type PfopId = Response +type jsonResponse struct { + PersistentId string `json:"persistentId"` // 持久化数据处理任务 ID +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{PersistentId: j.PersistentId}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PersistentId = nj.PersistentId + return nil +} +func (j *Response) validate() error { + if j.PersistentId == "" { + return errors.MissingRequiredFieldError{Name: "PersistentId"} + } + return nil +} diff --git a/media/apis/prefop/api.go b/media/apis/prefop/api.go new file mode 100644 index 00000000..25144eee --- /dev/null +++ b/media/apis/prefop/api.go @@ -0,0 +1,166 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 查询持久化数据处理命令的执行状态 +package prefop + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + PersistentId string // 持久化数据处理任务 ID + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct { + PersistentId string // 持久化数据处理任务 ID + Code int64 // 持久化数据处理任务状态码 + Description string // 与状态码相对应的详细描述 + ObjectName string // 源对象名称 + BucketName string // 源空间名称 + Pipeline string // 云处理操作的处理队列 + RequestId string // 云处理请求的请求 ID + Type int64 // 任务类型,支持 `0` 表示普通任务,`1` 表示闲时任务 + CreatedAt string // 任务创建时间 + Items PfopTaskItems // 云处理操作列表 +} + +// 返回的持久化数据处理任务中的云处理操作状态 +type PfopTaskItem struct { + Command string // 云操作命令 + Code int64 // 云操作状态码 + Description string // 与状态码相对应的详细描述 + Error string // 如果处理失败,该字段会给出失败的详细原因 + Hash string // 云处理结果保存在服务端的唯一标识 + ObjectName string // 云处理结果的外链对象名称 + ReturnOld int64 // 是否返回了旧的数据 +} +type jsonPfopTaskItem struct { + Command string `json:"cmd"` // 云操作命令 + Code int64 `json:"code"` // 云操作状态码 + Description string `json:"desc"` // 与状态码相对应的详细描述 + Error string `json:"error,omitempty"` // 如果处理失败,该字段会给出失败的详细原因 + Hash string `json:"hash"` // 云处理结果保存在服务端的唯一标识 + ObjectName string `json:"key"` // 云处理结果的外链对象名称 + ReturnOld int64 `json:"returnOld"` // 是否返回了旧的数据 +} + +func (j *PfopTaskItem) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonPfopTaskItem{Command: j.Command, Code: j.Code, Description: j.Description, Error: j.Error, Hash: j.Hash, ObjectName: j.ObjectName, ReturnOld: j.ReturnOld}) +} +func (j *PfopTaskItem) UnmarshalJSON(data []byte) error { + var nj jsonPfopTaskItem + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Command = nj.Command + j.Code = nj.Code + j.Description = nj.Description + j.Error = nj.Error + j.Hash = nj.Hash + j.ObjectName = nj.ObjectName + j.ReturnOld = nj.ReturnOld + return nil +} +func (j *PfopTaskItem) validate() error { + if j.Command == "" { + return errors.MissingRequiredFieldError{Name: "Command"} + } + if j.Code == 0 { + return errors.MissingRequiredFieldError{Name: "Code"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.Hash == "" { + return errors.MissingRequiredFieldError{Name: "Hash"} + } + if j.ObjectName == "" { + return errors.MissingRequiredFieldError{Name: "ObjectName"} + } + if j.ReturnOld == 0 { + return errors.MissingRequiredFieldError{Name: "ReturnOld"} + } + return nil +} + +// 返回的持久化数据处理任务中的云处理操作列表 +type PfopTaskItems = []PfopTaskItem + +// 返回的持久化数据处理任务信息 +type PfopTask = Response +type jsonResponse struct { + PersistentId string `json:"id"` // 持久化数据处理任务 ID + Code int64 `json:"code"` // 持久化数据处理任务状态码 + Description string `json:"desc"` // 与状态码相对应的详细描述 + ObjectName string `json:"inputKey"` // 源对象名称 + BucketName string `json:"inputBucket"` // 源空间名称 + Pipeline string `json:"pipeline"` // 云处理操作的处理队列 + RequestId string `json:"reqid"` // 云处理请求的请求 ID + Type int64 `json:"type,omitempty"` // 任务类型,支持 `0` 表示普通任务,`1` 表示闲时任务 + CreatedAt string `json:"creationDate,omitempty"` // 任务创建时间 + Items PfopTaskItems `json:"items"` // 云处理操作列表 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{PersistentId: j.PersistentId, Code: j.Code, Description: j.Description, ObjectName: j.ObjectName, BucketName: j.BucketName, Pipeline: j.Pipeline, RequestId: j.RequestId, Type: j.Type, CreatedAt: j.CreatedAt, Items: j.Items}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.PersistentId = nj.PersistentId + j.Code = nj.Code + j.Description = nj.Description + j.ObjectName = nj.ObjectName + j.BucketName = nj.BucketName + j.Pipeline = nj.Pipeline + j.RequestId = nj.RequestId + j.Type = nj.Type + j.CreatedAt = nj.CreatedAt + j.Items = nj.Items + return nil +} +func (j *Response) validate() error { + if j.PersistentId == "" { + return errors.MissingRequiredFieldError{Name: "PersistentId"} + } + if j.Code == 0 { + return errors.MissingRequiredFieldError{Name: "Code"} + } + if j.Description == "" { + return errors.MissingRequiredFieldError{Name: "Description"} + } + if j.ObjectName == "" { + return errors.MissingRequiredFieldError{Name: "ObjectName"} + } + if j.BucketName == "" { + return errors.MissingRequiredFieldError{Name: "BucketName"} + } + if j.Pipeline == "" { + return errors.MissingRequiredFieldError{Name: "Pipeline"} + } + if j.RequestId == "" { + return errors.MissingRequiredFieldError{Name: "RequestId"} + } + if len(j.Items) == 0 { + return errors.MissingRequiredFieldError{Name: "Items"} + } + for _, value := range j.Items { + if err := value.validate(); err != nil { + return err + } + } + return nil +} diff --git a/media/doc.go b/media/doc.go new file mode 100644 index 00000000..7fab6136 --- /dev/null +++ b/media/doc.go @@ -0,0 +1,5 @@ +// media 包提供了数据处理等功能。 +package media + +//go:generate go run ../internal/api-generator -- --api-specs=../api-specs/media --output=apis/ --struct-name=Media --api-package=github.com/qiniu/go-sdk/v7/media/apis +//go:generate go build ./apis/... diff --git a/storage/pfop.go b/storage/pfop.go index c0f0fc3e..0cb14479 100644 --- a/storage/pfop.go +++ b/storage/pfop.go @@ -4,18 +4,21 @@ import ( "context" "errors" "fmt" - "net/http" + "time" "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/client" - "github.com/qiniu/go-sdk/v7/conf" + "github.com/qiniu/go-sdk/v7/internal/clientv2" + "github.com/qiniu/go-sdk/v7/media/apis" + "github.com/qiniu/go-sdk/v7/storagev2/http_client" ) // OperationManager 提供了数据处理相关的方法 type OperationManager struct { - Client *client.Client - Mac *auth.Credentials - Cfg *Config + Client *client.Client + Mac *auth.Credentials + Cfg *Config + apiClient *apis.Media } // NewOperationManager 用来构建一个新的数据处理对象 @@ -36,10 +39,21 @@ func NewOperationManagerEx(mac *auth.Credentials, cfg *Config, clt *client.Clien clt = &client.DefaultClient } + opts := http_client.Options{ + BasicHTTPClient: clt.Client, + Credentials: mac, + Interceptors: []clientv2.Interceptor{}, + UseInsecureProtocol: !cfg.UseHTTPS, + } + if region := cfg.GetRegion(); region != nil { + opts.Regions = region + } + return &OperationManager{ - Client: clt, - Mac: mac, - Cfg: cfg, + Client: clt, + Mac: mac, + Cfg: cfg, + apiClient: apis.NewMedia(&opts), } } @@ -50,13 +64,15 @@ type PfopRet struct { // PrefopRet 为数据处理请求的状态查询回复内容 type PrefopRet struct { - ID string `json:"id"` - Code int `json:"code"` - Desc string `json:"desc"` - InputBucket string `json:"inputBucket,omitempty"` - InputKey string `json:"inputKey,omitempty"` - Pipeline string `json:"pipeline,omitempty"` - Reqid string `json:"reqid,omitempty"` + ID string `json:"id"` + Code int `json:"code"` + Desc string `json:"desc"` + Type int64 `json:"type,omitempty"` + InputBucket string `json:"inputBucket,omitempty"` + InputKey string `json:"inputKey,omitempty"` + Pipeline string `json:"pipeline,omitempty"` + Reqid string `json:"reqid,omitempty"` + CreatedAt time.Time `json:"creationDate,omitempty"` Items []FopResult } @@ -71,9 +87,15 @@ func (r *PrefopRet) String() string { if r.Pipeline != "" { strData += fmt.Sprintf("Pipeline: %s\n", r.Pipeline) } + if r.Type != 0 { + strData += fmt.Sprintf("Type: %d\n", r.Type) + } if r.Reqid != "" { strData += fmt.Sprintf("Reqid: %s\n", r.Reqid) } + if !r.CreatedAt.IsZero() { + strData += fmt.Sprintf("CreatedAt: %s\n", r.CreatedAt) + } strData = fmt.Sprintln(strData) for _, item := range r.Items { @@ -102,6 +124,16 @@ func (r *PrefopRet) String() string { return strData } +type PfopRequest struct { + BucketName string // 空间名称 + ObjectName string // 对象名称 + Fops string // 数据处理命令列表,以 `;` 分隔,可以指定多个数据处理命令,与 `workflowTemplateID` 二选一 + NotifyUrl string // 处理结果通知接收 URL + Force int64 // 强制执行数据处理,设为 `1`,则可强制执行数据处理并覆盖原结果 + Type int64 // 任务类型,支持 `0` 表示普通任务,`1` 表示闲时任务 + Pipeline string // 对列名,仅适用于普通任务 +} + // FopResult 云处理操作列表,包含每个云处理操作的状态信息 type FopResult struct { Cmd string `json:"cmd"` @@ -122,54 +154,80 @@ type FopResult struct { // pipeline 多媒体处理队列名称 // force 强制执行数据处理 func (m *OperationManager) Pfop(bucket, key, fops, pipeline, notifyURL string, - force bool) (persistentID string, err error) { - pfopParams := map[string][]string{ - "bucket": {bucket}, - "key": {key}, - "fops": {fops}, - } - - if pipeline != "" { - pfopParams["pipeline"] = []string{pipeline} + force bool) (string, error) { + var forceNumber int64 + if force { + forceNumber = 1 } - - if notifyURL != "" { - pfopParams["notifyURL"] = []string{notifyURL} + response, err := m.apiClient.Pfop(context.Background(), &apis.PfopRequest{ + BucketName: bucket, + ObjectName: key, + Fops: fops, + NotifyUrl: notifyURL, + Force: forceNumber, + Pipeline: pipeline, + }, nil) + if err != nil { + return "", err } + return response.PersistentId, nil +} - if force { - pfopParams["force"] = []string{"1"} - } - var ret PfopRet - ctx := auth.WithCredentialsType(context.TODO(), m.Mac, auth.TokenQiniu) - reqHost, reqErr := m.ApiHost(bucket) - if reqErr != nil { - err = reqErr - return - } - reqURL := fmt.Sprintf("%s/pfop/", reqHost) - headers := http.Header{} - headers.Add("Content-Type", conf.CONTENT_TYPE_FORM) - err = m.Client.CallWithForm(ctx, &ret, "POST", reqURL, headers, pfopParams) +// Pfop 持久化数据处理 v2 +func (m *OperationManager) PfopV2(ctx context.Context, pfopRequest *PfopRequest) (*PfopRet, error) { + response, err := m.apiClient.Pfop(context.Background(), &apis.PfopRequest{ + BucketName: pfopRequest.BucketName, + ObjectName: pfopRequest.ObjectName, + Fops: pfopRequest.Fops, + NotifyUrl: pfopRequest.NotifyUrl, + Force: pfopRequest.Force, + Type: pfopRequest.Type, + Pipeline: pfopRequest.Pipeline, + }, nil) if err != nil { - return + return nil, err } - - persistentID = ret.PersistentID - return + return &PfopRet{PersistentID: response.PersistentId}, nil } // Prefop 持久化处理状态查询 -func (m *OperationManager) Prefop(persistentID string) (ret PrefopRet, err error) { - reqHost := m.PrefopApiHost(persistentID) - reqURL := fmt.Sprintf("%s/status/get/prefop?id=%s", reqHost, persistentID) - headers := http.Header{} - headers.Add("Content-Type", conf.CONTENT_TYPE_FORM) - ctx := auth.WithCredentialsType(context.TODO(), m.Mac, auth.TokenQiniu) - err = m.Client.Call(ctx, &ret, "GET", reqURL, headers) - return +func (m *OperationManager) Prefop(persistentID string) (PrefopRet, error) { + response, err := m.apiClient.Prefop(context.Background(), &apis.PrefopRequest{ + PersistentId: persistentID, + }, nil) + if err != nil { + return PrefopRet{}, err + } + createdAt, err := time.Parse(time.RFC3339, response.CreatedAt) + if err != nil { + return PrefopRet{}, err + } + ret := PrefopRet{ + ID: response.PersistentId, + Code: int(response.Code), + Desc: response.Description, + Type: response.Type, + InputBucket: response.BucketName, + InputKey: response.ObjectName, + Pipeline: response.Pipeline, + Reqid: response.RequestId, + CreatedAt: createdAt, + Items: make([]FopResult, 0, len(response.Items)), + } + for _, item := range response.Items { + ret.Items = append(ret.Items, FopResult{ + Cmd: item.Command, + Code: int(item.Code), + Desc: item.Description, + Error: item.Error, + Hash: item.Hash, + Key: item.ObjectName, + }) + } + return ret, nil } +// Deprecated func (m *OperationManager) ApiHost(bucket string) (apiHost string, err error) { var zone *Zone if m.Cfg.Zone != nil { @@ -191,6 +249,7 @@ func (m *OperationManager) ApiHost(bucket string) (apiHost string, err error) { return } +// Deprecated func (m *OperationManager) PrefopApiHost(persistentID string) (apiHost string) { apiHost = "api.qiniu.com" if m.Cfg.Zone != nil { diff --git a/storage/token.go b/storage/token.go index 0afef1b5..2c047dfe 100644 --- a/storage/token.go +++ b/storage/token.go @@ -75,6 +75,9 @@ type PutPolicy struct { // 转码队列名。资源上传成功后,触发转码时指定独立的队列进行转码。为空则表示使用公用队列,处理速度比较慢。建议使用专用队列。 PersistentPipeline string `json:"persistentPipeline,omitempty"` + // 任务类型。0: 普通任务,1: 闲时任务 + PersistentType int64 `json:"persistentType,omitempty"` + // saveKey 的优先级设置。为 true 时,saveKey不能为空,会忽略客户端指定的key,强制使用saveKey进行文件命名。参数不设置时, // 默认值为false ForceSaveKey bool `json:"forceSaveKey,omitempty"` // diff --git a/storage/upload_manager_uplog_test.go b/storage/upload_manager_uplog_test.go index eea2a7fb..e9177a28 100644 --- a/storage/upload_manager_uplog_test.go +++ b/storage/upload_manager_uplog_test.go @@ -87,111 +87,107 @@ func TestUploadManagerUplogForm(t *testing.T) { } uplogs = append(uplogs, uplog) } - if len(uplogs) != 10 { + if len(uplogs) != 4 { t.Fatalf("unexpected uplog count:%v", len(uplogs)) } - for i := 0; i < 4; i++ { - if uplogs[i]["log_type"] != "request" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[i]["log_type"]) - } - if uplogs[i]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[i]["api_type"]) - } - if uplogs[i]["api_name"] != "postObject" { - t.Fatalf("unexpected uplog api_name:%v", uplogs[i]["api_name"]) - } - if uplogs[i]["error_type"] != "unknown_host" { - t.Fatalf("unexpected uplog error_type:%v", uplogs[i]["error_type"]) - } - if uplogs[i]["host"] != "mock03.qiniu.com" { - t.Fatalf("unexpected uplog host:%v", uplogs[i]["host"]) - } - if uplogs[i]["path"] != "/" { - t.Fatalf("unexpected uplog path:%v", uplogs[i]["path"]) - } - if uplogs[i]["method"] != "POST" { - t.Fatalf("unexpected uplog method:%v", uplogs[i]["method"]) - } - if uplogs[i]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[i]["target_bucket"]) - } + if uplogs[0]["log_type"] != "request" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[0]["log_type"]) } - for i := 4; i < 8; i++ { - if uplogs[i]["log_type"] != "request" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[i]["log_type"]) - } - if uplogs[i]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[i]["api_type"]) - } - if uplogs[i]["api_name"] != "postObject" { - t.Fatalf("unexpected uplog api_name:%v", uplogs[i]["api_name"]) - } - if uplogs[i]["error_type"] != "unknown_host" { - t.Fatalf("unexpected uplog error_type:%v", uplogs[i]["error_type"]) - } - if uplogs[i]["host"] != "mock04.qiniu.com" { - t.Fatalf("unexpected uplog host:%v", uplogs[i]["host"]) - } - if uplogs[i]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[i]["target_bucket"]) - } - if uplogs[i]["path"] != "/" { - t.Fatalf("unexpected uplog path:%v", uplogs[i]["path"]) - } - if uplogs[i]["method"] != "POST" { - t.Fatalf("unexpected uplog method:%v", uplogs[i]["method"]) - } + if uplogs[0]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[0]["api_type"]) } - if uplogs[8]["log_type"] != "request" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[8]["log_type"]) + if uplogs[0]["api_name"] != "postObject" { + t.Fatalf("unexpected uplog api_name:%v", uplogs[0]["api_name"]) } - if uplogs[8]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[8]["api_type"]) + if uplogs[0]["error_type"] != "unknown_host" { + t.Fatalf("unexpected uplog error_type:%v", uplogs[0]["error_type"]) } - if uplogs[8]["api_name"] != "postObject" { - t.Fatalf("unexpected uplog api_name:%v", uplogs[8]["api_name"]) + if uplogs[0]["host"] != "mock03.qiniu.com" { + t.Fatalf("unexpected uplog host:%v", uplogs[0]["host"]) } - if uplogs[8]["error_type"] != nil { - t.Fatalf("unexpected uplog error_type:%v", uplogs[8]["error_type"]) + if uplogs[0]["path"] != "/" { + t.Fatalf("unexpected uplog path:%v", uplogs[0]["path"]) } - if uplogs[8]["port"] != float64(443) { - t.Fatalf("unexpected uplog port:%v", uplogs[8]["port"]) + if uplogs[0]["method"] != "POST" { + t.Fatalf("unexpected uplog method:%v", uplogs[0]["method"]) } - if uplogs[8]["remote_ip"] == nil { - t.Fatalf("unexpected uplog remote_ip:%v", uplogs[8]["remote_ip"]) + if uplogs[0]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[0]["target_bucket"]) } - if uplogs[8]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[8]["target_bucket"]) + if uplogs[1]["log_type"] != "request" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[1]["log_type"]) } - if uplogs[8]["path"] != "/" { - t.Fatalf("unexpected uplog path:%v", uplogs[8]["path"]) + if uplogs[1]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[1]["api_type"]) } - if uplogs[8]["method"] != "POST" { - t.Fatalf("unexpected uplog method:%v", uplogs[8]["method"]) + if uplogs[1]["api_name"] != "postObject" { + t.Fatalf("unexpected uplog api_name:%v", uplogs[1]["api_name"]) } - if uplogs[8]["status_code"] != float64(200) { - t.Fatalf("unexpected uplog status_code:%v", uplogs[8]["status_code"]) + if uplogs[1]["error_type"] != "unknown_host" { + t.Fatalf("unexpected uplog error_type:%v", uplogs[1]["error_type"]) } - if uplogs[9]["log_type"] != "quality" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[9]["log_type"]) + if uplogs[1]["host"] != "mock04.qiniu.com" { + t.Fatalf("unexpected uplog host:%v", uplogs[1]["host"]) } - if uplogs[9]["result"] != "ok" { - t.Fatalf("unexpected uplog result:%v", uplogs[9]["result"]) + if uplogs[1]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[1]["target_bucket"]) } - if uplogs[9]["up_type"] != "form" { - t.Fatalf("unexpected uplog up_type:%v", uplogs[9]["up_type"]) + if uplogs[1]["path"] != "/" { + t.Fatalf("unexpected uplog path:%v", uplogs[1]["path"]) } - if uplogs[9]["regions_count"] != float64(2) { - t.Fatalf("unexpected uplog regions_count:%v", uplogs[9]["regions_count"]) + if uplogs[1]["method"] != "POST" { + t.Fatalf("unexpected uplog method:%v", uplogs[1]["method"]) } - if uplogs[9]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[9]["api_type"]) + if uplogs[2]["log_type"] != "request" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[2]["log_type"]) } - if uplogs[9]["file_size"] != float64(dataLen) { - t.Fatalf("unexpected uplog file_size:%v", uplogs[9]["file_size"]) + if uplogs[2]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[2]["api_type"]) } - if uplogs[9]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[9]["target_bucket"]) + if uplogs[2]["api_name"] != "postObject" { + t.Fatalf("unexpected uplog api_name:%v", uplogs[2]["api_name"]) + } + if uplogs[2]["error_type"] != nil { + t.Fatalf("unexpected uplog error_type:%v", uplogs[2]["error_type"]) + } + if uplogs[2]["port"] != float64(443) { + t.Fatalf("unexpected uplog port:%v", uplogs[2]["port"]) + } + if uplogs[2]["remote_ip"] == nil { + t.Fatalf("unexpected uplog remote_ip:%v", uplogs[2]["remote_ip"]) + } + if uplogs[2]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[2]["target_bucket"]) + } + if uplogs[2]["path"] != "/" { + t.Fatalf("unexpected uplog path:%v", uplogs[2]["path"]) + } + if uplogs[2]["method"] != "POST" { + t.Fatalf("unexpected uplog method:%v", uplogs[2]["method"]) + } + if uplogs[2]["status_code"] != float64(200) { + t.Fatalf("unexpected uplog status_code:%v", uplogs[2]["status_code"]) + } + if uplogs[3]["log_type"] != "quality" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[3]["log_type"]) + } + if uplogs[3]["result"] != "ok" { + t.Fatalf("unexpected uplog result:%v", uplogs[3]["result"]) + } + if uplogs[3]["up_type"] != "form" { + t.Fatalf("unexpected uplog up_type:%v", uplogs[3]["up_type"]) + } + if uplogs[3]["regions_count"] != float64(2) { + t.Fatalf("unexpected uplog regions_count:%v", uplogs[3]["regions_count"]) + } + if uplogs[3]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[3]["api_type"]) + } + if uplogs[3]["file_size"] != float64(dataLen) { + t.Fatalf("unexpected uplog file_size:%v", uplogs[3]["file_size"]) + } + if uplogs[3]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[3]["target_bucket"]) } } @@ -270,116 +266,112 @@ func TestUploadManagerUplogResumableV1(t *testing.T) { } uplogs = append(uplogs, uplog) } - if len(uplogs) != 12 { + if len(uplogs) != 10 { t.Fatalf("unexpected uplog count:%v", len(uplogs)) } - for i := 0; i < 2; i++ { - if uplogs[i]["log_type"] != "request" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[i]["log_type"]) - } - if uplogs[i]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[i]["api_type"]) - } - if uplogs[i]["api_name"] != "resumableUploadV1MakeBlock" { - t.Fatalf("unexpected uplog api_name:%v", uplogs[i]["api_name"]) - } - if uplogs[i]["error_type"] != "unknown_host" { - t.Fatalf("unexpected uplog error_type:%v", uplogs[i]["error_type"]) - } - if uplogs[i]["host"] != "mock05.qiniu.com" { - t.Fatalf("unexpected uplog host:%v", uplogs[i]["host"]) - } - if uplogs[i]["path"] != "/mkblk/4194304" { - t.Fatalf("unexpected uplog path:%v", uplogs[i]["path"]) - } - if uplogs[i]["method"] != "POST" { - t.Fatalf("unexpected uplog method:%v", uplogs[i]["method"]) - } - if uplogs[i]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[i]["target_bucket"]) - } + if uplogs[0]["log_type"] != "request" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[0]["log_type"]) } - for i := 2; i < 4; i++ { - if uplogs[i]["log_type"] != "request" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[i]["log_type"]) - } - if uplogs[i]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[i]["api_type"]) - } - if uplogs[i]["api_name"] != "resumableUploadV1MakeBlock" { - t.Fatalf("unexpected uplog api_name:%v", uplogs[i]["api_name"]) - } - if uplogs[i]["error_type"] != "unknown_host" { - t.Fatalf("unexpected uplog error_type:%v", uplogs[i]["error_type"]) - } - if uplogs[i]["host"] != "mock06.qiniu.com" { - t.Fatalf("unexpected uplog host:%v", uplogs[i]["host"]) - } - if uplogs[i]["path"] != "/mkblk/4194304" { - t.Fatalf("unexpected uplog path:%v", uplogs[i]["path"]) - } - if uplogs[i]["method"] != "POST" { - t.Fatalf("unexpected uplog method:%v", uplogs[i]["method"]) - } - if uplogs[i]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[i]["target_bucket"]) - } + if uplogs[0]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[0]["api_type"]) } - if uplogs[4]["log_type"] != "block" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[4]["log_type"]) + if uplogs[0]["api_name"] != "resumableUploadV1MakeBlock" { + t.Fatalf("unexpected uplog api_name:%v", uplogs[0]["api_name"]) } - if uplogs[4]["up_api_version"] != float64(1) { - t.Fatalf("unexpected uplog up_api_version:%v", uplogs[4]["up_api_version"]) + if uplogs[0]["error_type"] != "unknown_host" { + t.Fatalf("unexpected uplog error_type:%v", uplogs[0]["error_type"]) } - if uplogs[4]["requests_count"] != float64(4) { - t.Fatalf("unexpected uplog requests_count:%v", uplogs[4]["requests_count"]) + if uplogs[0]["host"] != "mock05.qiniu.com" { + t.Fatalf("unexpected uplog host:%v", uplogs[0]["host"]) } - if uplogs[4]["error_type"] != "unknown_host" { - t.Fatalf("unexpected uplog error_type:%v", uplogs[4]["error_type"]) + if uplogs[0]["path"] != "/mkblk/4194304" { + t.Fatalf("unexpected uplog path:%v", uplogs[0]["path"]) } - if uplogs[4]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[4]["api_type"]) + if uplogs[0]["method"] != "POST" { + t.Fatalf("unexpected uplog method:%v", uplogs[0]["method"]) } - if uplogs[4]["file_size"] != float64(length) { - t.Fatalf("unexpected uplog file_size:%v", uplogs[4]["file_size"]) + if uplogs[0]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[0]["target_bucket"]) } - if uplogs[4]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[4]["target_bucket"]) + if uplogs[1]["log_type"] != "request" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[1]["log_type"]) } - if uplogs[5]["log_type"] != "request" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[5]["log_type"]) + if uplogs[1]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[1]["api_type"]) } - if uplogs[5]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[5]["api_type"]) + if uplogs[1]["api_name"] != "resumableUploadV1MakeBlock" { + t.Fatalf("unexpected uplog api_name:%v", uplogs[1]["api_name"]) } - if uplogs[5]["api_name"] != "resumableUploadV1MakeBlock" { - t.Fatalf("unexpected uplog api_name:%v", uplogs[5]["api_name"]) + if uplogs[1]["error_type"] != "unknown_host" { + t.Fatalf("unexpected uplog error_type:%v", uplogs[1]["error_type"]) } - if uplogs[5]["error_type"] != nil { - t.Fatalf("unexpected uplog error_type:%v", uplogs[5]["error_type"]) + if uplogs[1]["host"] != "mock06.qiniu.com" { + t.Fatalf("unexpected uplog host:%v", uplogs[1]["host"]) } - if uplogs[5]["port"] != float64(443) { - t.Fatalf("unexpected uplog port:%v", uplogs[5]["port"]) + if uplogs[1]["path"] != "/mkblk/4194304" { + t.Fatalf("unexpected uplog path:%v", uplogs[1]["path"]) } - if uplogs[5]["remote_ip"] == nil { - t.Fatalf("unexpected uplog remote_ip:%v", uplogs[5]["remote_ip"]) + if uplogs[1]["method"] != "POST" { + t.Fatalf("unexpected uplog method:%v", uplogs[1]["method"]) } - if uplogs[5]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[5]["target_bucket"]) + if uplogs[1]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[1]["target_bucket"]) } - if uplogs[5]["path"] != "/mkblk/4194304" { - t.Fatalf("unexpected uplog path:%v", uplogs[5]["path"]) + if uplogs[2]["log_type"] != "block" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[2]["log_type"]) } - if uplogs[5]["method"] != "POST" { - t.Fatalf("unexpected uplog method:%v", uplogs[5]["method"]) + if uplogs[2]["up_api_version"] != float64(1) { + t.Fatalf("unexpected uplog up_api_version:%v", uplogs[2]["up_api_version"]) } - if uplogs[5]["status_code"] != float64(200) { - t.Fatalf("unexpected uplog status_code:%v", uplogs[5]["status_code"]) + if uplogs[2]["requests_count"] != float64(2) { + t.Fatalf("unexpected uplog requests_count:%v", uplogs[2]["requests_count"]) } - if uplogs[5]["bytes_sent"] != float64(1024*1024) { - t.Fatalf("unexpected uplog bytes_sent:%v", uplogs[5]["bytes_sent"]) + if uplogs[2]["error_type"] != "unknown_host" { + t.Fatalf("unexpected uplog error_type:%v", uplogs[2]["error_type"]) } - for i := 6; i < 9; i++ { + if uplogs[2]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[2]["api_type"]) + } + if uplogs[2]["file_size"] != float64(length) { + t.Fatalf("unexpected uplog file_size:%v", uplogs[2]["file_size"]) + } + if uplogs[2]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[2]["target_bucket"]) + } + if uplogs[3]["log_type"] != "request" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[3]["log_type"]) + } + if uplogs[3]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[3]["api_type"]) + } + if uplogs[3]["api_name"] != "resumableUploadV1MakeBlock" { + t.Fatalf("unexpected uplog api_name:%v", uplogs[3]["api_name"]) + } + if uplogs[3]["error_type"] != nil { + t.Fatalf("unexpected uplog error_type:%v", uplogs[3]["error_type"]) + } + if uplogs[3]["port"] != float64(443) { + t.Fatalf("unexpected uplog port:%v", uplogs[3]["port"]) + } + if uplogs[3]["remote_ip"] == nil { + t.Fatalf("unexpected uplog remote_ip:%v", uplogs[3]["remote_ip"]) + } + if uplogs[3]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[3]["target_bucket"]) + } + if uplogs[3]["path"] != "/mkblk/4194304" { + t.Fatalf("unexpected uplog path:%v", uplogs[3]["path"]) + } + if uplogs[3]["method"] != "POST" { + t.Fatalf("unexpected uplog method:%v", uplogs[3]["method"]) + } + if uplogs[3]["status_code"] != float64(200) { + t.Fatalf("unexpected uplog status_code:%v", uplogs[3]["status_code"]) + } + if uplogs[3]["bytes_sent"] != float64(1024*1024) { + t.Fatalf("unexpected uplog bytes_sent:%v", uplogs[3]["bytes_sent"]) + } + for i := 4; i < 7; i++ { if uplogs[i]["log_type"] != "request" { t.Fatalf("unexpected uplog log_type:%v", uplogs[i]["log_type"]) } @@ -414,76 +406,76 @@ func TestUploadManagerUplogResumableV1(t *testing.T) { t.Fatalf("unexpected uplog bytes_sent:%v", uplogs[i]["bytes_sent"]) } } - if uplogs[9]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[9]["api_type"]) + if uplogs[7]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[7]["api_type"]) } - if uplogs[9]["api_name"] != "resumableUploadV1MakeFile" { - t.Fatalf("unexpected uplog api_name:%v", uplogs[9]["api_name"]) + if uplogs[7]["api_name"] != "resumableUploadV1MakeFile" { + t.Fatalf("unexpected uplog api_name:%v", uplogs[7]["api_name"]) } - if uplogs[9]["error_type"] != nil { - t.Fatalf("unexpected uplog error_type:%v", uplogs[9]["error_type"]) + if uplogs[7]["error_type"] != nil { + t.Fatalf("unexpected uplog error_type:%v", uplogs[7]["error_type"]) } - if uplogs[9]["port"] != float64(443) { - t.Fatalf("unexpected uplog port:%v", uplogs[9]["port"]) + if uplogs[7]["port"] != float64(443) { + t.Fatalf("unexpected uplog port:%v", uplogs[7]["port"]) } - if uplogs[9]["remote_ip"] == nil { - t.Fatalf("unexpected uplog remote_ip:%v", uplogs[9]["remote_ip"]) + if uplogs[7]["remote_ip"] == nil { + t.Fatalf("unexpected uplog remote_ip:%v", uplogs[7]["remote_ip"]) } - if uplogs[9]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[9]["target_bucket"]) + if uplogs[7]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[7]["target_bucket"]) } - if uplogs[9]["path"] != "/mkfile/4194304" { - t.Fatalf("unexpected uplog path:%v", uplogs[9]["path"]) + if uplogs[7]["path"] != "/mkfile/4194304" { + t.Fatalf("unexpected uplog path:%v", uplogs[7]["path"]) } - if uplogs[9]["method"] != "POST" { - t.Fatalf("unexpected uplog method:%v", uplogs[9]["method"]) + if uplogs[7]["method"] != "POST" { + t.Fatalf("unexpected uplog method:%v", uplogs[7]["method"]) } - if uplogs[9]["status_code"] != float64(200) { - t.Fatalf("unexpected uplog status_code:%v", uplogs[9]["status_code"]) + if uplogs[7]["status_code"] != float64(200) { + t.Fatalf("unexpected uplog status_code:%v", uplogs[7]["status_code"]) } - if uplogs[10]["log_type"] != "block" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[10]["log_type"]) + if uplogs[8]["log_type"] != "block" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[8]["log_type"]) } - if uplogs[10]["up_api_version"] != float64(1) { - t.Fatalf("unexpected uplog up_api_version:%v", uplogs[10]["up_api_version"]) + if uplogs[8]["up_api_version"] != float64(1) { + t.Fatalf("unexpected uplog up_api_version:%v", uplogs[8]["up_api_version"]) } - if uplogs[10]["requests_count"] != float64(5) { - t.Fatalf("unexpected uplog requests_count:%v", uplogs[10]["requests_count"]) + if uplogs[8]["requests_count"] != float64(5) { + t.Fatalf("unexpected uplog requests_count:%v", uplogs[8]["requests_count"]) } - if uplogs[10]["error_type"] != nil { - t.Fatalf("unexpected uplog error_type:%v", uplogs[10]["error_type"]) + if uplogs[8]["error_type"] != nil { + t.Fatalf("unexpected uplog error_type:%v", uplogs[8]["error_type"]) } - if uplogs[10]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[10]["api_type"]) + if uplogs[8]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[8]["api_type"]) } - if uplogs[10]["file_size"] != float64(length) { - t.Fatalf("unexpected uplog file_size:%v", uplogs[10]["file_size"]) + if uplogs[8]["file_size"] != float64(length) { + t.Fatalf("unexpected uplog file_size:%v", uplogs[8]["file_size"]) } - if uplogs[10]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[10]["target_bucket"]) + if uplogs[8]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[8]["target_bucket"]) } - if uplogs[11]["log_type"] != "quality" { - t.Fatalf("unexpected uplog log_type:%v", uplogs[11]["log_type"]) + if uplogs[9]["log_type"] != "quality" { + t.Fatalf("unexpected uplog log_type:%v", uplogs[9]["log_type"]) } - if uplogs[11]["requests_count"] != float64(9) { - t.Fatalf("unexpected uplog requests_count:%v", uplogs[11]["requests_count"]) + if uplogs[9]["requests_count"] != float64(7) { + t.Fatalf("unexpected uplog requests_count:%v", uplogs[9]["requests_count"]) } - if uplogs[11]["result"] != "ok" { - t.Fatalf("unexpected uplog result:%v", uplogs[11]["result"]) + if uplogs[9]["result"] != "ok" { + t.Fatalf("unexpected uplog result:%v", uplogs[9]["result"]) } - if uplogs[11]["up_type"] != "resumable_v1" { - t.Fatalf("unexpected uplog up_type:%v", uplogs[11]["up_type"]) + if uplogs[9]["up_type"] != "resumable_v1" { + t.Fatalf("unexpected uplog up_type:%v", uplogs[9]["up_type"]) } - if uplogs[11]["regions_count"] != float64(2) { - t.Fatalf("unexpected uplog regions_count:%v", uplogs[11]["regions_count"]) + if uplogs[9]["regions_count"] != float64(2) { + t.Fatalf("unexpected uplog regions_count:%v", uplogs[9]["regions_count"]) } - if uplogs[11]["api_type"] != "kodo" { - t.Fatalf("unexpected uplog api_type:%v", uplogs[11]["api_type"]) + if uplogs[9]["api_type"] != "kodo" { + t.Fatalf("unexpected uplog api_type:%v", uplogs[9]["api_type"]) } - if uplogs[11]["file_size"] != float64(length) { - t.Fatalf("unexpected uplog file_size:%v", uplogs[11]["file_size"]) + if uplogs[9]["file_size"] != float64(length) { + t.Fatalf("unexpected uplog file_size:%v", uplogs[9]["file_size"]) } - if uplogs[11]["target_bucket"] != testBucket { - t.Fatalf("unexpected uplog target_bucket:%v", uplogs[11]["target_bucket"]) + if uplogs[9]["target_bucket"] != testBucket { + t.Fatalf("unexpected uplog target_bucket:%v", uplogs[9]["target_bucket"]) } } diff --git a/storagev2/apis/api_add_bucket_event_rule.go b/storagev2/apis/api_add_bucket_event_rule.go index 99de5faf..c17b0dcc 100644 --- a/storagev2/apis/api_add_bucket_event_rule.go +++ b/storagev2/apis/api_add_bucket_event_rule.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" addbucketeventrule "github.com/qiniu/go-sdk/v7/storagev2/apis/add_bucket_event_rule" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -61,16 +61,6 @@ func (query *innerAddBucketEventRuleRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerAddBucketEventRuleRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type AddBucketEventRuleRequest = addbucketeventrule.Request type AddBucketEventRuleResponse = addbucketeventrule.Response @@ -85,7 +75,7 @@ func (storage *Storage) AddBucketEventRule(ctx context.Context, request *AddBuck if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "events", "add") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -101,8 +91,7 @@ func (storage *Storage) AddBucketEventRule(ctx context.Context, request *AddBuck return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("addBucketEventRule", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("addBucketEventRule", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -118,33 +107,11 @@ func (storage *Storage) AddBucketEventRule(ctx context.Context, request *AddBuck } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_add_bucket_rules.go b/storagev2/apis/api_add_bucket_rules.go index 843869d3..7f6f50f1 100644 --- a/storagev2/apis/api_add_bucket_rules.go +++ b/storagev2/apis/api_add_bucket_rules.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" addbucketrules "github.com/qiniu/go-sdk/v7/storagev2/apis/add_bucket_rules" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -42,16 +42,6 @@ func (form *innerAddBucketRulesRequest) build() (url.Values, error) { formValues.Set("to_archive_ir_after_days", strconv.FormatInt(form.ToArchiveIrAfterDays, 10)) return formValues, nil } -func (request *innerAddBucketRulesRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type AddBucketRulesRequest = addbucketrules.Request type AddBucketRulesResponse = addbucketrules.Response @@ -66,7 +56,7 @@ func (storage *Storage) AddBucketRules(ctx context.Context, request *AddBucketRu if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "rules", "add") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -81,8 +71,7 @@ func (storage *Storage) AddBucketRules(ctx context.Context, request *AddBucketRu return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("addBucketRules", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("addBucketRules", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -98,33 +87,11 @@ func (storage *Storage) AddBucketRules(ctx context.Context, request *AddBucketRu } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: httpclient.GetFormRequestBody(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_async_fetch_object.go b/storagev2/apis/api_async_fetch_object.go index 15e07401..5b93370c 100644 --- a/storagev2/apis/api_async_fetch_object.go +++ b/storagev2/apis/api_async_fetch_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/json" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" asyncfetchobject "github.com/qiniu/go-sdk/v7/storagev2/apis/async_fetch_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -54,7 +54,7 @@ func (storage *Storage) AsyncFetchObject(ctx context.Context, request *AsyncFetc if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "sisyphus", "fetch") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -86,40 +86,64 @@ func (storage *Storage) AsyncFetchObject(ctx context.Context, request *AsyncFetc } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } + } + } + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { + } else { + + req.Region = storage.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { return nil, err - } else if creds != nil { - accessKey = creds.AccessKey } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeSign: storage.client.GetBeforeSignCallback(), AfterSign: storage.client.GetAfterSignCallback(), SignError: storage.client.GetSignErrorCallback(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } } } } diff --git a/storagev2/apis/api_batch_ops.go b/storagev2/apis/api_batch_ops.go index e08882b3..26f57871 100644 --- a/storagev2/apis/api_batch_ops.go +++ b/storagev2/apis/api_batch_ops.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" batchops "github.com/qiniu/go-sdk/v7/storagev2/apis/batch_ops" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -53,7 +53,7 @@ func (storage *Storage) BatchOps(ctx context.Context, request *BatchOpsRequest, if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "batch") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -62,8 +62,7 @@ func (storage *Storage) BatchOps(ctx context.Context, request *BatchOpsRequest, return nil, err } bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("batchOps", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("batchOps", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -79,40 +78,42 @@ func (storage *Storage) BatchOps(ctx context.Context, request *BatchOpsRequest, } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: httpclient.GetFormRequestBody(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_check_share.go b/storagev2/apis/api_check_share.go new file mode 100644 index 00000000..615ea14d --- /dev/null +++ b/storagev2/apis/api_check_share.go @@ -0,0 +1,161 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + checkshare "github.com/qiniu/go-sdk/v7/storagev2/apis/check_share" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strings" + "time" +) + +type innerCheckShareRequest checkshare.Request + +func (path *innerCheckShareRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.ShareId != "" { + allSegments = append(allSegments, path.ShareId) + } else { + return nil, errors.MissingRequiredFieldError{Name: "ShareId"} + } + return allSegments, nil +} +func (query *innerCheckShareRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Token != "" { + allQuery.Set("token", query.Token) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Token"} + } + return allQuery, nil +} +func (request *innerCheckShareRequest) getAccessKey(ctx context.Context) (string, error) { + if request.Credentials != nil { + if credentials, err := request.Credentials.Get(ctx); err != nil { + return "", err + } else { + return credentials.AccessKey, nil + } + } + return "", nil +} + +type CheckShareRequest = checkshare.Request +type CheckShareResponse = checkshare.Response + +// 检查目录分享 +func (storage *Storage) CheckShare(ctx context.Context, request *CheckShareRequest, options *Options) (*CheckShareResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerCheckShareRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "shares") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "check") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + bucketName := options.OverwrittenBucketName + uplogInterceptor, err := uplog.NewRequestUplog("checkShare", bucketName, "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy(bucketName, time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { + return nil, err + } + } + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } + } + } + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } + } + } else { + + req.Region = storage.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeSign: storage.client.GetBeforeSignCallback(), AfterSign: storage.client.GetAfterSignCallback(), SignError: storage.client.GetSignErrorCallback(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + } + resp, err := storage.client.Do(ctx, &req) + if err != nil { + return nil, err + } + return &CheckShareResponse{}, resp.Body.Close() +} diff --git a/storagev2/apis/api_copy_object.go b/storagev2/apis/api_copy_object.go index 4d48eafa..d2374dd6 100644 --- a/storagev2/apis/api_copy_object.go +++ b/storagev2/apis/api_copy_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" copyobject "github.com/qiniu/go-sdk/v7/storagev2/apis/copy_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -30,7 +30,7 @@ func (pp *innerCopyObjectRequest) getObjectName() string { return "" } func (path *innerCopyObjectRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 4) if path.SrcEntry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.SrcEntry))) } else { @@ -70,7 +70,7 @@ func (storage *Storage) CopyObject(ctx context.Context, request *CopyObjectReque if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 5) pathSegments = append(pathSegments, "copy") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -103,40 +103,42 @@ func (storage *Storage) CopyObject(ctx context.Context, request *CopyObjectReque } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_create_bucket.go b/storagev2/apis/api_create_bucket.go index 850d4127..3adf30e5 100644 --- a/storagev2/apis/api_create_bucket.go +++ b/storagev2/apis/api_create_bucket.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" createbucket "github.com/qiniu/go-sdk/v7/storagev2/apis/create_bucket" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -18,7 +18,7 @@ import ( type innerCreateBucketRequest createbucket.Request func (path *innerCreateBucketRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 3) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -29,16 +29,6 @@ func (path *innerCreateBucketRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerCreateBucketRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type CreateBucketRequest = createbucket.Request type CreateBucketResponse = createbucket.Response @@ -53,7 +43,7 @@ func (storage *Storage) CreateBucket(ctx context.Context, request *CreateBucketR if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 4) pathSegments = append(pathSegments, "mkbucketv3") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -63,8 +53,7 @@ func (storage *Storage) CreateBucket(ctx context.Context, request *CreateBucketR path := "/" + strings.Join(pathSegments, "/") var rawQuery string bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("createBucket", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("createBucket", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -80,33 +69,11 @@ func (storage *Storage) CreateBucket(ctx context.Context, request *CreateBucketR } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_create_share.go b/storagev2/apis/api_create_share.go new file mode 100644 index 00000000..b9bb1a81 --- /dev/null +++ b/storagev2/apis/api_create_share.go @@ -0,0 +1,143 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + createshare "github.com/qiniu/go-sdk/v7/storagev2/apis/create_share" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "strings" + "time" +) + +type innerCreateShareRequest createshare.Request + +func (j *innerCreateShareRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*createshare.Request)(j)) +} +func (j *innerCreateShareRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*createshare.Request)(j)) +} +func (request *innerCreateShareRequest) getAccessKey(ctx context.Context) (string, error) { + if request.Credentials != nil { + if credentials, err := request.Credentials.Get(ctx); err != nil { + return "", err + } else { + return credentials.AccessKey, nil + } + } + return "", nil +} + +type CreateShareRequest = createshare.Request +type CreateShareResponse = createshare.Response + +// 创建目录分享 +func (storage *Storage) CreateShare(ctx context.Context, request *CreateShareRequest, options *Options) (*CreateShareResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerCreateShareRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 1) + pathSegments = append(pathSegments, "shares") + path := "/" + strings.Join(pathSegments, "/") + path += "/" + var rawQuery string + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + bucketName := options.OverwrittenBucketName + uplogInterceptor, err := uplog.NewRequestUplog("createShare", bucketName, "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy(bucketName, time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { + return nil, err + } + } + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } + } + } + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } + } + } else { + + req.Region = storage.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeSign: storage.client.GetBeforeSignCallback(), AfterSign: storage.client.GetAfterSignCallback(), SignError: storage.client.GetSignErrorCallback(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + } + var respBody CreateShareResponse + if err := storage.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/storagev2/apis/api_delete_bucket.go b/storagev2/apis/api_delete_bucket.go index 16080a9c..1c1211b7 100644 --- a/storagev2/apis/api_delete_bucket.go +++ b/storagev2/apis/api_delete_bucket.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" deletebucket "github.com/qiniu/go-sdk/v7/storagev2/apis/delete_bucket" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -21,7 +21,7 @@ func (pp *innerDeleteBucketRequest) getBucketName(ctx context.Context) (string, return pp.Bucket, nil } func (path *innerDeleteBucketRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -29,16 +29,6 @@ func (path *innerDeleteBucketRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerDeleteBucketRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type DeleteBucketRequest = deletebucket.Request type DeleteBucketResponse = deletebucket.Response @@ -53,7 +43,7 @@ func (storage *Storage) DeleteBucket(ctx context.Context, request *DeleteBucketR if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "drop") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -69,8 +59,7 @@ func (storage *Storage) DeleteBucket(ctx context.Context, request *DeleteBucketR return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("deleteBucket", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("deleteBucket", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -86,33 +75,11 @@ func (storage *Storage) DeleteBucket(ctx context.Context, request *DeleteBucketR } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_delete_bucket_event_rule.go b/storagev2/apis/api_delete_bucket_event_rule.go index 1b6a9ff6..f5233cd9 100644 --- a/storagev2/apis/api_delete_bucket_event_rule.go +++ b/storagev2/apis/api_delete_bucket_event_rule.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" deletebucketeventrule "github.com/qiniu/go-sdk/v7/storagev2/apis/delete_bucket_event_rule" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -35,16 +35,6 @@ func (query *innerDeleteBucketEventRuleRequest) buildQuery() (url.Values, error) } return allQuery, nil } -func (request *innerDeleteBucketEventRuleRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type DeleteBucketEventRuleRequest = deletebucketeventrule.Request type DeleteBucketEventRuleResponse = deletebucketeventrule.Response @@ -59,7 +49,7 @@ func (storage *Storage) DeleteBucketEventRule(ctx context.Context, request *Dele if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "events", "delete") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -75,8 +65,7 @@ func (storage *Storage) DeleteBucketEventRule(ctx context.Context, request *Dele return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("deleteBucketEventRule", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("deleteBucketEventRule", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -92,33 +81,11 @@ func (storage *Storage) DeleteBucketEventRule(ctx context.Context, request *Dele } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_delete_bucket_rules.go b/storagev2/apis/api_delete_bucket_rules.go index 0836c1f4..2bdddb95 100644 --- a/storagev2/apis/api_delete_bucket_rules.go +++ b/storagev2/apis/api_delete_bucket_rules.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" deletebucketrules "github.com/qiniu/go-sdk/v7/storagev2/apis/delete_bucket_rules" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -35,16 +35,6 @@ func (form *innerDeleteBucketRulesRequest) build() (url.Values, error) { } return formValues, nil } -func (request *innerDeleteBucketRulesRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type DeleteBucketRulesRequest = deletebucketrules.Request type DeleteBucketRulesResponse = deletebucketrules.Response @@ -59,7 +49,7 @@ func (storage *Storage) DeleteBucketRules(ctx context.Context, request *DeleteBu if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "rules", "delete") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -74,8 +64,7 @@ func (storage *Storage) DeleteBucketRules(ctx context.Context, request *DeleteBu return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("deleteBucketRules", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("deleteBucketRules", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -91,33 +80,11 @@ func (storage *Storage) DeleteBucketRules(ctx context.Context, request *DeleteBu } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: httpclient.GetFormRequestBody(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_delete_bucket_taggings.go b/storagev2/apis/api_delete_bucket_taggings.go index b7f23fa8..68af4b25 100644 --- a/storagev2/apis/api_delete_bucket_taggings.go +++ b/storagev2/apis/api_delete_bucket_taggings.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" deletebuckettaggings "github.com/qiniu/go-sdk/v7/storagev2/apis/delete_bucket_taggings" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -30,16 +30,6 @@ func (query *innerDeleteBucketTaggingsRequest) buildQuery() (url.Values, error) } return allQuery, nil } -func (request *innerDeleteBucketTaggingsRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type DeleteBucketTaggingsRequest = deletebuckettaggings.Request type DeleteBucketTaggingsResponse = deletebuckettaggings.Response @@ -54,7 +44,7 @@ func (storage *Storage) DeleteBucketTaggings(ctx context.Context, request *Delet if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "bucketTagging") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -70,8 +60,7 @@ func (storage *Storage) DeleteBucketTaggings(ctx context.Context, request *Delet return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("deleteBucketTaggings", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("deleteBucketTaggings", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -87,33 +76,11 @@ func (storage *Storage) DeleteBucketTaggings(ctx context.Context, request *Delet } req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_delete_object.go b/storagev2/apis/api_delete_object.go index e7eafeef..03755244 100644 --- a/storagev2/apis/api_delete_object.go +++ b/storagev2/apis/api_delete_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" deleteobject "github.com/qiniu/go-sdk/v7/storagev2/apis/delete_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -29,7 +29,7 @@ func (pp *innerDeleteObjectRequest) getObjectName() string { return "" } func (path *innerDeleteObjectRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -61,7 +61,7 @@ func (storage *Storage) DeleteObject(ctx context.Context, request *DeleteObjectR if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "delete") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -94,40 +94,42 @@ func (storage *Storage) DeleteObject(ctx context.Context, request *DeleteObjectR } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_delete_object_after_days.go b/storagev2/apis/api_delete_object_after_days.go index 5446821c..e4c05e8e 100644 --- a/storagev2/apis/api_delete_object_after_days.go +++ b/storagev2/apis/api_delete_object_after_days.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" deleteobjectafterdays "github.com/qiniu/go-sdk/v7/storagev2/apis/delete_object_after_days" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -23,7 +23,7 @@ func (pp *innerDeleteObjectAfterDaysRequest) getBucketName(ctx context.Context) return strings.SplitN(pp.Entry, ":", 2)[0], nil } func (path *innerDeleteObjectAfterDaysRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 2) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -56,7 +56,7 @@ func (storage *Storage) DeleteObjectAfterDays(ctx context.Context, request *Dele if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 3) pathSegments = append(pathSegments, "deleteAfterDays") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -72,8 +72,7 @@ func (storage *Storage) DeleteObjectAfterDays(ctx context.Context, request *Dele return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("deleteObjectAfterDays", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("deleteObjectAfterDays", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -89,40 +88,42 @@ func (storage *Storage) DeleteObjectAfterDays(ctx context.Context, request *Dele } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_disable_bucket_index_page.go b/storagev2/apis/api_disable_bucket_index_page.go index 31a186a8..54ab1c1c 100644 --- a/storagev2/apis/api_disable_bucket_index_page.go +++ b/storagev2/apis/api_disable_bucket_index_page.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" disablebucketindexpage "github.com/qiniu/go-sdk/v7/storagev2/apis/disable_bucket_index_page" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -32,16 +32,6 @@ func (query *innerDisableBucketIndexPageRequest) buildQuery() (url.Values, error allQuery.Set("noIndexPage", strconv.FormatInt(query.NoIndexPage, 10)) return allQuery, nil } -func (request *innerDisableBucketIndexPageRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type DisableBucketIndexPageRequest = disablebucketindexpage.Request type DisableBucketIndexPageResponse = disablebucketindexpage.Response @@ -56,7 +46,7 @@ func (storage *Storage) DisableBucketIndexPage(ctx context.Context, request *Dis if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "noIndexPage") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -72,8 +62,7 @@ func (storage *Storage) DisableBucketIndexPage(ctx context.Context, request *Dis return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("disableBucketIndexPage", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("disableBucketIndexPage", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -89,33 +78,11 @@ func (storage *Storage) DisableBucketIndexPage(ctx context.Context, request *Dis } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_fetch_object.go b/storagev2/apis/api_fetch_object.go index eb05b80c..f53e320e 100644 --- a/storagev2/apis/api_fetch_object.go +++ b/storagev2/apis/api_fetch_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" fetchobject "github.com/qiniu/go-sdk/v7/storagev2/apis/fetch_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -29,7 +29,7 @@ func (pp *innerFetchObjectRequest) getObjectName() string { return "" } func (path *innerFetchObjectRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.FromUrl != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.FromUrl))) } else { @@ -69,7 +69,7 @@ func (storage *Storage) FetchObject(ctx context.Context, request *FetchObjectReq if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "fetch") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -102,40 +102,42 @@ func (storage *Storage) FetchObject(ctx context.Context, request *FetchObjectReq } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_get_async_fetch_task.go b/storagev2/apis/api_get_async_fetch_task.go index a5ab7e72..84ffdf2d 100644 --- a/storagev2/apis/api_get_async_fetch_task.go +++ b/storagev2/apis/api_get_async_fetch_task.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getasyncfetchtask "github.com/qiniu/go-sdk/v7/storagev2/apis/get_async_fetch_task" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -51,7 +51,7 @@ func (storage *Storage) GetAsyncFetchTask(ctx context.Context, request *GetAsync if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "sisyphus", "fetch") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -61,8 +61,7 @@ func (storage *Storage) GetAsyncFetchTask(ctx context.Context, request *GetAsync rawQuery += query.Encode() } bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getAsyncFetchTask", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getAsyncFetchTask", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -78,40 +77,64 @@ func (storage *Storage) GetAsyncFetchTask(ctx context.Context, request *GetAsync } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } + } + } + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { + } else { + + req.Region = storage.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { return nil, err - } else if creds != nil { - accessKey = creds.AccessKey } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeSign: storage.client.GetBeforeSignCallback(), AfterSign: storage.client.GetAfterSignCallback(), SignError: storage.client.GetSignErrorCallback(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } } } } diff --git a/storagev2/apis/api_get_bucket_cors_rules.go b/storagev2/apis/api_get_bucket_cors_rules.go index 7c3b0931..22904210 100644 --- a/storagev2/apis/api_get_bucket_cors_rules.go +++ b/storagev2/apis/api_get_bucket_cors_rules.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketcorsrules "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_cors_rules" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -21,7 +21,7 @@ func (pp *innerGetBucketCORSRulesRequest) getBucketName(ctx context.Context) (st return pp.Bucket, nil } func (path *innerGetBucketCORSRulesRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -29,16 +29,6 @@ func (path *innerGetBucketCORSRulesRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerGetBucketCORSRulesRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketCORSRulesRequest = getbucketcorsrules.Request type GetBucketCORSRulesResponse = getbucketcorsrules.Response @@ -53,7 +43,7 @@ func (storage *Storage) GetBucketCORSRules(ctx context.Context, request *GetBuck if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 3) pathSegments = append(pathSegments, "corsRules", "get") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -69,8 +59,7 @@ func (storage *Storage) GetBucketCORSRules(ctx context.Context, request *GetBuck return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketCorsrules", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketCorsrules", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -86,33 +75,11 @@ func (storage *Storage) GetBucketCORSRules(ctx context.Context, request *GetBuck } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketCORSRulesResponse diff --git a/storagev2/apis/api_get_bucket_domains.go b/storagev2/apis/api_get_bucket_domains.go index 70ed62f6..077fa2e9 100644 --- a/storagev2/apis/api_get_bucket_domains.go +++ b/storagev2/apis/api_get_bucket_domains.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketdomains "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_domains" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -30,16 +30,6 @@ func (query *innerGetBucketDomainsRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketDomainsRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketDomainsRequest = getbucketdomains.Request type GetBucketDomainsResponse = getbucketdomains.Response @@ -54,7 +44,7 @@ func (storage *Storage) GetBucketDomains(ctx context.Context, request *GetBucket if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "v2", "domains") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -70,8 +60,7 @@ func (storage *Storage) GetBucketDomains(ctx context.Context, request *GetBucket return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketDomains", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketDomains", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -87,33 +76,11 @@ func (storage *Storage) GetBucketDomains(ctx context.Context, request *GetBucket } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketDomainsResponse diff --git a/storagev2/apis/api_get_bucket_domains_v3.go b/storagev2/apis/api_get_bucket_domains_v3.go index 70e71b7a..c7b17b54 100644 --- a/storagev2/apis/api_get_bucket_domains_v3.go +++ b/storagev2/apis/api_get_bucket_domains_v3.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketdomainsv3 "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_domains_v3" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -30,16 +30,6 @@ func (query *innerGetBucketDomainsV3Request) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketDomainsV3Request) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketDomainsV3Request = getbucketdomainsv3.Request type GetBucketDomainsV3Response = getbucketdomainsv3.Response @@ -54,7 +44,7 @@ func (storage *Storage) GetBucketDomainsV3(ctx context.Context, request *GetBuck if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "v3", "domains") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -70,8 +60,7 @@ func (storage *Storage) GetBucketDomainsV3(ctx context.Context, request *GetBuck return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketDomainsV3", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketDomainsV3", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -87,33 +76,11 @@ func (storage *Storage) GetBucketDomainsV3(ctx context.Context, request *GetBuck } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketDomainsV3Response diff --git a/storagev2/apis/api_get_bucket_event_rules.go b/storagev2/apis/api_get_bucket_event_rules.go index 8e6256b2..2c8888bb 100644 --- a/storagev2/apis/api_get_bucket_event_rules.go +++ b/storagev2/apis/api_get_bucket_event_rules.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketeventrules "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_event_rules" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -30,16 +30,6 @@ func (query *innerGetBucketEventRulesRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketEventRulesRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketEventRulesRequest = getbucketeventrules.Request type GetBucketEventRulesResponse = getbucketeventrules.Response @@ -54,7 +44,7 @@ func (storage *Storage) GetBucketEventRules(ctx context.Context, request *GetBuc if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "events", "get") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -70,8 +60,7 @@ func (storage *Storage) GetBucketEventRules(ctx context.Context, request *GetBuc return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketEventRules", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketEventRules", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -87,33 +76,11 @@ func (storage *Storage) GetBucketEventRules(ctx context.Context, request *GetBuc } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketEventRulesResponse diff --git a/storagev2/apis/api_get_bucket_info.go b/storagev2/apis/api_get_bucket_info.go index c86da2e7..b83856a9 100644 --- a/storagev2/apis/api_get_bucket_info.go +++ b/storagev2/apis/api_get_bucket_info.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketinfo "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_info" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -30,16 +30,6 @@ func (query *innerGetBucketInfoRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketInfoRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketInfoRequest = getbucketinfo.Request type GetBucketInfoResponse = getbucketinfo.Response @@ -54,7 +44,7 @@ func (storage *Storage) GetBucketInfo(ctx context.Context, request *GetBucketInf if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "v2", "bucketInfo") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -70,8 +60,7 @@ func (storage *Storage) GetBucketInfo(ctx context.Context, request *GetBucketInf return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketInfo", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketInfo", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -87,33 +76,11 @@ func (storage *Storage) GetBucketInfo(ctx context.Context, request *GetBucketInf } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketInfoResponse diff --git a/storagev2/apis/api_get_bucket_infos.go b/storagev2/apis/api_get_bucket_infos.go index 9d741a0a..079d4265 100644 --- a/storagev2/apis/api_get_bucket_infos.go +++ b/storagev2/apis/api_get_bucket_infos.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketinfos "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_infos" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -29,16 +29,6 @@ func (query *innerGetBucketInfosRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketInfosRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketInfosRequest = getbucketinfos.Request type GetBucketInfosResponse = getbucketinfos.Response @@ -53,7 +43,7 @@ func (storage *Storage) GetBucketInfos(ctx context.Context, request *GetBucketIn if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "v2", "bucketInfos") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -63,8 +53,7 @@ func (storage *Storage) GetBucketInfos(ctx context.Context, request *GetBucketIn rawQuery += query.Encode() } bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketInfos", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketInfos", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -80,33 +69,11 @@ func (storage *Storage) GetBucketInfos(ctx context.Context, request *GetBucketIn } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketInfosResponse diff --git a/storagev2/apis/api_get_bucket_quota.go b/storagev2/apis/api_get_bucket_quota.go index 157f151e..4e721690 100644 --- a/storagev2/apis/api_get_bucket_quota.go +++ b/storagev2/apis/api_get_bucket_quota.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketquota "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_quota" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -21,7 +21,7 @@ func (pp *innerGetBucketQuotaRequest) getBucketName(ctx context.Context) (string return pp.Bucket, nil } func (path *innerGetBucketQuotaRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -29,16 +29,6 @@ func (path *innerGetBucketQuotaRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerGetBucketQuotaRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketQuotaRequest = getbucketquota.Request type GetBucketQuotaResponse = getbucketquota.Response @@ -53,7 +43,7 @@ func (storage *Storage) GetBucketQuota(ctx context.Context, request *GetBucketQu if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "getbucketquota") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -69,8 +59,7 @@ func (storage *Storage) GetBucketQuota(ctx context.Context, request *GetBucketQu return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketQuota", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketQuota", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -86,33 +75,11 @@ func (storage *Storage) GetBucketQuota(ctx context.Context, request *GetBucketQu } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketQuotaResponse diff --git a/storagev2/apis/api_get_bucket_rules.go b/storagev2/apis/api_get_bucket_rules.go index 5ad62cfe..390b892e 100644 --- a/storagev2/apis/api_get_bucket_rules.go +++ b/storagev2/apis/api_get_bucket_rules.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketrules "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_rules" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -27,16 +27,6 @@ func (query *innerGetBucketRulesRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketRulesRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketRulesRequest = getbucketrules.Request type GetBucketRulesResponse = getbucketrules.Response @@ -51,7 +41,7 @@ func (storage *Storage) GetBucketRules(ctx context.Context, request *GetBucketRu if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "rules", "get") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -61,8 +51,7 @@ func (storage *Storage) GetBucketRules(ctx context.Context, request *GetBucketRu rawQuery += query.Encode() } bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketRules", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketRules", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -78,33 +67,11 @@ func (storage *Storage) GetBucketRules(ctx context.Context, request *GetBucketRu } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketRulesResponse diff --git a/storagev2/apis/api_get_bucket_taggings.go b/storagev2/apis/api_get_bucket_taggings.go index 161689d8..3073c918 100644 --- a/storagev2/apis/api_get_bucket_taggings.go +++ b/storagev2/apis/api_get_bucket_taggings.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbuckettaggings "github.com/qiniu/go-sdk/v7/storagev2/apis/get_bucket_taggings" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -30,16 +30,6 @@ func (query *innerGetBucketTaggingsRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketTaggingsRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketTaggingsRequest = getbuckettaggings.Request type GetBucketTaggingsResponse = getbuckettaggings.Response @@ -54,7 +44,7 @@ func (storage *Storage) GetBucketTaggings(ctx context.Context, request *GetBucke if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "bucketTagging") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -70,8 +60,7 @@ func (storage *Storage) GetBucketTaggings(ctx context.Context, request *GetBucke return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketTaggings", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketTaggings", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -87,33 +76,11 @@ func (storage *Storage) GetBucketTaggings(ctx context.Context, request *GetBucke } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketTaggingsResponse diff --git a/storagev2/apis/api_get_buckets.go b/storagev2/apis/api_get_buckets.go index dce22f60..eeef828b 100644 --- a/storagev2/apis/api_get_buckets.go +++ b/storagev2/apis/api_get_buckets.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbuckets "github.com/qiniu/go-sdk/v7/storagev2/apis/get_buckets" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -25,16 +25,6 @@ func (query *innerGetBucketsRequest) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketsRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketsRequest = getbuckets.Request type GetBucketsResponse = getbuckets.Response @@ -49,7 +39,7 @@ func (storage *Storage) GetBuckets(ctx context.Context, request *GetBucketsReque if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "buckets") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -59,8 +49,7 @@ func (storage *Storage) GetBuckets(ctx context.Context, request *GetBucketsReque rawQuery += query.Encode() } bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBuckets", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBuckets", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -76,33 +65,11 @@ func (storage *Storage) GetBuckets(ctx context.Context, request *GetBucketsReque } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketsResponse diff --git a/storagev2/apis/api_get_buckets_v4.go b/storagev2/apis/api_get_buckets_v4.go index 4ba88ab6..e1acbb6e 100644 --- a/storagev2/apis/api_get_buckets_v4.go +++ b/storagev2/apis/api_get_buckets_v4.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getbucketsv4 "github.com/qiniu/go-sdk/v7/storagev2/apis/get_buckets_v4" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -32,16 +32,6 @@ func (query *innerGetBucketsV4Request) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerGetBucketsV4Request) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type GetBucketsV4Request = getbucketsv4.Request type GetBucketsV4Response = getbucketsv4.Response @@ -56,7 +46,7 @@ func (storage *Storage) GetBucketsV4(ctx context.Context, request *GetBucketsV4R if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "buckets") path := "/" + strings.Join(pathSegments, "/") rawQuery := "apiVersion=v4&" @@ -66,8 +56,7 @@ func (storage *Storage) GetBucketsV4(ctx context.Context, request *GetBucketsV4R rawQuery += query.Encode() } bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getBucketsV4", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getBucketsV4", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -83,33 +72,11 @@ func (storage *Storage) GetBucketsV4(ctx context.Context, request *GetBucketsV4R } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetBucketsV4Response diff --git a/storagev2/apis/api_get_objects.go b/storagev2/apis/api_get_objects.go index cf76cbbd..a7aa35a4 100644 --- a/storagev2/apis/api_get_objects.go +++ b/storagev2/apis/api_get_objects.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getobjects "github.com/qiniu/go-sdk/v7/storagev2/apis/get_objects" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -70,7 +70,7 @@ func (storage *Storage) GetObjects(ctx context.Context, request *GetObjectsReque if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "list") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -86,8 +86,7 @@ func (storage *Storage) GetObjects(ctx context.Context, request *GetObjectsReque return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getObjects", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getObjects", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -103,40 +102,42 @@ func (storage *Storage) GetObjects(ctx context.Context, request *GetObjectsReque } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_get_objects_v2.go b/storagev2/apis/api_get_objects_v2.go index 4821324b..1711ba42 100644 --- a/storagev2/apis/api_get_objects_v2.go +++ b/storagev2/apis/api_get_objects_v2.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getobjectsv2 "github.com/qiniu/go-sdk/v7/storagev2/apis/get_objects_v2" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -70,7 +70,7 @@ func (storage *Storage) GetObjectsV2(ctx context.Context, request *GetObjectsV2R if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "v2", "list") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -86,8 +86,7 @@ func (storage *Storage) GetObjectsV2(ctx context.Context, request *GetObjectsV2R return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getObjectsV2", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getObjectsV2", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -103,40 +102,42 @@ func (storage *Storage) GetObjectsV2(ctx context.Context, request *GetObjectsV2R } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_get_regions.go b/storagev2/apis/api_get_regions.go index 474fa2cb..967a18e5 100644 --- a/storagev2/apis/api_get_regions.go +++ b/storagev2/apis/api_get_regions.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" getregions "github.com/qiniu/go-sdk/v7/storagev2/apis/get_regions" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -16,18 +16,6 @@ import ( ) type innerGetRegionsRequest getregions.Request - -func (request *innerGetRegionsRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} - type GetRegionsRequest = getregions.Request type GetRegionsResponse = getregions.Response @@ -41,13 +29,12 @@ func (storage *Storage) GetRegions(ctx context.Context, request *GetRegionsReque if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "regions") path := "/" + strings.Join(pathSegments, "/") var rawQuery string bucketName := options.OverwrittenBucketName - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("getRegions", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("getRegions", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -63,33 +50,11 @@ func (storage *Storage) GetRegions(ctx context.Context, request *GetRegionsReque } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } var respBody GetRegionsResponse diff --git a/storagev2/apis/api_modify_object_life_cycle.go b/storagev2/apis/api_modify_object_life_cycle.go index 43bb4bc8..be26aa87 100644 --- a/storagev2/apis/api_modify_object_life_cycle.go +++ b/storagev2/apis/api_modify_object_life_cycle.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" modifyobjectlifecycle "github.com/qiniu/go-sdk/v7/storagev2/apis/modify_object_life_cycle" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -30,7 +30,7 @@ func (pp *innerModifyObjectLifeCycleRequest) getObjectName() string { return "" } func (path *innerModifyObjectLifeCycleRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 11) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -77,7 +77,7 @@ func (storage *Storage) ModifyObjectLifeCycle(ctx context.Context, request *Modi if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 12) pathSegments = append(pathSegments, "lifecycle") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -110,40 +110,42 @@ func (storage *Storage) ModifyObjectLifeCycle(ctx context.Context, request *Modi } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_modify_object_metadata.go b/storagev2/apis/api_modify_object_metadata.go index 82daa387..819de9b8 100644 --- a/storagev2/apis/api_modify_object_metadata.go +++ b/storagev2/apis/api_modify_object_metadata.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" modifyobjectmetadata "github.com/qiniu/go-sdk/v7/storagev2/apis/modify_object_metadata" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -29,7 +29,7 @@ func (pp *innerModifyObjectMetadataRequest) getObjectName() string { return "" } func (path *innerModifyObjectMetadataRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -71,7 +71,7 @@ func (storage *Storage) ModifyObjectMetadata(ctx context.Context, request *Modif if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "chgm") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -104,40 +104,42 @@ func (storage *Storage) ModifyObjectMetadata(ctx context.Context, request *Modif } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_modify_object_status.go b/storagev2/apis/api_modify_object_status.go index 6db6c1f8..6ba5a158 100644 --- a/storagev2/apis/api_modify_object_status.go +++ b/storagev2/apis/api_modify_object_status.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" modifyobjectstatus "github.com/qiniu/go-sdk/v7/storagev2/apis/modify_object_status" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -30,7 +30,7 @@ func (pp *innerModifyObjectStatusRequest) getObjectName() string { return "" } func (path *innerModifyObjectStatusRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 3) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -63,7 +63,7 @@ func (storage *Storage) ModifyObjectStatus(ctx context.Context, request *ModifyO if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 4) pathSegments = append(pathSegments, "chstatus") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -96,40 +96,42 @@ func (storage *Storage) ModifyObjectStatus(ctx context.Context, request *ModifyO } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_move_object.go b/storagev2/apis/api_move_object.go index 1a8864aa..a78b30e8 100644 --- a/storagev2/apis/api_move_object.go +++ b/storagev2/apis/api_move_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" moveobject "github.com/qiniu/go-sdk/v7/storagev2/apis/move_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -30,7 +30,7 @@ func (pp *innerMoveObjectRequest) getObjectName() string { return "" } func (path *innerMoveObjectRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 4) if path.SrcEntry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.SrcEntry))) } else { @@ -70,7 +70,7 @@ func (storage *Storage) MoveObject(ctx context.Context, request *MoveObjectReque if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 5) pathSegments = append(pathSegments, "move") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -103,40 +103,42 @@ func (storage *Storage) MoveObject(ctx context.Context, request *MoveObjectReque } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_post_object.go b/storagev2/apis/api_post_object.go index ca7e0023..8a45403d 100644 --- a/storagev2/apis/api_post_object.go +++ b/storagev2/apis/api_post_object.go @@ -4,10 +4,10 @@ package apis import ( "context" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" postobject "github.com/qiniu/go-sdk/v7/storagev2/apis/post_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "strconv" "strings" @@ -81,8 +81,7 @@ func (storage *Storage) PostObject(ctx context.Context, request *PostObjectReque } innerRequest := (*innerPostObjectRequest)(request) serviceNames := []region.ServiceName{region.ServiceUp} - var pathSegments []string - pathSegments = append(pathSegments, "") + pathSegments := make([]string, 0) path := "/" + strings.Join(pathSegments, "/") var rawQuery string body, err := innerRequest.build(ctx) @@ -103,40 +102,42 @@ func (storage *Storage) PostObject(ctx context.Context, request *PostObjectReque } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, BufferResponse: true, RequestBody: httpclient.GetMultipartFormRequestBody(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_prefetch_object.go b/storagev2/apis/api_prefetch_object.go index 43694ee3..0e60d0a7 100644 --- a/storagev2/apis/api_prefetch_object.go +++ b/storagev2/apis/api_prefetch_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" prefetchobject "github.com/qiniu/go-sdk/v7/storagev2/apis/prefetch_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -29,7 +29,7 @@ func (pp *innerPrefetchObjectRequest) getObjectName() string { return "" } func (path *innerPrefetchObjectRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -61,7 +61,7 @@ func (storage *Storage) PrefetchObject(ctx context.Context, request *PrefetchObj if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "prefetch") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -94,40 +94,42 @@ func (storage *Storage) PrefetchObject(ctx context.Context, request *PrefetchObj } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_query_bucket_v2.go b/storagev2/apis/api_query_bucket_v2.go index 00292ff5..0590f7a4 100644 --- a/storagev2/apis/api_query_bucket_v2.go +++ b/storagev2/apis/api_query_bucket_v2.go @@ -4,10 +4,10 @@ package apis import ( "context" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" querybucketv2 "github.com/qiniu/go-sdk/v7/storagev2/apis/query_bucket_v2" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "net/url" "strings" @@ -32,9 +32,6 @@ func (query *innerQueryBucketV2Request) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerQueryBucketV2Request) getAccessKey(ctx context.Context) (string, error) { - return "", nil -} type QueryBucketV2Request = querybucketv2.Request type QueryBucketV2Response = querybucketv2.Response @@ -46,7 +43,7 @@ func (storage *Storage) QueryBucketV2(ctx context.Context, request *QueryBucketV } innerRequest := (*innerQueryBucketV2Request)(request) serviceNames := []region.ServiceName{region.ServiceBucket} - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "v2", "query") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -62,40 +59,17 @@ func (storage *Storage) QueryBucketV2(ctx context.Context, request *QueryBucketV return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("queryBucketV2", bucketName, objectName, nil) + uplogInterceptor, err := uplog.NewRequestUplog("queryBucketV2", bucketName, "", nil) if err != nil { return nil, err } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } ctx = httpclient.WithoutSignature(ctx) diff --git a/storagev2/apis/api_query_bucket_v4.go b/storagev2/apis/api_query_bucket_v4.go index 02af0164..2597fa24 100644 --- a/storagev2/apis/api_query_bucket_v4.go +++ b/storagev2/apis/api_query_bucket_v4.go @@ -4,10 +4,10 @@ package apis import ( "context" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" querybucketv4 "github.com/qiniu/go-sdk/v7/storagev2/apis/query_bucket_v4" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "net/url" "strings" @@ -32,9 +32,6 @@ func (query *innerQueryBucketV4Request) buildQuery() (url.Values, error) { } return allQuery, nil } -func (request *innerQueryBucketV4Request) getAccessKey(ctx context.Context) (string, error) { - return "", nil -} type QueryBucketV4Request = querybucketv4.Request type QueryBucketV4Response = querybucketv4.Response @@ -46,7 +43,7 @@ func (storage *Storage) QueryBucketV4(ctx context.Context, request *QueryBucketV } innerRequest := (*innerQueryBucketV4Request)(request) serviceNames := []region.ServiceName{region.ServiceBucket} - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "v4", "query") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -62,40 +59,17 @@ func (storage *Storage) QueryBucketV4(ctx context.Context, request *QueryBucketV return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("queryBucketV4", bucketName, objectName, nil) + uplogInterceptor, err := uplog.NewRequestUplog("queryBucketV4", bucketName, "", nil) if err != nil { return nil, err } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } ctx = httpclient.WithoutSignature(ctx) diff --git a/storagev2/apis/api_restore_archived_object.go b/storagev2/apis/api_restore_archived_object.go index e8f800cf..9608cfd2 100644 --- a/storagev2/apis/api_restore_archived_object.go +++ b/storagev2/apis/api_restore_archived_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" restorearchivedobject "github.com/qiniu/go-sdk/v7/storagev2/apis/restore_archived_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -30,7 +30,7 @@ func (pp *innerRestoreArchivedObjectRequest) getObjectName() string { return "" } func (path *innerRestoreArchivedObjectRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 3) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -67,7 +67,7 @@ func (storage *Storage) RestoreArchivedObject(ctx context.Context, request *Rest if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 4) pathSegments = append(pathSegments, "restoreAr") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -100,40 +100,42 @@ func (storage *Storage) RestoreArchivedObject(ctx context.Context, request *Rest } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v1_bput.go b/storagev2/apis/api_resumable_upload_v1_bput.go index e88fed44..7022a0c5 100644 --- a/storagev2/apis/api_resumable_upload_v1_bput.go +++ b/storagev2/apis/api_resumable_upload_v1_bput.go @@ -4,10 +4,10 @@ package apis import ( "context" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv1bput "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v1_bput" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "strconv" "strings" @@ -26,7 +26,7 @@ func (request *innerResumableUploadV1BputRequest) getBucketName(ctx context.Cont return "", nil } func (path *innerResumableUploadV1BputRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 2) if path.Ctx != "" { allSegments = append(allSegments, path.Ctx) } else { @@ -55,7 +55,7 @@ func (storage *Storage) ResumableUploadV1Bput(ctx context.Context, request *Resu if innerRequest.UpToken == nil { return nil, errors.MissingRequiredFieldError{Name: "UpToken"} } - var pathSegments []string + pathSegments := make([]string, 0, 3) pathSegments = append(pathSegments, "bput") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -75,8 +75,7 @@ func (storage *Storage) ResumableUploadV1Bput(ctx context.Context, request *Resu return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV1Bput", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV1Bput", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -84,40 +83,42 @@ func (storage *Storage) ResumableUploadV1Bput(ctx context.Context, request *Resu } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, UpToken: innerRequest.UpToken, BufferResponse: true, RequestBody: httpclient.GetRequestBodyFromReadSeekCloser(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v1_make_block.go b/storagev2/apis/api_resumable_upload_v1_make_block.go index 959a2031..1f55ecf4 100644 --- a/storagev2/apis/api_resumable_upload_v1_make_block.go +++ b/storagev2/apis/api_resumable_upload_v1_make_block.go @@ -4,10 +4,10 @@ package apis import ( "context" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv1makeblock "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v1_make_block" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "strconv" "strings" @@ -26,7 +26,7 @@ func (request *innerResumableUploadV1MakeBlockRequest) getBucketName(ctx context return "", nil } func (path *innerResumableUploadV1MakeBlockRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.BlockSize != 0 { allSegments = append(allSegments, strconv.FormatInt(path.BlockSize, 10)) } else { @@ -54,7 +54,7 @@ func (storage *Storage) ResumableUploadV1MakeBlock(ctx context.Context, request if innerRequest.UpToken == nil { return nil, errors.MissingRequiredFieldError{Name: "UpToken"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "mkblk") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -74,8 +74,7 @@ func (storage *Storage) ResumableUploadV1MakeBlock(ctx context.Context, request return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV1MakeBlock", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV1MakeBlock", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -83,40 +82,42 @@ func (storage *Storage) ResumableUploadV1MakeBlock(ctx context.Context, request } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, UpToken: innerRequest.UpToken, BufferResponse: true, RequestBody: httpclient.GetRequestBodyFromReadSeekCloser(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v1_make_file.go b/storagev2/apis/api_resumable_upload_v1_make_file.go index c47ed99d..3bdbc546 100644 --- a/storagev2/apis/api_resumable_upload_v1_make_file.go +++ b/storagev2/apis/api_resumable_upload_v1_make_file.go @@ -5,10 +5,10 @@ package apis import ( "context" "encoding/base64" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv1makefile "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v1_make_file" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "strconv" "strings" @@ -27,7 +27,7 @@ func (request *innerResumableUploadV1MakeFileRequest) getBucketName(ctx context. return "", nil } func (path *innerResumableUploadV1MakeFileRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 7) allSegments = append(allSegments, strconv.FormatInt(path.Size, 10)) if path.ObjectName != nil { allSegments = append(allSegments, "key", base64.URLEncoding.EncodeToString([]byte(*path.ObjectName))) @@ -64,7 +64,7 @@ func (storage *Storage) ResumableUploadV1MakeFile(ctx context.Context, request * if innerRequest.UpToken == nil { return nil, errors.MissingRequiredFieldError{Name: "UpToken"} } - var pathSegments []string + pathSegments := make([]string, 0, 8) pathSegments = append(pathSegments, "mkfile") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -84,8 +84,7 @@ func (storage *Storage) ResumableUploadV1MakeFile(ctx context.Context, request * return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV1MakeFile", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV1MakeFile", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -93,40 +92,42 @@ func (storage *Storage) ResumableUploadV1MakeFile(ctx context.Context, request * } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, UpToken: innerRequest.UpToken, BufferResponse: true, RequestBody: httpclient.GetRequestBodyFromReadSeekCloser(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v2_abort_multipart_upload.go b/storagev2/apis/api_resumable_upload_v2_abort_multipart_upload.go index 243c28e4..9396cb23 100644 --- a/storagev2/apis/api_resumable_upload_v2_abort_multipart_upload.go +++ b/storagev2/apis/api_resumable_upload_v2_abort_multipart_upload.go @@ -5,10 +5,10 @@ package apis import ( "context" "encoding/base64" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv2abortmultipartupload "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v2_abort_multipart_upload" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "strings" ) @@ -26,7 +26,7 @@ func (request *innerResumableUploadV2AbortMultipartUploadRequest) getBucketName( return "", nil } func (path *innerResumableUploadV2AbortMultipartUploadRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.BucketName != "" { allSegments = append(allSegments, path.BucketName) } else { @@ -64,7 +64,7 @@ func (storage *Storage) ResumableUploadV2AbortMultipartUpload(ctx context.Contex if innerRequest.UpToken == nil { return nil, errors.MissingRequiredFieldError{Name: "UpToken"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "buckets") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -80,8 +80,7 @@ func (storage *Storage) ResumableUploadV2AbortMultipartUpload(ctx context.Contex return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2AbortMultipartUpload", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2AbortMultipartUpload", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -89,40 +88,42 @@ func (storage *Storage) ResumableUploadV2AbortMultipartUpload(ctx context.Contex } req := httpclient.Request{Method: "DELETE", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, UpToken: innerRequest.UpToken, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v2_complete_multipart_upload.go b/storagev2/apis/api_resumable_upload_v2_complete_multipart_upload.go index 16109088..6b314714 100644 --- a/storagev2/apis/api_resumable_upload_v2_complete_multipart_upload.go +++ b/storagev2/apis/api_resumable_upload_v2_complete_multipart_upload.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" "encoding/json" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv2completemultipartupload "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v2_complete_multipart_upload" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "strings" ) @@ -27,7 +27,7 @@ func (request *innerResumableUploadV2CompleteMultipartUploadRequest) getBucketNa return "", nil } func (path *innerResumableUploadV2CompleteMultipartUploadRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.BucketName != "" { allSegments = append(allSegments, path.BucketName) } else { @@ -71,7 +71,7 @@ func (storage *Storage) ResumableUploadV2CompleteMultipartUpload(ctx context.Con if innerRequest.UpToken == nil { return nil, errors.MissingRequiredFieldError{Name: "UpToken"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "buckets") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -91,8 +91,7 @@ func (storage *Storage) ResumableUploadV2CompleteMultipartUpload(ctx context.Con return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2CompleteMultipartUpload", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2CompleteMultipartUpload", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -100,40 +99,42 @@ func (storage *Storage) ResumableUploadV2CompleteMultipartUpload(ctx context.Con } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, UpToken: innerRequest.UpToken, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v2_initiate_multipart_upload.go b/storagev2/apis/api_resumable_upload_v2_initiate_multipart_upload.go index cfb2cc0f..90001216 100644 --- a/storagev2/apis/api_resumable_upload_v2_initiate_multipart_upload.go +++ b/storagev2/apis/api_resumable_upload_v2_initiate_multipart_upload.go @@ -5,10 +5,10 @@ package apis import ( "context" "encoding/base64" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv2initiatemultipartupload "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v2_initiate_multipart_upload" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "strings" ) @@ -26,7 +26,7 @@ func (request *innerResumableUploadV2InitiateMultipartUploadRequest) getBucketNa return "", nil } func (path *innerResumableUploadV2InitiateMultipartUploadRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 3) if path.BucketName != "" { allSegments = append(allSegments, path.BucketName) } else { @@ -59,7 +59,7 @@ func (storage *Storage) ResumableUploadV2InitiateMultipartUpload(ctx context.Con if innerRequest.UpToken == nil { return nil, errors.MissingRequiredFieldError{Name: "UpToken"} } - var pathSegments []string + pathSegments := make([]string, 0, 5) pathSegments = append(pathSegments, "buckets") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -76,8 +76,7 @@ func (storage *Storage) ResumableUploadV2InitiateMultipartUpload(ctx context.Con return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2InitiateMultipartUpload", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2InitiateMultipartUpload", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -85,40 +84,42 @@ func (storage *Storage) ResumableUploadV2InitiateMultipartUpload(ctx context.Con } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, UpToken: innerRequest.UpToken, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v2_list_parts.go b/storagev2/apis/api_resumable_upload_v2_list_parts.go index 5f0bc8d8..4eda37bf 100644 --- a/storagev2/apis/api_resumable_upload_v2_list_parts.go +++ b/storagev2/apis/api_resumable_upload_v2_list_parts.go @@ -5,10 +5,10 @@ package apis import ( "context" "encoding/base64" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv2listparts "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v2_list_parts" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "net/url" "strconv" @@ -28,7 +28,7 @@ func (request *innerResumableUploadV2ListPartsRequest) getBucketName(ctx context return "", nil } func (path *innerResumableUploadV2ListPartsRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.BucketName != "" { allSegments = append(allSegments, path.BucketName) } else { @@ -76,7 +76,7 @@ func (storage *Storage) ResumableUploadV2ListParts(ctx context.Context, request if innerRequest.UpToken == nil { return nil, errors.MissingRequiredFieldError{Name: "UpToken"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "buckets") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -97,8 +97,7 @@ func (storage *Storage) ResumableUploadV2ListParts(ctx context.Context, request return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2ListParts", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2ListParts", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -106,40 +105,42 @@ func (storage *Storage) ResumableUploadV2ListParts(ctx context.Context, request } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, UpToken: innerRequest.UpToken, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_resumable_upload_v2_upload_part.go b/storagev2/apis/api_resumable_upload_v2_upload_part.go index cbd03f45..7c28066c 100644 --- a/storagev2/apis/api_resumable_upload_v2_upload_part.go +++ b/storagev2/apis/api_resumable_upload_v2_upload_part.go @@ -5,10 +5,10 @@ package apis import ( "context" "encoding/base64" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" resumableuploadv2uploadpart "github.com/qiniu/go-sdk/v7/storagev2/apis/resumable_upload_v2_upload_part" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" "net/http" "strconv" @@ -28,7 +28,7 @@ func (request *innerResumableUploadV2UploadPartRequest) getBucketName(ctx contex return "", nil } func (path *innerResumableUploadV2UploadPartRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 6) if path.BucketName != "" { allSegments = append(allSegments, path.BucketName) } else { @@ -82,7 +82,7 @@ func (storage *Storage) ResumableUploadV2UploadPart(ctx context.Context, request if err != nil { return nil, err } - var pathSegments []string + pathSegments := make([]string, 0, 7) pathSegments = append(pathSegments, "buckets") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -102,8 +102,7 @@ func (storage *Storage) ResumableUploadV2UploadPart(ctx context.Context, request return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2UploadPart", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("resumableUploadV2UploadPart", bucketName, "", func() (string, error) { return innerRequest.UpToken.GetUpToken(ctx) }) if err != nil { @@ -111,40 +110,42 @@ func (storage *Storage) ResumableUploadV2UploadPart(ctx context.Context, request } req := httpclient.Request{Method: "PUT", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, Header: headers, UpToken: innerRequest.UpToken, BufferResponse: true, RequestBody: httpclient.GetRequestBodyFromReadSeekCloser(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_set_bucket_access_mode.go b/storagev2/apis/api_set_bucket_access_mode.go index 1f225c1c..c415dedd 100644 --- a/storagev2/apis/api_set_bucket_access_mode.go +++ b/storagev2/apis/api_set_bucket_access_mode.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketaccessmode "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_access_mode" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -22,7 +22,7 @@ func (pp *innerSetBucketAccessModeRequest) getBucketName(ctx context.Context) (s return pp.Bucket, nil } func (path *innerSetBucketAccessModeRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 3) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -31,16 +31,6 @@ func (path *innerSetBucketAccessModeRequest) buildPath() ([]string, error) { allSegments = append(allSegments, "mode", strconv.FormatInt(path.Mode, 10)) return allSegments, nil } -func (request *innerSetBucketAccessModeRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketAccessModeRequest = setbucketaccessmode.Request type SetBucketAccessModeResponse = setbucketaccessmode.Response @@ -55,7 +45,7 @@ func (storage *Storage) SetBucketAccessMode(ctx context.Context, request *SetBuc if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 4) pathSegments = append(pathSegments, "accessMode") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -71,8 +61,7 @@ func (storage *Storage) SetBucketAccessMode(ctx context.Context, request *SetBuc return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketAccessMode", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketAccessMode", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -88,33 +77,11 @@ func (storage *Storage) SetBucketAccessMode(ctx context.Context, request *SetBuc } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_cors_rules.go b/storagev2/apis/api_set_bucket_cors_rules.go index b1f7f726..3ac63b99 100644 --- a/storagev2/apis/api_set_bucket_cors_rules.go +++ b/storagev2/apis/api_set_bucket_cors_rules.go @@ -6,10 +6,10 @@ import ( "context" "encoding/json" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketcorsrules "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_cors_rules" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -22,7 +22,7 @@ func (pp *innerSetBucketCORSRulesRequest) getBucketName(ctx context.Context) (st return pp.Bucket, nil } func (path *innerSetBucketCORSRulesRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -36,16 +36,6 @@ func (j *innerSetBucketCORSRulesRequest) MarshalJSON() ([]byte, error) { func (j *innerSetBucketCORSRulesRequest) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, (*setbucketcorsrules.Request)(j)) } -func (request *innerSetBucketCORSRulesRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketCORSRulesRequest = setbucketcorsrules.Request type SetBucketCORSRulesResponse = setbucketcorsrules.Response @@ -60,7 +50,7 @@ func (storage *Storage) SetBucketCORSRules(ctx context.Context, request *SetBuck if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 3) pathSegments = append(pathSegments, "corsRules", "set") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -80,8 +70,7 @@ func (storage *Storage) SetBucketCORSRules(ctx context.Context, request *SetBuck return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketCorsrules", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketCorsrules", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -97,33 +86,11 @@ func (storage *Storage) SetBucketCORSRules(ctx context.Context, request *SetBuck } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_image.go b/storagev2/apis/api_set_bucket_image.go index 1a90c161..155e9afe 100644 --- a/storagev2/apis/api_set_bucket_image.go +++ b/storagev2/apis/api_set_bucket_image.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketimage "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_image" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -22,7 +22,7 @@ func (pp *innerSetBucketImageRequest) getBucketName(ctx context.Context) (string return pp.Bucket, nil } func (path *innerSetBucketImageRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -38,16 +38,6 @@ func (path *innerSetBucketImageRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerSetBucketImageRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketImageRequest = setbucketimage.Request type SetBucketImageResponse = setbucketimage.Response @@ -62,7 +52,7 @@ func (storage *Storage) SetBucketImage(ctx context.Context, request *SetBucketIm if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "image") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -78,8 +68,7 @@ func (storage *Storage) SetBucketImage(ctx context.Context, request *SetBucketIm return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketImage", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketImage", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -95,33 +84,11 @@ func (storage *Storage) SetBucketImage(ctx context.Context, request *SetBucketIm } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_max_age.go b/storagev2/apis/api_set_bucket_max_age.go index 6f6106fa..e550b506 100644 --- a/storagev2/apis/api_set_bucket_max_age.go +++ b/storagev2/apis/api_set_bucket_max_age.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketmaxage "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_max_age" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -32,16 +32,6 @@ func (query *innerSetBucketMaxAgeRequest) buildQuery() (url.Values, error) { allQuery.Set("maxAge", strconv.FormatInt(query.MaxAge, 10)) return allQuery, nil } -func (request *innerSetBucketMaxAgeRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketMaxAgeRequest = setbucketmaxage.Request type SetBucketMaxAgeResponse = setbucketmaxage.Response @@ -56,7 +46,7 @@ func (storage *Storage) SetBucketMaxAge(ctx context.Context, request *SetBucketM if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "maxAge") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -72,8 +62,7 @@ func (storage *Storage) SetBucketMaxAge(ctx context.Context, request *SetBucketM return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketMaxAge", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketMaxAge", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -89,33 +78,11 @@ func (storage *Storage) SetBucketMaxAge(ctx context.Context, request *SetBucketM } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_private.go b/storagev2/apis/api_set_bucket_private.go index 30f32609..d696c35a 100644 --- a/storagev2/apis/api_set_bucket_private.go +++ b/storagev2/apis/api_set_bucket_private.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketprivate "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_private" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -32,16 +32,6 @@ func (form *innerSetBucketPrivateRequest) build() (url.Values, error) { formValues.Set("private", strconv.FormatInt(form.IsPrivate, 10)) return formValues, nil } -func (request *innerSetBucketPrivateRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketPrivateRequest = setbucketprivate.Request type SetBucketPrivateResponse = setbucketprivate.Response @@ -56,7 +46,7 @@ func (storage *Storage) SetBucketPrivate(ctx context.Context, request *SetBucket if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "private") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -71,8 +61,7 @@ func (storage *Storage) SetBucketPrivate(ctx context.Context, request *SetBucket return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketPrivate", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketPrivate", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -88,33 +77,11 @@ func (storage *Storage) SetBucketPrivate(ctx context.Context, request *SetBucket } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: httpclient.GetFormRequestBody(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_quota.go b/storagev2/apis/api_set_bucket_quota.go index e7832ac1..c4b4eb1a 100644 --- a/storagev2/apis/api_set_bucket_quota.go +++ b/storagev2/apis/api_set_bucket_quota.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketquota "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_quota" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -22,7 +22,7 @@ func (pp *innerSetBucketQuotaRequest) getBucketName(ctx context.Context) (string return pp.Bucket, nil } func (path *innerSetBucketQuotaRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -36,16 +36,6 @@ func (path *innerSetBucketQuotaRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerSetBucketQuotaRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketQuotaRequest = setbucketquota.Request type SetBucketQuotaResponse = setbucketquota.Response @@ -60,7 +50,7 @@ func (storage *Storage) SetBucketQuota(ctx context.Context, request *SetBucketQu if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "setbucketquota") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -76,8 +66,7 @@ func (storage *Storage) SetBucketQuota(ctx context.Context, request *SetBucketQu return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketQuota", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketQuota", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -93,33 +82,11 @@ func (storage *Storage) SetBucketQuota(ctx context.Context, request *SetBucketQu } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_refer_anti_leech.go b/storagev2/apis/api_set_bucket_refer_anti_leech.go index 3d0393d7..516cf9e7 100644 --- a/storagev2/apis/api_set_bucket_refer_anti_leech.go +++ b/storagev2/apis/api_set_bucket_refer_anti_leech.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketreferantileech "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_refer_anti_leech" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -35,16 +35,6 @@ func (query *innerSetBucketReferAntiLeechRequest) buildQuery() (url.Values, erro allQuery.Set("source_enabled", strconv.FormatInt(query.SourceEnabled, 10)) return allQuery, nil } -func (request *innerSetBucketReferAntiLeechRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketReferAntiLeechRequest = setbucketreferantileech.Request type SetBucketReferAntiLeechResponse = setbucketreferantileech.Response @@ -59,7 +49,7 @@ func (storage *Storage) SetBucketReferAntiLeech(ctx context.Context, request *Se if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "referAntiLeech") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -75,8 +65,7 @@ func (storage *Storage) SetBucketReferAntiLeech(ctx context.Context, request *Se return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketReferAntiLeech", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketReferAntiLeech", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -92,33 +81,11 @@ func (storage *Storage) SetBucketReferAntiLeech(ctx context.Context, request *Se } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_remark.go b/storagev2/apis/api_set_bucket_remark.go index 83a9dd01..0e6affae 100644 --- a/storagev2/apis/api_set_bucket_remark.go +++ b/storagev2/apis/api_set_bucket_remark.go @@ -6,10 +6,10 @@ import ( "context" "encoding/json" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketremark "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_remark" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -22,7 +22,7 @@ func (pp *innerSetBucketRemarkRequest) getBucketName(ctx context.Context) (strin return pp.Bucket, nil } func (path *innerSetBucketRemarkRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -36,16 +36,6 @@ func (j *innerSetBucketRemarkRequest) MarshalJSON() ([]byte, error) { func (j *innerSetBucketRemarkRequest) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, (*setbucketremark.Request)(j)) } -func (request *innerSetBucketRemarkRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketRemarkRequest = setbucketremark.Request type SetBucketRemarkResponse = setbucketremark.Response @@ -60,7 +50,7 @@ func (storage *Storage) SetBucketRemark(ctx context.Context, request *SetBucketR if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "buckets") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -80,8 +70,7 @@ func (storage *Storage) SetBucketRemark(ctx context.Context, request *SetBucketR return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketRemark", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketRemark", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -97,33 +86,11 @@ func (storage *Storage) SetBucketRemark(ctx context.Context, request *SetBucketR } req := httpclient.Request{Method: "PUT", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_bucket_taggings.go b/storagev2/apis/api_set_bucket_taggings.go index 1b67cbc4..18714d05 100644 --- a/storagev2/apis/api_set_bucket_taggings.go +++ b/storagev2/apis/api_set_bucket_taggings.go @@ -6,10 +6,10 @@ import ( "context" "encoding/json" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbuckettaggings "github.com/qiniu/go-sdk/v7/storagev2/apis/set_bucket_taggings" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -37,16 +37,6 @@ func (j *innerSetBucketTaggingsRequest) MarshalJSON() ([]byte, error) { func (j *innerSetBucketTaggingsRequest) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, (*setbuckettaggings.Request)(j)) } -func (request *innerSetBucketTaggingsRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketTaggingsRequest = setbuckettaggings.Request type SetBucketTaggingsResponse = setbuckettaggings.Response @@ -61,7 +51,7 @@ func (storage *Storage) SetBucketTaggings(ctx context.Context, request *SetBucke if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 1) pathSegments = append(pathSegments, "bucketTagging") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -81,8 +71,7 @@ func (storage *Storage) SetBucketTaggings(ctx context.Context, request *SetBucke return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketTaggings", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketTaggings", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -98,33 +87,11 @@ func (storage *Storage) SetBucketTaggings(ctx context.Context, request *SetBucke } req := httpclient.Request{Method: "PUT", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: body, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_buckets_mirror.go b/storagev2/apis/api_set_buckets_mirror.go index ae2f470c..e2278e42 100644 --- a/storagev2/apis/api_set_buckets_mirror.go +++ b/storagev2/apis/api_set_buckets_mirror.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setbucketsmirror "github.com/qiniu/go-sdk/v7/storagev2/apis/set_buckets_mirror" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -22,7 +22,7 @@ func (pp *innerSetBucketsMirrorRequest) getBucketName(ctx context.Context) (stri return pp.Bucket, nil } func (path *innerSetBucketsMirrorRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 5) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -40,16 +40,6 @@ func (path *innerSetBucketsMirrorRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerSetBucketsMirrorRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type SetBucketsMirrorRequest = setbucketsmirror.Request type SetBucketsMirrorResponse = setbucketsmirror.Response @@ -64,7 +54,7 @@ func (storage *Storage) SetBucketsMirror(ctx context.Context, request *SetBucket if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 6) pathSegments = append(pathSegments, "image") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -80,8 +70,7 @@ func (storage *Storage) SetBucketsMirror(ctx context.Context, request *SetBucket return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("setBucketsMirror", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("setBucketsMirror", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -97,33 +86,11 @@ func (storage *Storage) SetBucketsMirror(ctx context.Context, request *SetBucket } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_set_object_file_type.go b/storagev2/apis/api_set_object_file_type.go index 85f2e270..1f32cbdd 100644 --- a/storagev2/apis/api_set_object_file_type.go +++ b/storagev2/apis/api_set_object_file_type.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" setobjectfiletype "github.com/qiniu/go-sdk/v7/storagev2/apis/set_object_file_type" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strconv" @@ -30,7 +30,7 @@ func (pp *innerSetObjectFileTypeRequest) getObjectName() string { return "" } func (path *innerSetObjectFileTypeRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 3) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -63,7 +63,7 @@ func (storage *Storage) SetObjectFileType(ctx context.Context, request *SetObjec if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 4) pathSegments = append(pathSegments, "chtype") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -96,40 +96,42 @@ func (storage *Storage) SetObjectFileType(ctx context.Context, request *SetObjec } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_stat_object.go b/storagev2/apis/api_stat_object.go index a5b9ec91..7be85283 100644 --- a/storagev2/apis/api_stat_object.go +++ b/storagev2/apis/api_stat_object.go @@ -6,10 +6,10 @@ import ( "context" "encoding/base64" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" statobject "github.com/qiniu/go-sdk/v7/storagev2/apis/stat_object" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -31,7 +31,7 @@ func (pp *innerStatObjectRequest) getObjectName() string { return "" } func (path *innerStatObjectRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Entry != "" { allSegments = append(allSegments, base64.URLEncoding.EncodeToString([]byte(path.Entry))) } else { @@ -70,7 +70,7 @@ func (storage *Storage) StatObject(ctx context.Context, request *StatObjectReque if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "stat") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -108,40 +108,42 @@ func (storage *Storage) StatObject(ctx context.Context, request *StatObjectReque } req := httpclient.Request{Method: "GET", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { return nil, err } } - queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Client: storage.client.GetClient(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} - if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { - queryOptions.RetryMax = hostRetryConfig.RetryMax - queryOptions.Backoff = hostRetryConfig.Backoff - } - if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { - return nil, err - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } } } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } } } } diff --git a/storagev2/apis/api_unset_bucket_image.go b/storagev2/apis/api_unset_bucket_image.go index bfd1ea11..422136d9 100644 --- a/storagev2/apis/api_unset_bucket_image.go +++ b/storagev2/apis/api_unset_bucket_image.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" unsetbucketimage "github.com/qiniu/go-sdk/v7/storagev2/apis/unset_bucket_image" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "strings" @@ -21,7 +21,7 @@ func (pp *innerUnsetBucketImageRequest) getBucketName(ctx context.Context) (stri return pp.Bucket, nil } func (path *innerUnsetBucketImageRequest) buildPath() ([]string, error) { - var allSegments []string + allSegments := make([]string, 0, 1) if path.Bucket != "" { allSegments = append(allSegments, path.Bucket) } else { @@ -29,16 +29,6 @@ func (path *innerUnsetBucketImageRequest) buildPath() ([]string, error) { } return allSegments, nil } -func (request *innerUnsetBucketImageRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type UnsetBucketImageRequest = unsetbucketimage.Request type UnsetBucketImageResponse = unsetbucketimage.Response @@ -53,7 +43,7 @@ func (storage *Storage) UnsetBucketImage(ctx context.Context, request *UnsetBuck if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "unimage") if segments, err := innerRequest.buildPath(); err != nil { return nil, err @@ -69,8 +59,7 @@ func (storage *Storage) UnsetBucketImage(ctx context.Context, request *UnsetBuck return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("unsetBucketImage", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("unsetBucketImage", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -86,33 +75,11 @@ func (storage *Storage) UnsetBucketImage(ctx context.Context, request *UnsetBuck } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_update_bucket_event_rule.go b/storagev2/apis/api_update_bucket_event_rule.go index b956eaae..1487fd5b 100644 --- a/storagev2/apis/api_update_bucket_event_rule.go +++ b/storagev2/apis/api_update_bucket_event_rule.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" updatebucketeventrule "github.com/qiniu/go-sdk/v7/storagev2/apis/update_bucket_event_rule" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -61,16 +61,6 @@ func (query *innerUpdateBucketEventRuleRequest) buildQuery() (url.Values, error) } return allQuery, nil } -func (request *innerUpdateBucketEventRuleRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type UpdateBucketEventRuleRequest = updatebucketeventrule.Request type UpdateBucketEventRuleResponse = updatebucketeventrule.Response @@ -85,7 +75,7 @@ func (storage *Storage) UpdateBucketEventRule(ctx context.Context, request *Upda if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "events", "update") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -101,8 +91,7 @@ func (storage *Storage) UpdateBucketEventRule(ctx context.Context, request *Upda return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("updateBucketEventRule", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("updateBucketEventRule", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -118,33 +107,11 @@ func (storage *Storage) UpdateBucketEventRule(ctx context.Context, request *Upda } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_update_bucket_rules.go b/storagev2/apis/api_update_bucket_rules.go index 8626ffb0..f39d6bf6 100644 --- a/storagev2/apis/api_update_bucket_rules.go +++ b/storagev2/apis/api_update_bucket_rules.go @@ -5,10 +5,10 @@ package apis import ( "context" auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" updatebucketrules "github.com/qiniu/go-sdk/v7/storagev2/apis/update_bucket_rules" errors "github.com/qiniu/go-sdk/v7/storagev2/errors" httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" - uplog "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" region "github.com/qiniu/go-sdk/v7/storagev2/region" uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" "net/url" @@ -44,16 +44,6 @@ func (form *innerUpdateBucketRulesRequest) build() (url.Values, error) { formValues.Set("to_archive_ir_after_days", strconv.FormatInt(form.ToArchiveIrAfterDays, 10)) return formValues, nil } -func (request *innerUpdateBucketRulesRequest) getAccessKey(ctx context.Context) (string, error) { - if request.Credentials != nil { - if credentials, err := request.Credentials.Get(ctx); err != nil { - return "", err - } else { - return credentials.AccessKey, nil - } - } - return "", nil -} type UpdateBucketRulesRequest = updatebucketrules.Request type UpdateBucketRulesResponse = updatebucketrules.Response @@ -68,7 +58,7 @@ func (storage *Storage) UpdateBucketRules(ctx context.Context, request *UpdateBu if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { return nil, errors.MissingRequiredFieldError{Name: "Credentials"} } - var pathSegments []string + pathSegments := make([]string, 0, 2) pathSegments = append(pathSegments, "rules", "update") path := "/" + strings.Join(pathSegments, "/") var rawQuery string @@ -83,8 +73,7 @@ func (storage *Storage) UpdateBucketRules(ctx context.Context, request *UpdateBu return nil, err } } - var objectName string - uplogInterceptor, err := uplog.NewRequestUplog("updateBucketRules", bucketName, objectName, func() (string, error) { + uplogInterceptor, err := uplog.NewRequestUplog("updateBucketRules", bucketName, "", func() (string, error) { credentials := innerRequest.Credentials if credentials == nil { credentials = storage.client.GetCredentials() @@ -100,33 +89,11 @@ func (storage *Storage) UpdateBucketRules(ctx context.Context, request *UpdateBu } req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, RequestBody: httpclient.GetFormRequestBody(body), OnRequestProgress: options.OnRequestProgress} if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { - query := storage.client.GetBucketQuery() - if query == nil { - bucketHosts := httpclient.DefaultBucketHosts() - if options.OverwrittenBucketHosts != nil { - req.Endpoints = options.OverwrittenBucketHosts - } else { - req.Endpoints = bucketHosts - } - } - if query != nil { - var accessKey string - var err error - if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { - return nil, err - } - if accessKey == "" { - if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else if creds != nil { - accessKey = creds.AccessKey - } - } - } - if accessKey != "" && bucketName != "" { - req.Region = query.Query(accessKey, bucketName) - } + bucketHosts := httpclient.DefaultBucketHosts() + if options.OverwrittenBucketHosts != nil { + req.Endpoints = options.OverwrittenBucketHosts + } else { + req.Endpoints = bucketHosts } } resp, err := storage.client.Do(ctx, &req) diff --git a/storagev2/apis/api_verify_share.go b/storagev2/apis/api_verify_share.go new file mode 100644 index 00000000..c9de293b --- /dev/null +++ b/storagev2/apis/api_verify_share.go @@ -0,0 +1,172 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +package apis + +import ( + "context" + "encoding/json" + auth "github.com/qiniu/go-sdk/v7/auth" + uplog "github.com/qiniu/go-sdk/v7/internal/uplog" + verifyshare "github.com/qiniu/go-sdk/v7/storagev2/apis/verify_share" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" + httpclient "github.com/qiniu/go-sdk/v7/storagev2/http_client" + region "github.com/qiniu/go-sdk/v7/storagev2/region" + uptoken "github.com/qiniu/go-sdk/v7/storagev2/uptoken" + "net/url" + "strings" + "time" +) + +type innerVerifyShareRequest verifyshare.Request + +func (path *innerVerifyShareRequest) buildPath() ([]string, error) { + allSegments := make([]string, 0, 1) + if path.ShareId != "" { + allSegments = append(allSegments, path.ShareId) + } else { + return nil, errors.MissingRequiredFieldError{Name: "ShareId"} + } + return allSegments, nil +} +func (query *innerVerifyShareRequest) buildQuery() (url.Values, error) { + allQuery := make(url.Values) + if query.Token != "" { + allQuery.Set("token", query.Token) + } else { + return nil, errors.MissingRequiredFieldError{Name: "Token"} + } + return allQuery, nil +} +func (j *innerVerifyShareRequest) MarshalJSON() ([]byte, error) { + return json.Marshal((*verifyshare.Request)(j)) +} +func (j *innerVerifyShareRequest) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, (*verifyshare.Request)(j)) +} +func (request *innerVerifyShareRequest) getAccessKey(ctx context.Context) (string, error) { + if request.Credentials != nil { + if credentials, err := request.Credentials.Get(ctx); err != nil { + return "", err + } else { + return credentials.AccessKey, nil + } + } + return "", nil +} + +type VerifyShareRequest = verifyshare.Request +type VerifyShareResponse = verifyshare.Response + +// 校验目录分享并提取分享信息 +func (storage *Storage) VerifyShare(ctx context.Context, request *VerifyShareRequest, options *Options) (*VerifyShareResponse, error) { + if options == nil { + options = &Options{} + } + innerRequest := (*innerVerifyShareRequest)(request) + serviceNames := []region.ServiceName{region.ServiceApi} + if innerRequest.Credentials == nil && storage.client.GetCredentials() == nil { + return nil, errors.MissingRequiredFieldError{Name: "Credentials"} + } + pathSegments := make([]string, 0, 3) + pathSegments = append(pathSegments, "shares") + if segments, err := innerRequest.buildPath(); err != nil { + return nil, err + } else { + pathSegments = append(pathSegments, segments...) + } + pathSegments = append(pathSegments, "verify") + path := "/" + strings.Join(pathSegments, "/") + var rawQuery string + if query, err := innerRequest.buildQuery(); err != nil { + return nil, err + } else { + rawQuery += query.Encode() + } + body, err := httpclient.GetJsonRequestBody(&innerRequest) + if err != nil { + return nil, err + } + bucketName := options.OverwrittenBucketName + uplogInterceptor, err := uplog.NewRequestUplog("verifyShare", bucketName, "", func() (string, error) { + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + putPolicy, err := uptoken.NewPutPolicy(bucketName, time.Now().Add(time.Hour)) + if err != nil { + return "", err + } + return uptoken.NewSigner(putPolicy, credentials).GetUpToken(ctx) + }) + if err != nil { + return nil, err + } + req := httpclient.Request{Method: "POST", ServiceNames: serviceNames, Path: path, RawQuery: rawQuery, Endpoints: options.OverwrittenEndpoints, Region: options.OverwrittenRegion, Interceptors: []httpclient.Interceptor{uplogInterceptor}, AuthType: auth.TokenQiniu, Credentials: innerRequest.Credentials, BufferResponse: true, RequestBody: body, OnRequestProgress: options.OnRequestProgress} + if options.OverwrittenEndpoints == nil && options.OverwrittenRegion == nil && storage.client.GetRegions() == nil { + bucketHosts := httpclient.DefaultBucketHosts() + if bucketName != "" { + query := storage.client.GetBucketQuery() + if query == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + queryOptions := region.BucketRegionsQueryOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), AccelerateUploading: storage.client.AccelerateUploadingEnabled(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + queryOptions.RetryMax = hostRetryConfig.RetryMax + queryOptions.Backoff = hostRetryConfig.Backoff + } + if query, err = region.NewBucketRegionsQuery(bucketHosts, &queryOptions); err != nil { + return nil, err + } + } + if query != nil { + var accessKey string + var err error + if accessKey, err = innerRequest.getAccessKey(ctx); err != nil { + return nil, err + } + if accessKey == "" { + if credentialsProvider := storage.client.GetCredentials(); credentialsProvider != nil { + if creds, err := credentialsProvider.Get(ctx); err != nil { + return nil, err + } else if creds != nil { + accessKey = creds.AccessKey + } + } + } + if accessKey != "" { + req.Region = query.Query(accessKey, bucketName) + } + } + } else { + + req.Region = storage.client.GetAllRegions() + if req.Region == nil { + if options.OverwrittenBucketHosts != nil { + if bucketHosts, err = options.OverwrittenBucketHosts.GetEndpoints(ctx); err != nil { + return nil, err + } + } + allRegionsOptions := region.AllRegionsProviderOptions{UseInsecureProtocol: storage.client.UseInsecureProtocol(), HostFreezeDuration: storage.client.GetHostFreezeDuration(), Resolver: storage.client.GetResolver(), Chooser: storage.client.GetChooser(), BeforeSign: storage.client.GetBeforeSignCallback(), AfterSign: storage.client.GetAfterSignCallback(), SignError: storage.client.GetSignErrorCallback(), BeforeResolve: storage.client.GetBeforeResolveCallback(), AfterResolve: storage.client.GetAfterResolveCallback(), ResolveError: storage.client.GetResolveErrorCallback(), BeforeBackoff: storage.client.GetBeforeBackoffCallback(), AfterBackoff: storage.client.GetAfterBackoffCallback(), BeforeRequest: storage.client.GetBeforeRequestCallback(), AfterResponse: storage.client.GetAfterResponseCallback()} + if hostRetryConfig := storage.client.GetHostRetryConfig(); hostRetryConfig != nil { + allRegionsOptions.RetryMax = hostRetryConfig.RetryMax + allRegionsOptions.Backoff = hostRetryConfig.Backoff + } + credentials := innerRequest.Credentials + if credentials == nil { + credentials = storage.client.GetCredentials() + } + if req.Region, err = region.NewAllRegionsProvider(credentials, bucketHosts, &allRegionsOptions); err != nil { + return nil, err + } + } + } + } + var respBody VerifyShareResponse + if err := storage.client.DoAndAcceptJSON(ctx, &req, &respBody); err != nil { + return nil, err + } + return &respBody, nil +} diff --git a/storagev2/apis/check_share/api.go b/storagev2/apis/check_share/api.go new file mode 100644 index 00000000..ea28dba1 --- /dev/null +++ b/storagev2/apis/check_share/api.go @@ -0,0 +1,16 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 检查目录分享 +package check_share + +import credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + +// 调用 API 所用的请求 +type Request struct { + ShareId string // 分享 ID + Token string // 分享 Token + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider +} + +// 获取 API 所用的响应 +type Response struct{} diff --git a/storagev2/apis/create_share/api.go b/storagev2/apis/create_share/api.go new file mode 100644 index 00000000..f4c466f1 --- /dev/null +++ b/storagev2/apis/create_share/api.go @@ -0,0 +1,111 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 创建目录分享 +package create_share + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + Bucket string // 分享的空间名称 + Prefix string // 分享的对象名称前缀 + DurationSeconds int64 // 分享过期时间,单位为秒,最小 900 秒,最长 7200 秒 + ExtractCode string // 提取码,必须给出 6 个字符,仅大小写字母和数字 + Permission string // 权限,目前仅支持 READONLY,未来会支持 READWRITE +} + +// 新创建的分享参数 +type NewShareParams = Request +type jsonRequest struct { + Bucket string `json:"bucket"` // 分享的空间名称 + Prefix string `json:"prefix"` // 分享的对象名称前缀 + DurationSeconds int64 `json:"duration_seconds"` // 分享过期时间,单位为秒,最小 900 秒,最长 7200 秒 + ExtractCode string `json:"extract_code"` // 提取码,必须给出 6 个字符,仅大小写字母和数字 + Permission string `json:"permission"` // 权限,目前仅支持 READONLY,未来会支持 READWRITE +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{Bucket: j.Bucket, Prefix: j.Prefix, DurationSeconds: j.DurationSeconds, ExtractCode: j.ExtractCode, Permission: j.Permission}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Bucket = nj.Bucket + j.Prefix = nj.Prefix + j.DurationSeconds = nj.DurationSeconds + j.ExtractCode = nj.ExtractCode + j.Permission = nj.Permission + return nil +} +func (j *Request) validate() error { + if j.Bucket == "" { + return errors.MissingRequiredFieldError{Name: "Bucket"} + } + if j.Prefix == "" { + return errors.MissingRequiredFieldError{Name: "Prefix"} + } + if j.DurationSeconds == 0 { + return errors.MissingRequiredFieldError{Name: "DurationSeconds"} + } + if j.ExtractCode == "" { + return errors.MissingRequiredFieldError{Name: "ExtractCode"} + } + if j.Permission == "" { + return errors.MissingRequiredFieldError{Name: "Permission"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct { + Id string // 分享 ID + Token string // 分享 Token + Expires string // 分享过期时间,遵循 ISO8601 风格,使用 UTC 0 时区时间 +} + +// 返回的分享信息 +type NewShareInfo = Response +type jsonResponse struct { + Id string `json:"id"` // 分享 ID + Token string `json:"token"` // 分享 Token + Expires string `json:"expires"` // 分享过期时间,遵循 ISO8601 风格,使用 UTC 0 时区时间 +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Id: j.Id, Token: j.Token, Expires: j.Expires}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Id = nj.Id + j.Token = nj.Token + j.Expires = nj.Expires + return nil +} +func (j *Response) validate() error { + if j.Id == "" { + return errors.MissingRequiredFieldError{Name: "Id"} + } + if j.Token == "" { + return errors.MissingRequiredFieldError{Name: "Token"} + } + if j.Expires == "" { + return errors.MissingRequiredFieldError{Name: "Expires"} + } + return nil +} diff --git a/storagev2/apis/get_bucket_quota/api.go b/storagev2/apis/get_bucket_quota/api.go index 3964cb5c..45af282f 100644 --- a/storagev2/apis/get_bucket_quota/api.go +++ b/storagev2/apis/get_bucket_quota/api.go @@ -19,6 +19,9 @@ type Response struct { Size int64 // 空间存储量配额 Count int64 // 空间文件数配额 } + +// Bucket 配额信息 +type BucketQuota = Response type jsonResponse struct { Size int64 `json:"size,omitempty"` // 空间存储量配额 Count int64 `json:"count,omitempty"` // 空间文件数配额 diff --git a/storagev2/apis/set_bucket_remark/api.go b/storagev2/apis/set_bucket_remark/api.go index a4b5c826..d57b4bd4 100644 --- a/storagev2/apis/set_bucket_remark/api.go +++ b/storagev2/apis/set_bucket_remark/api.go @@ -15,6 +15,9 @@ type Request struct { Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider Remark string // 空间备注信息, 字符长度不能超过 100, 允许为空 } + +// 空间备注信息 +type BucketRemark = Request type jsonRequest struct { Remark string `json:"remark"` // 空间备注信息, 字符长度不能超过 100, 允许为空 } diff --git a/storagev2/apis/verify_share/api.go b/storagev2/apis/verify_share/api.go new file mode 100644 index 00000000..966430b8 --- /dev/null +++ b/storagev2/apis/verify_share/api.go @@ -0,0 +1,128 @@ +// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY! + +// 校验目录分享并提取分享信息 +package verify_share + +import ( + "encoding/json" + credentials "github.com/qiniu/go-sdk/v7/storagev2/credentials" + errors "github.com/qiniu/go-sdk/v7/storagev2/errors" +) + +// 调用 API 所用的请求 +type Request struct { + ShareId string // 分享 ID + Token string // 分享 Token + Credentials credentials.CredentialsProvider // 鉴权参数,用于生成鉴权凭证,如果为空,则使用 HTTPClientOptions 中的 CredentialsProvider + ExtractCode string // 提取码 +} +type jsonRequest struct { + ExtractCode string `json:"extract_code"` // 提取码 +} + +func (j *Request) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonRequest{ExtractCode: j.ExtractCode}) +} +func (j *Request) UnmarshalJSON(data []byte) error { + var nj jsonRequest + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.ExtractCode = nj.ExtractCode + return nil +} +func (j *Request) validate() error { + if j.ExtractCode == "" { + return errors.MissingRequiredFieldError{Name: "ExtractCode"} + } + return nil +} + +// 获取 API 所用的响应 +type Response struct { + Endpoint string // 空间所用的 S3 域名 + Region string // 空间所在的 S3 区域 ID + BucketName string // 空间名称 + BucketId string // 空间 ID + Prefix string // 被分享的目录路径 + Permission string // 权限,目前仅支持 READONLY,未来会支持 READWRITE + Expires string // 分享过期时间,遵循 ISO8601 风格,使用 UTC 0 时区时间 + FederatedAk string // S3 STS Access Key + FederatedSk string // S3 STS Secret Key + SessionToken string // S3 STS Session Token +} + +// 返回的经过校验的分享信息 +type VerifiedShareInfo = Response +type jsonResponse struct { + Endpoint string `json:"endpoint"` // 空间所用的 S3 域名 + Region string `json:"region"` // 空间所在的 S3 区域 ID + BucketName string `json:"bucket_name"` // 空间名称 + BucketId string `json:"bucket_id"` // 空间 ID + Prefix string `json:"prefix"` // 被分享的目录路径 + Permission string `json:"permission"` // 权限,目前仅支持 READONLY,未来会支持 READWRITE + Expires string `json:"expires"` // 分享过期时间,遵循 ISO8601 风格,使用 UTC 0 时区时间 + FederatedAk string `json:"federated_ak"` // S3 STS Access Key + FederatedSk string `json:"federated_sk"` // S3 STS Secret Key + SessionToken string `json:"session_token"` // S3 STS Session Token +} + +func (j *Response) MarshalJSON() ([]byte, error) { + if err := j.validate(); err != nil { + return nil, err + } + return json.Marshal(&jsonResponse{Endpoint: j.Endpoint, Region: j.Region, BucketName: j.BucketName, BucketId: j.BucketId, Prefix: j.Prefix, Permission: j.Permission, Expires: j.Expires, FederatedAk: j.FederatedAk, FederatedSk: j.FederatedSk, SessionToken: j.SessionToken}) +} +func (j *Response) UnmarshalJSON(data []byte) error { + var nj jsonResponse + if err := json.Unmarshal(data, &nj); err != nil { + return err + } + j.Endpoint = nj.Endpoint + j.Region = nj.Region + j.BucketName = nj.BucketName + j.BucketId = nj.BucketId + j.Prefix = nj.Prefix + j.Permission = nj.Permission + j.Expires = nj.Expires + j.FederatedAk = nj.FederatedAk + j.FederatedSk = nj.FederatedSk + j.SessionToken = nj.SessionToken + return nil +} +func (j *Response) validate() error { + if j.Endpoint == "" { + return errors.MissingRequiredFieldError{Name: "Endpoint"} + } + if j.Region == "" { + return errors.MissingRequiredFieldError{Name: "Region"} + } + if j.BucketName == "" { + return errors.MissingRequiredFieldError{Name: "BucketName"} + } + if j.BucketId == "" { + return errors.MissingRequiredFieldError{Name: "BucketId"} + } + if j.Prefix == "" { + return errors.MissingRequiredFieldError{Name: "Prefix"} + } + if j.Permission == "" { + return errors.MissingRequiredFieldError{Name: "Permission"} + } + if j.Expires == "" { + return errors.MissingRequiredFieldError{Name: "Expires"} + } + if j.FederatedAk == "" { + return errors.MissingRequiredFieldError{Name: "FederatedAk"} + } + if j.FederatedSk == "" { + return errors.MissingRequiredFieldError{Name: "FederatedSk"} + } + if j.SessionToken == "" { + return errors.MissingRequiredFieldError{Name: "SessionToken"} + } + return nil +} diff --git a/storagev2/doc.go b/storagev2/doc.go index 058d8ea4..16eee04b 100644 --- a/storagev2/doc.go +++ b/storagev2/doc.go @@ -1,4 +1,5 @@ // storagev2 包提供了资源管理等功能。 package storagev2 -//go:generate go run ./internal/api-generator +//go:generate go run ../internal/api-generator -- --api-specs=../api-specs/storage --api-specs=internal/api-specs --output=apis/ --struct-name=Storage --api-package=github.com/qiniu/go-sdk/v7/storagev2/apis +//go:generate go build ./apis/... diff --git a/storagev2/downloader/download_manager.go b/storagev2/downloader/download_manager.go index fc1ea38b..beb37d0d 100644 --- a/storagev2/downloader/download_manager.go +++ b/storagev2/downloader/download_manager.go @@ -191,12 +191,16 @@ func (downloadManager *DownloadManager) DownloadDirectory(ctx context.Context, t var object objects.ObjectDetails for lister.Next(&object) { objectName := object.Name + if options.ShouldDownloadObject != nil && !options.ShouldDownloadObject(objectName) { + continue + } + relativePath := strings.TrimPrefix(objectName, options.ObjectPrefix) if pathSeparator != string(filepath.Separator) { relativePath = strings.Replace(relativePath, pathSeparator, string(filepath.Separator), -1) } fullPath := filepath.Join(targetDirPath, relativePath) - if strings.HasSuffix(relativePath, string(filepath.Separator)) { + if relativePath == "" || strings.HasSuffix(relativePath, string(filepath.Separator)) { if err = os.MkdirAll(fullPath, 0700); err != nil { return err } @@ -219,9 +223,6 @@ func (downloadManager *DownloadManager) DownloadDirectory(ctx context.Context, t }, DownloadURLsProvider: options.DownloadURLsProvider, } - if options.ShouldDownloadObject != nil && !options.ShouldDownloadObject(objectName) { - return nil - } if options.BeforeObjectDownload != nil { options.BeforeObjectDownload(objectName, &objectOptions) } @@ -260,6 +261,7 @@ func (downloadManager *DownloadManager) initDownloadURLsProvider(ctx context.Con AfterBackoff: downloadManager.options.AfterBackoff, BeforeRequest: downloadManager.options.BeforeRequest, AfterResponse: downloadManager.options.AfterResponse, + AccelerateUploading: downloadManager.options.AccelerateUploading, } if hostRetryConfig := downloadManager.options.HostRetryConfig; hostRetryConfig != nil { bucketRegionsQueryOptions.RetryMax = hostRetryConfig.RetryMax diff --git a/storagev2/downloader/download_manager_test.go b/storagev2/downloader/download_manager_test.go index b45f899a..d4927829 100644 --- a/storagev2/downloader/download_manager_test.go +++ b/storagev2/downloader/download_manager_test.go @@ -14,6 +14,7 @@ import ( "os" "path/filepath" "strconv" + "strings" "testing" "time" @@ -142,3 +143,217 @@ func TestDownloadManagerDownloadDirectory(t *testing.T) { t.Fatalf("unexpected file size: test2/file2") } } + +func TestDownloadManagerDownloadDirectoryWithPrefix(t *testing.T) { + rsfMux := http.NewServeMux() + rsfMux.HandleFunc("/list", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Fatalf("unexpected method") + } + w.Header().Set("Content-Type", "application/json") + query := r.URL.Query() + if query.Get("bucket") != "bucket1" { + t.Fatalf("unexpected bucket") + } + if query.Get("prefix") != "test1/" { + t.Fatalf("unexpected prefix") + } + if query.Get("limit") != "" { + t.Fatalf("unexpected limit") + } + jsonData, err := json.Marshal(&get_objects.Response{ + Items: []get_objects.ListedObjectEntry{{ + Key: "test1/", + PutTime: time.Now().UnixNano() / 100, + Hash: "testhash1", + Size: 0, + MimeType: "application/octet-stream", + }, { + Key: "test1/file1", + PutTime: time.Now().UnixNano() / 100, + Hash: "testhash1", + Size: 4 * 1024 * 1024, + MimeType: "application/json", + }}, + }) + if err != nil { + t.Fatal(err) + } + w.Header().Add("X-ReqId", "fakereqid") + w.Write(jsonData) + }) + rsfServer := httptest.NewServer(rsfMux) + defer rsfServer.Close() + + ioMux := http.NewServeMux() + ioMux.HandleFunc("/test1/file1", func(w http.ResponseWriter, r *http.Request) { + rander := rand.New(rand.NewSource(time.Now().UnixNano())) + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Add("X-ReqId", "fakereqid") + switch r.Method { + case http.MethodHead: + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(4*1024*1024)) + w.Header().Set("ETag", "testetag1") + case http.MethodGet: + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(4*1024*1024)) + w.Header().Set("ETag", "testetag1") + io.CopyN(w, rander, 4*1024*1024) + default: + t.Fatalf("unexpected method") + } + }) + ioServer := httptest.NewServer(ioMux) + defer ioServer.Close() + + tmpDir, err := ioutil.TempDir("", "") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(tmpDir) + + downloadManager := downloader.NewDownloadManager(&downloader.DownloadManagerOptions{ + Options: http_client.Options{ + Regions: ®ion.Region{ + Rsf: region.Endpoints{Preferred: []string{rsfServer.URL}}, + }, + Credentials: credentials.NewCredentials("testaccesskey", "testsecretkey"), + UseInsecureProtocol: true, + }, + DestinationDownloader: downloader.NewConcurrentDownloader(&downloader.ConcurrentDownloaderOptions{ + Concurrency: 1, + PartSize: 10 * 1024 * 1024, + }), + }) + if err = downloadManager.DownloadDirectory(context.Background(), tmpDir, &downloader.DirectoryOptions{ + UseInsecureProtocol: true, + BucketName: "bucket1", + ObjectPrefix: "test1/", + DownloadURLsProvider: downloader.NewStaticDomainBasedURLsProvider([]string{ioServer.URL}), + }); err != nil { + t.Fatal(err) + } + if fileInfo, err := os.Stat(filepath.Join(tmpDir, "file1")); err != nil { + t.Fatal(err) + } else if fileInfo.Size() != 4*1024*1024 { + t.Fatalf("unexpected file size: file1") + } +} + +func TestDownloadManagerDownloadDirectoryWithFilter(t *testing.T) { + rsfMux := http.NewServeMux() + rsfMux.HandleFunc("/list", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Fatalf("unexpected method") + } + w.Header().Set("Content-Type", "application/json") + query := r.URL.Query() + if query.Get("bucket") != "bucket1" { + t.Fatalf("unexpected bucket") + } + if query.Get("prefix") != "" { + t.Fatalf("unexpected prefix") + } + if query.Get("limit") != "" { + t.Fatalf("unexpected limit") + } + jsonData, err := json.Marshal(&get_objects.Response{ + Items: []get_objects.ListedObjectEntry{{ + Key: "test1/", + PutTime: time.Now().UnixNano() / 100, + Hash: "testhash1", + Size: 0, + MimeType: "application/octet-stream", + }, { + Key: "test1/file1", + PutTime: time.Now().UnixNano() / 100, + Hash: "testhash1", + Size: 4 * 1024 * 1024, + MimeType: "application/json", + }, { + Key: "test2/", + PutTime: time.Now().UnixNano() / 100, + Hash: "testhash2", + Size: 0, + MimeType: "application/octet-stream", + }, { + Key: "test2/file2", + PutTime: time.Now().UnixNano() / 100, + Hash: "testhash2", + Size: 4 * 1024 * 1024, + MimeType: "application/json", + }}, + }) + if err != nil { + t.Fatal(err) + } + w.Header().Add("X-ReqId", "fakereqid") + w.Write(jsonData) + }) + rsfServer := httptest.NewServer(rsfMux) + defer rsfServer.Close() + + ioMux := http.NewServeMux() + ioMux.HandleFunc("/test1/file1", func(w http.ResponseWriter, r *http.Request) { + rander := rand.New(rand.NewSource(time.Now().UnixNano())) + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Add("X-ReqId", "fakereqid") + switch r.Method { + case http.MethodHead: + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(4*1024*1024)) + w.Header().Set("ETag", "testetag1") + case http.MethodGet: + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(4*1024*1024)) + w.Header().Set("ETag", "testetag1") + io.CopyN(w, rander, 4*1024*1024) + default: + t.Fatalf("unexpected method") + } + }) + ioServer := httptest.NewServer(ioMux) + defer ioServer.Close() + + tmpDir, err := ioutil.TempDir("", "") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(tmpDir) + + downloadManager := downloader.NewDownloadManager(&downloader.DownloadManagerOptions{ + Options: http_client.Options{ + Regions: ®ion.Region{ + Rsf: region.Endpoints{Preferred: []string{rsfServer.URL}}, + }, + Credentials: credentials.NewCredentials("testaccesskey", "testsecretkey"), + UseInsecureProtocol: true, + }, + DestinationDownloader: downloader.NewConcurrentDownloader(&downloader.ConcurrentDownloaderOptions{ + Concurrency: 1, + PartSize: 10 * 1024 * 1024, + }), + }) + if err = downloadManager.DownloadDirectory(context.Background(), tmpDir, &downloader.DirectoryOptions{ + UseInsecureProtocol: true, + BucketName: "bucket1", + DownloadURLsProvider: downloader.NewStaticDomainBasedURLsProvider([]string{ioServer.URL}), + ShouldDownloadObject: func(objectName string) bool { + return strings.HasPrefix(objectName, "test1/") + }, + }); err != nil { + t.Fatal(err) + } + if fileInfo, err := os.Stat(filepath.Join(tmpDir, "test1", "file1")); err != nil { + t.Fatal(err) + } else if fileInfo.Size() != 4*1024*1024 { + t.Fatalf("unexpected file size: test1/file1") + } + if _, err = os.Stat(filepath.Join(tmpDir, "test2")); err == nil { + t.Fatalf("unexpected test2/") + } + if _, err = os.Stat(filepath.Join(tmpDir, "test2", "file2")); err == nil { + t.Fatalf("unexpected test2/file2") + } +} diff --git a/storagev2/downloader/urls_provider_test.go b/storagev2/downloader/urls_provider_test.go index 836c4171..49e778af 100644 --- a/storagev2/downloader/urls_provider_test.go +++ b/storagev2/downloader/urls_provider_test.go @@ -10,7 +10,6 @@ import ( "io/ioutil" "net/http" "net/http/httptest" - "net/url" "os" "sync/atomic" "testing" @@ -28,25 +27,24 @@ func TestStaticDomainBasedURLsProvider(t *testing.T) { "testc.com", }) - urlsIter, err := generator.GetURLsIter(context.Background(), "/!@#$%^&*()?", &downloader.GenerateOptions{ + urls, err := downloader.GetURLStrings(context.Background(), generator, "/!@#$%^&*()?", &downloader.GenerateOptions{ Command: "test1|test2", }) if err != nil { t.Fatal(err) } - if peekURLsIter(t, urlsIter) != "http://testa.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { + if len(urls) != 3 { + t.Fatalf("unexpected urls count") + } + if urls[0] != "http://testa.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { t.Fatalf("unexpected generated url") } - urlsIter.Next() - if peekURLsIter(t, urlsIter) != "https://b.testb.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { + if urls[1] != "https://b.testb.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { t.Fatalf("unexpected generated url") } - urlsIter.Next() - if peekURLsIter(t, urlsIter) != "https://testc.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { + if urls[2] != "https://testc.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { t.Fatalf("unexpected generated url") } - urlsIter.Next() - assertURLsIterIsConsumed(t, urlsIter) } func TestDefaultSrcURLsProvider(t *testing.T) { @@ -95,18 +93,19 @@ func TestDefaultSrcURLsProvider(t *testing.T) { BucketHosts: region.Endpoints{Preferred: []string{server.URL}}, }, ) - urlsIter, err := urlsProvider.GetURLsIter(context.Background(), "/!@#$%^&*()?", &downloader.GenerateOptions{ + urls, err := downloader.GetURLStrings(context.Background(), urlsProvider, "/!@#$%^&*()?", &downloader.GenerateOptions{ BucketName: bucketName, Command: "test1|test2", }) if err != nil { t.Fatal(err) } - if peekURLsIter(t, urlsIter) != "https://fakebucket.cn-east-1.qiniucs.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { + if len(urls) != 1 { + t.Fatalf("unexpected urls count") + } + if urls[0] != "https://fakebucket.cn-east-1.qiniucs.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { t.Fatalf("unexpected generated url") } - urlsIter.Next() - assertURLsIterIsConsumed(t, urlsIter) } func TestDomainsQueryURLsProvider(t *testing.T) { @@ -148,43 +147,24 @@ func TestDomainsQueryURLsProvider(t *testing.T) { t.Fatal(err) } for i := 0; i < 2; i++ { - urlsIter, err := generator.GetURLsIter(context.Background(), "/!@#$%^&*()?", &downloader.GenerateOptions{ + urls, err := downloader.GetURLStrings(context.Background(), generator, "/!@#$%^&*()?", &downloader.GenerateOptions{ BucketName: bucketName, Command: "test1|test2", }) if err != nil { t.Fatal(err) } - if peekURLsIter(t, urlsIter) != "https://domain1.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { + if len(urls) != 2 { + t.Fatalf("unexpected urls count") + } + if urls[0] != "https://domain1.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { t.Fatalf("unexpected generated url") } - urlsIter.Next() - if peekURLsIter(t, urlsIter) != "https://domain2.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { + if urls[1] != "https://domain2.com//%21@%23$%25%5E&%2A%28%29%3F?test1|test2" { t.Fatalf("unexpected generated url") } - urlsIter.Next() - assertURLsIterIsConsumed(t, urlsIter) } if atomic.LoadUint64(&callCount) != 1 { t.Fatalf("unexpected call count") } } - -func peekURLsIter(t *testing.T, urlsIter downloader.URLsIter) string { - var u url.URL - if ok, err := urlsIter.Peek(&u); err != nil { - t.Fatal(err) - } else if !ok { - t.Fatalf("unexpected empty urls iter") - } - return u.String() -} - -func assertURLsIterIsConsumed(t *testing.T, urlsIter downloader.URLsIter) { - var u url.URL - if ok, err := urlsIter.Peek(&u); err != nil { - t.Fatal(err) - } else if ok { - t.Fatalf("urls iter should be consumed") - } -} diff --git a/storagev2/downloader/urls_provider_utils.go b/storagev2/downloader/urls_provider_utils.go new file mode 100644 index 00000000..79024d75 --- /dev/null +++ b/storagev2/downloader/urls_provider_utils.go @@ -0,0 +1,40 @@ +package downloader + +import ( + "context" + "net/url" +) + +// GetURLs 从 DownloadURLsProvider 读取出所有 URL 返回 +func GetURLs(ctx context.Context, provider DownloadURLsProvider, objectName string, options *GenerateOptions) ([]*url.URL, error) { + var ok bool + + iter, err := provider.GetURLsIter(ctx, objectName, options) + if err != nil { + return nil, err + } + urls := make([]*url.URL, 0, 16) + for { + u := new(url.URL) + ok, err = iter.Peek(u) + if err != nil || !ok { + break + } + urls = append(urls, u) + iter.Next() + } + return urls, nil +} + +// GetURLStrings 从 DownloadURLsProvider 读取出所有 URL 并转换成字符串返回 +func GetURLStrings(ctx context.Context, provider DownloadURLsProvider, objectName string, options *GenerateOptions) ([]string, error) { + urls, err := GetURLs(ctx, provider, objectName, options) + if err != nil { + return nil, err + } + strs := make([]string, len(urls)) + for i, u := range urls { + strs[i] = u.String() + } + return strs, nil +} diff --git a/storagev2/http_client/http_client.go b/storagev2/http_client/http_client.go index a330af07..39215b93 100644 --- a/storagev2/http_client/http_client.go +++ b/storagev2/http_client/http_client.go @@ -40,27 +40,29 @@ type ( // Client 提供了对七牛 HTTP 客户端 Client struct { - useHttps bool - basicHTTPClient BasicHTTPClient - bucketQuery region.BucketRegionsQuery - regions region.RegionsProvider - credentials credentials.CredentialsProvider - resolver resolver.Resolver - chooser chooser.Chooser - hostRetryConfig *RetryConfig - hostsRetryConfig *RetryConfig - hostFreezeDuration time.Duration - shouldFreezeHost func(req *http.Request, resp *http.Response, err error) bool - beforeSign func(req *http.Request) - afterSign func(req *http.Request) - signError func(req *http.Request, err error) - beforeResolve func(*http.Request) - afterResolve func(*http.Request, []net.IP) - resolveError func(*http.Request, error) - beforeBackoff func(*http.Request, *retrier.RetrierOptions, time.Duration) - afterBackoff func(*http.Request, *retrier.RetrierOptions, time.Duration) - beforeRequest func(*http.Request, *retrier.RetrierOptions) - afterResponse func(*http.Response, *retrier.RetrierOptions, error) + useHttps bool + accelerateUploading bool + basicHTTPClient BasicHTTPClient + bucketQuery region.BucketRegionsQuery + allRegions region.RegionsProvider + regions region.RegionsProvider + credentials credentials.CredentialsProvider + resolver resolver.Resolver + chooser chooser.Chooser + hostRetryConfig *RetryConfig + hostsRetryConfig *RetryConfig + hostFreezeDuration time.Duration + shouldFreezeHost func(req *http.Request, resp *http.Response, err error) bool + beforeSign func(req *http.Request) + afterSign func(req *http.Request) + signError func(req *http.Request, err error) + beforeResolve func(*http.Request) + afterResolve func(*http.Request, []net.IP) + resolveError func(*http.Request, error) + beforeBackoff func(*http.Request, *retrier.RetrierOptions, time.Duration) + afterBackoff func(*http.Request, *retrier.RetrierOptions, time.Duration) + beforeRequest func(*http.Request, *retrier.RetrierOptions) + afterResponse func(*http.Response, *retrier.RetrierOptions, error) } // Options 为构建 Client 提供了可选参数 @@ -71,6 +73,9 @@ type ( // 空间区域查询器 BucketQuery region.BucketRegionsQuery + // 所有区域提供者 + AllRegions region.RegionsProvider + // 区域提供者 Regions region.RegionsProvider @@ -130,6 +135,9 @@ type ( // 请求后回调函数 AfterResponse func(*http.Response, *retrier.RetrierOptions, error) + + // 是否加速上传 + AccelerateUploading bool } // Request 包含一个具体的 HTTP 请求的参数 @@ -205,27 +213,29 @@ func NewClient(options *Options) *Client { } return &Client{ - useHttps: !options.UseInsecureProtocol, - basicHTTPClient: clientv2.NewClient(options.BasicHTTPClient, options.Interceptors...), - bucketQuery: options.BucketQuery, - regions: options.Regions, - credentials: creds, - resolver: options.Resolver, - chooser: options.Chooser, - hostRetryConfig: options.HostRetryConfig, - hostsRetryConfig: options.HostsRetryConfig, - hostFreezeDuration: hostFreezeDuration, - shouldFreezeHost: shouldFreezeHost, - beforeSign: options.BeforeSign, - afterSign: options.AfterSign, - signError: options.SignError, - beforeResolve: options.BeforeResolve, - afterResolve: options.AfterResolve, - resolveError: options.ResolveError, - beforeBackoff: options.BeforeBackoff, - afterBackoff: options.AfterBackoff, - beforeRequest: options.BeforeRequest, - afterResponse: options.AfterResponse, + useHttps: !options.UseInsecureProtocol, + accelerateUploading: options.AccelerateUploading, + basicHTTPClient: clientv2.NewClient(options.BasicHTTPClient, options.Interceptors...), + bucketQuery: options.BucketQuery, + allRegions: options.AllRegions, + regions: options.Regions, + credentials: creds, + resolver: options.Resolver, + chooser: options.Chooser, + hostRetryConfig: options.HostRetryConfig, + hostsRetryConfig: options.HostsRetryConfig, + hostFreezeDuration: hostFreezeDuration, + shouldFreezeHost: shouldFreezeHost, + beforeSign: options.BeforeSign, + afterSign: options.AfterSign, + signError: options.SignError, + beforeResolve: options.BeforeResolve, + afterResolve: options.AfterResolve, + resolveError: options.ResolveError, + beforeBackoff: options.BeforeBackoff, + afterBackoff: options.AfterBackoff, + beforeRequest: options.BeforeRequest, + afterResponse: options.AfterResponse, } } @@ -246,23 +256,14 @@ func (httpClient *Client) Do(ctx context.Context, request *Request) (*http.Respo if credentialsProvider == nil { credentialsProvider = httpClient.credentials } - if credentialsProvider == nil { - if defaultCreds := credentials.Default(); defaultCreds != nil { - credentialsProvider = defaultCreds - } - } if credentialsProvider != nil { - if creds, err := credentialsProvider.Get(ctx); err != nil { - return nil, err - } else { - req = clientv2.WithInterceptors(req, clientv2.NewAuthInterceptor(clientv2.AuthConfig{ - Credentials: creds, - TokenType: request.AuthType, - BeforeSign: httpClient.beforeSign, - AfterSign: httpClient.afterSign, - SignError: httpClient.signError, - })) - } + req = clientv2.WithInterceptors(req, clientv2.NewAuthInterceptor(clientv2.AuthConfig{ + Credentials: credentialsProvider, + TokenType: request.AuthType, + BeforeSign: httpClient.beforeSign, + AfterSign: httpClient.afterSign, + SignError: httpClient.signError, + })) } } } @@ -281,6 +282,10 @@ func (httpClient *Client) DoAndAcceptJSON(ctx context.Context, request *Request, } } +func (httpClient *Client) AccelerateUploadingEnabled() bool { + return httpClient.accelerateUploading +} + func (httpClient *Client) GetBucketQuery() region.BucketRegionsQuery { return httpClient.bucketQuery } @@ -289,6 +294,10 @@ func (httpClient *Client) GetCredentials() credentials.CredentialsProvider { return httpClient.credentials } +func (httpClient *Client) GetAllRegions() region.RegionsProvider { + return httpClient.allRegions +} + func (httpClient *Client) GetRegions() region.RegionsProvider { return httpClient.regions } @@ -321,6 +330,18 @@ func (httpClient *Client) GetChooser() chooser.Chooser { return httpClient.chooser } +func (httpClient *Client) GetBeforeSignCallback() func(*http.Request) { + return httpClient.beforeSign +} + +func (httpClient *Client) GetAfterSignCallback() func(*http.Request) { + return httpClient.afterSign +} + +func (httpClient *Client) GetSignErrorCallback() func(*http.Request, error) { + return httpClient.signError +} + func (httpClient *Client) GetBeforeResolveCallback() func(*http.Request) { return httpClient.beforeResolve } @@ -361,7 +382,7 @@ func (httpClient *Client) getEndpoints(ctx context.Context, request *Request) (r return region.Endpoints{}, ErrNoRegion } r := rs[0] - return r.Endpoints(request.ServiceNames) + return r.Endpoints(serviceNames) } if request.Endpoints != nil { return getEndpointsFromEndpointsProvider(ctx, request.Endpoints) @@ -391,7 +412,7 @@ func (httpClient *Client) makeReq(ctx context.Context, request *Request) (*http. hostsRetryConfig = *httpClient.hostsRetryConfig } if hostsRetryConfig.RetryMax <= 0 { - hostsRetryConfig.RetryMax = len(endpoints.Preferred) + len(endpoints.Alternative) + hostsRetryConfig.RetryMax = endpoints.HostsLength() } if hostsRetryConfig.Retrier == nil { hostsRetryConfig.Retrier = retrier.NewErrorRetrier() diff --git a/storagev2/region/all.go b/storagev2/region/all.go new file mode 100644 index 00000000..c2851afd --- /dev/null +++ b/storagev2/region/all.go @@ -0,0 +1,223 @@ +package region + +import ( + "context" + "fmt" + "math" + "net" + "net/http" + "os" + "path/filepath" + "time" + + "github.com/qiniu/go-sdk/v7/internal/cache" + "github.com/qiniu/go-sdk/v7/internal/clientv2" + "github.com/qiniu/go-sdk/v7/storagev2/backoff" + "github.com/qiniu/go-sdk/v7/storagev2/chooser" + "github.com/qiniu/go-sdk/v7/storagev2/credentials" + "github.com/qiniu/go-sdk/v7/storagev2/resolver" + "github.com/qiniu/go-sdk/v7/storagev2/retrier" +) + +type ( + allRegionsProvider struct { + credentials credentials.CredentialsProvider + bucketHosts Endpoints + cache *cache.Cache + client clientv2.Client + useHttps bool + } + + // AllRegionsProviderOptions 所有区域提供者选项 + AllRegionsProviderOptions struct { + // 使用 HTTP 协议 + UseInsecureProtocol bool + + // 压缩周期(默认:60s) + CompactInterval time.Duration + + // 持久化路径(默认:$TMPDIR/qiniu-golang-sdk/regions_v4_01.cache.json) + PersistentFilePath string + + // 持久化周期(默认:60s) + PersistentDuration time.Duration + + // 单域名重试次数(默认:2) + RetryMax int + + // 主备域名冻结时间(默认:600s),当一个域名请求失败(单个域名会被重试 RetryMax 次),会被冻结一段时间,使用备用域名进行重试,在冻结时间内,域名不能被使用,当一个操作中所有域名竣备冻结操作不在进行重试,返回最后一次操作的错误。 + HostFreezeDuration time.Duration + + // HTTP 客户端,如果不配置则使用默认的 HTTP 客户端 + Client clientv2.Client + + // 域名解析器,如果不配置则使用默认的域名解析器 + Resolver resolver.Resolver + + // 域名选择器,如果不配置则使用默认的域名选择器 + Chooser chooser.Chooser + + // 退避器,如果不配置则使用默认的退避器 + Backoff backoff.Backoff + + // 签名前回调函数 + BeforeSign func(*http.Request) + + // 签名后回调函数 + AfterSign func(*http.Request) + + // 签名错误回调函数 + SignError func(*http.Request, error) + + // 域名解析前回调函数 + BeforeResolve func(*http.Request) + + // 域名解析后回调函数 + AfterResolve func(*http.Request, []net.IP) + + // 域名解析错误回调函数 + ResolveError func(*http.Request, error) + + // 退避前回调函数 + BeforeBackoff func(*http.Request, *retrier.RetrierOptions, time.Duration) + + // 退避后回调函数 + AfterBackoff func(*http.Request, *retrier.RetrierOptions, time.Duration) + + // 请求前回调函数 + BeforeRequest func(*http.Request, *retrier.RetrierOptions) + + // 请求后回调函数 + AfterResponse func(*http.Response, *retrier.RetrierOptions, error) + } + + singleRegion struct { + ID string `json:"id"` + Ttl int64 `json:"ttl"` + Io v4QueryServiceHosts `json:"io"` + Up v4QueryServiceHosts `json:"up"` + Rs v4QueryServiceHosts `json:"rs"` + Rsf v4QueryServiceHosts `json:"rsf"` + Api v4QueryServiceHosts `json:"api"` + Uc v4QueryServiceHosts `json:"uc"` + } + + regionsResponse struct { + Regions []singleRegion `json:"regions"` + } +) + +const allRegionsProviderCacheFileName = "regions_v4_01.cache.json" + +// NewAllRegionsProvider 创建所有空间提供者 +func NewAllRegionsProvider(credentials credentials.CredentialsProvider, bucketHosts Endpoints, opts *AllRegionsProviderOptions) (RegionsProvider, error) { + if opts == nil { + opts = &AllRegionsProviderOptions{} + } + retryMax := opts.RetryMax + if retryMax <= 0 { + retryMax = 2 + } + compactInterval := opts.CompactInterval + if compactInterval == time.Duration(0) { + compactInterval = time.Minute + } + persistentFilePath := opts.PersistentFilePath + if persistentFilePath == "" { + persistentFilePath = filepath.Join(os.TempDir(), "qiniu-golang-sdk", allRegionsProviderCacheFileName) + } + persistentDuration := opts.PersistentDuration + if persistentDuration == time.Duration(0) { + persistentDuration = time.Minute + } + + persistentCache, err := getPersistentCache(persistentFilePath, compactInterval, persistentDuration) + if err != nil { + return nil, err + } + + return &allRegionsProvider{ + credentials: credentials, + bucketHosts: bucketHosts, + cache: persistentCache, + client: makeBucketQueryClient( + opts.Client, + credentials, + bucketHosts, + !opts.UseInsecureProtocol, + retryMax, + opts.HostFreezeDuration, + opts.Resolver, + opts.Chooser, + opts.Backoff, + opts.BeforeResolve, + opts.AfterResolve, + opts.ResolveError, + opts.BeforeBackoff, + opts.AfterBackoff, + opts.BeforeRequest, + opts.AfterResponse, + opts.BeforeSign, + opts.AfterSign, + opts.SignError, + ), + useHttps: !opts.UseInsecureProtocol, + }, nil +} + +func (provider *allRegionsProvider) GetRegions(ctx context.Context) ([]*Region, error) { + creds, err := provider.credentials.Get(ctx) + if err != nil { + return nil, err + } + cacheValue, status := provider.cache.Get(makeRegionsProviderCacheKey(creds.AccessKey, provider.bucketHosts), func() (cache.CacheValue, error) { + var ret regionsResponse + url := provider.bucketHosts.firstUrl(provider.useHttps) + "/regions" + if err = clientv2.DoAndDecodeJsonResponse(provider.client, clientv2.RequestParams{ + Context: ctx, + Method: clientv2.RequestMethodGet, + Url: url, + BufferResponse: true, + }, &ret); err != nil { + return nil, err + } + return ret.toCacheValue(), nil + }) + if status == cache.NoResultGot { + return nil, err + } + return cacheValue.(*v4QueryCacheValue).Regions, nil +} + +func (response *regionsResponse) toCacheValue() *v4QueryCacheValue { + var ( + minTtl = int64(math.MaxInt64) + regions = make([]*Region, 0, len(response.Regions)) + ) + for _, host := range response.Regions { + regions = append(regions, host.toCacheValue()) + if host.Ttl < minTtl { + minTtl = host.Ttl + } + } + return &v4QueryCacheValue{ + Regions: regions, + ExpiredAt: time.Now().Add(time.Duration(minTtl) * time.Second), + } +} + +func (response *singleRegion) toCacheValue() *Region { + return &Region{ + RegionID: response.ID, + Up: response.Up.toCacheValue(), + Io: response.Io.toCacheValue(), + Rs: response.Rs.toCacheValue(), + Rsf: response.Rsf.toCacheValue(), + Api: response.Api.toCacheValue(), + Bucket: response.Uc.toCacheValue(), + } +} + +func makeRegionsProviderCacheKey(accessKey string, bucketHosts Endpoints) string { + return fmt.Sprintf("%s:%s", accessKey, makeBucketHostsCacheKey(bucketHosts)) +} diff --git a/storagev2/region/all_test.go b/storagev2/region/all_test.go new file mode 100644 index 00000000..3d3e2975 --- /dev/null +++ b/storagev2/region/all_test.go @@ -0,0 +1,137 @@ +//go:build unit +// +build unit + +package region + +import ( + "context" + "io" + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/qiniu/go-sdk/v7/storagev2/credentials" +) + +func TestAllRegionsProvider(t *testing.T) { + const accessKey = "fakeaccesskey" + const secretKey = "fakesecretkey" + var callCount uint64 + mux := http.NewServeMux() + mux.HandleFunc("/regions", func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.Header.Get("Authorization"), "Qiniu "+accessKey) { + t.Fatalf("unexpected authorization") + } + w.Header().Add("X-ReqId", "fakereqid") + if _, err := io.WriteString(w, mockUcRegionsResponseBody()); err != nil { + t.Fatal(err) + } + atomic.AddUint64(&callCount, 1) + }) + server := httptest.NewServer(mux) + defer server.Close() + + cacheFile, err := ioutil.TempFile("", "") + if err != nil { + t.Fatal(err) + } + defer os.Remove(cacheFile.Name()) + defer cacheFile.Close() + + provider, err := NewAllRegionsProvider(credentials.NewCredentials(accessKey, secretKey), Endpoints{Preferred: []string{server.URL}}, &AllRegionsProviderOptions{ + PersistentFilePath: cacheFile.Name(), + }) + if err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + regions, err := provider.GetRegions(context.Background()) + if err != nil { + t.Fatal(err) + } + if regionsCount := len(regions); regionsCount != 2 { + t.Fatalf("Unexpected regions count: %d", regionsCount) + } + if regionId := regions[0].RegionID; regionId != "z0" { + t.Fatalf("Unexpected regionId: %s", regionId) + } + if preferredUp := regions[0].Up.Preferred; !reflect.DeepEqual(preferredUp, []string{"upload.qiniup.com", "up.qiniup.com"}) { + t.Fatalf("Unexpected preferred up domains: %v", preferredUp) + } + if alternativeUp := regions[0].Up.Alternative; !reflect.DeepEqual(alternativeUp, []string{"upload.qbox.me", "up.qbox.me"}) { + t.Fatalf("Unexpected alternative up domains: %v", alternativeUp) + } + if regionId := regions[1].RegionID; regionId != "z1" { + t.Fatalf("Unexpected regionId: %s", regionId) + } + if preferredUp := regions[1].Up.Preferred; !reflect.DeepEqual(preferredUp, []string{"upload-z1.qiniup.com", "up-z1.qiniup.com"}) { + t.Fatalf("Unexpected preferred up domains: %v", preferredUp) + } + if alternativeUp := regions[1].Up.Alternative; !reflect.DeepEqual(alternativeUp, []string{"upload-z1.qbox.me", "up-z1.qbox.me"}) { + t.Fatalf("Unexpected alternative up domains: %v", alternativeUp) + } + } + if cc := atomic.LoadUint64(&callCount); cc != 1 { + t.Fatalf("Unexpected call count: %d", cc) + } +} + +func mockUcRegionsResponseBody() string { + return ` + { + "regions": [ + { + "id": "z0", + "ttl": 86400, + "io": { + "domains": ["iovip.qbox.me"] + }, + "up": { + "domains": ["upload.qiniup.com", "up.qiniup.com"], + "old": ["upload.qbox.me", "up.qbox.me"] + }, + "uc": { + "domains": ["uc.qbox.me"] + }, + "rs": { + "domains": ["rs-z0.qbox.me"] + }, + "rsf": { + "domains": ["rsf-z0.qbox.me"] + }, + "api": { + "domains": ["api.qiniu.com"] + } + }, + { + "id": "z1", + "ttl": 86400, + "io": { + "domains": ["iovip-z1.qbox.me"] + }, + "up": { + "domains": ["upload-z1.qiniup.com", "up-z1.qiniup.com"], + "old": ["upload-z1.qbox.me", "up-z1.qbox.me"] + }, + "uc": { + "domains": ["uc.qbox.me"] + }, + "rs": { + "domains": ["rs-z1.qbox.me"] + }, + "rsf": { + "domains": ["rsf-z1.qbox.me"] + }, + "api": { + "domains": ["api-z1.qiniu.com"] + } + } + ] + } + ` +} diff --git a/storagev2/region/query.go b/storagev2/region/query.go index 9bcca509..05c7d165 100644 --- a/storagev2/region/query.go +++ b/storagev2/region/query.go @@ -17,12 +17,14 @@ import ( "sync" "time" + "github.com/qiniu/go-sdk/v7/auth" "github.com/qiniu/go-sdk/v7/internal/cache" "github.com/qiniu/go-sdk/v7/internal/clientv2" "github.com/qiniu/go-sdk/v7/internal/hostprovider" "github.com/qiniu/go-sdk/v7/internal/log" "github.com/qiniu/go-sdk/v7/storagev2/backoff" "github.com/qiniu/go-sdk/v7/storagev2/chooser" + "github.com/qiniu/go-sdk/v7/storagev2/credentials" "github.com/qiniu/go-sdk/v7/storagev2/resolver" "github.com/qiniu/go-sdk/v7/storagev2/retrier" ) @@ -34,17 +36,21 @@ type ( } bucketRegionsQuery struct { - bucketHosts Endpoints - cache *cache.Cache - client clientv2.Client - useHttps bool + bucketHosts Endpoints + cache *cache.Cache + client clientv2.Client + useHttps bool + accelerateUploading bool } - // BucketRegionsQuery 空间区域查询器选项 + // BucketRegionsQueryOptions 空间区域查询器选项 BucketRegionsQueryOptions struct { // 使用 HTTP 协议 UseInsecureProtocol bool + // 是否加速上传 + AccelerateUploading bool + // 压缩周期(默认:60s) CompactInterval time.Duration @@ -95,10 +101,11 @@ type ( } bucketRegionsProvider struct { - accessKey string - bucketName string - cacheKey string - query *bucketRegionsQuery + accessKey string + bucketName string + cacheKey string + query *bucketRegionsQuery + accelerateUploading bool } v4QueryCacheValue struct { @@ -107,8 +114,9 @@ type ( } v4QueryServiceHosts struct { - Domains []string `json:"domains"` - Old []string `json:"old"` + Domains []string `json:"domains"` + Old []string `json:"old"` + AccDomains []string `json:"acc_domains"` } v4QueryRegion struct { @@ -128,7 +136,7 @@ type ( } ) -const cacheFileName = "query_v4_01.cache.json" +const bucketRegionsQueryCacheFileName = "query_v4_01.cache.json" var ( persistentCaches map[uint64]*cache.Cache @@ -150,7 +158,7 @@ func NewBucketRegionsQuery(bucketHosts Endpoints, opts *BucketRegionsQueryOption } persistentFilePath := opts.PersistentFilePath if persistentFilePath == "" { - persistentFilePath = filepath.Join(os.TempDir(), "qiniu-golang-sdk", cacheFileName) + persistentFilePath = filepath.Join(os.TempDir(), "qiniu-golang-sdk", bucketRegionsQueryCacheFileName) } persistentDuration := opts.PersistentDuration if persistentDuration == time.Duration(0) { @@ -166,7 +174,7 @@ func NewBucketRegionsQuery(bucketHosts Endpoints, opts *BucketRegionsQueryOption bucketHosts: bucketHosts, cache: persistentCache, client: makeBucketQueryClient( - opts.Client, + opts.Client, nil, bucketHosts, !opts.UseInsecureProtocol, retryMax, @@ -181,8 +189,10 @@ func NewBucketRegionsQuery(bucketHosts Endpoints, opts *BucketRegionsQueryOption opts.AfterBackoff, opts.BeforeRequest, opts.AfterResponse, + nil, nil, nil, ), - useHttps: !opts.UseInsecureProtocol, + useHttps: !opts.UseInsecureProtocol, + accelerateUploading: opts.AccelerateUploading, }, nil } @@ -220,10 +230,11 @@ func getPersistentCache(persistentFilePath string, compactInterval, persistentDu // Query 查询空间区域,返回 region.RegionsProvider func (query *bucketRegionsQuery) Query(accessKey, bucketName string) RegionsProvider { return &bucketRegionsProvider{ - accessKey: accessKey, - bucketName: bucketName, - query: query, - cacheKey: makeRegionCacheKey(accessKey, bucketName, query.bucketHosts), + accessKey: accessKey, + bucketName: bucketName, + query: query, + cacheKey: makeRegionCacheKey(accessKey, bucketName, query.accelerateUploading, query.bucketHosts), + accelerateUploading: query.accelerateUploading, } } @@ -233,13 +244,14 @@ func (provider *bucketRegionsProvider) GetRegions(ctx context.Context) ([]*Regio var ret v4QueryResponse url := fmt.Sprintf("%s/v4/query?ak=%s&bucket=%s", provider.query.bucketHosts.firstUrl(provider.query.useHttps), provider.accessKey, provider.bucketName) if err = clientv2.DoAndDecodeJsonResponse(provider.query.client, clientv2.RequestParams{ - Context: ctx, - Method: clientv2.RequestMethodGet, - Url: url, + Context: ctx, + Method: clientv2.RequestMethodGet, + Url: url, + BufferResponse: true, }, &ret); err != nil { return nil, err } - return ret.toCacheValue(), nil + return ret.toCacheValue(provider.accelerateUploading), nil }) if status == cache.NoResultGot { return nil, err @@ -266,13 +278,13 @@ func (left *v4QueryCacheValue) IsValid() bool { return time.Now().Before(left.ExpiredAt) } -func (response *v4QueryResponse) toCacheValue() *v4QueryCacheValue { +func (response *v4QueryResponse) toCacheValue(accelerateUploading bool) *v4QueryCacheValue { var ( minTtl = int64(math.MaxInt64) regions = make([]*Region, 0, len(response.Hosts)) ) for _, host := range response.Hosts { - regions = append(regions, host.toCacheValue()) + regions = append(regions, host.toCacheValue(accelerateUploading)) if host.Ttl < minTtl { minTtl = host.Ttl } @@ -283,8 +295,8 @@ func (response *v4QueryResponse) toCacheValue() *v4QueryCacheValue { } } -func (response *v4QueryRegion) toCacheValue() *Region { - return &Region{ +func (response *v4QueryRegion) toCacheValue(accelerateUploading bool) *Region { + region := Region{ RegionID: response.RegionId, Up: response.Up.toCacheValue(), Io: response.Io.toCacheValue(), @@ -294,21 +306,31 @@ func (response *v4QueryRegion) toCacheValue() *Region { Api: response.Api.toCacheValue(), Bucket: response.Uc.toCacheValue(), } + if !accelerateUploading { + region.Up.Accelerated = nil + } + + return ®ion } func (response *v4QueryServiceHosts) toCacheValue() Endpoints { return Endpoints{ + Accelerated: response.AccDomains, Preferred: response.Domains, Alternative: response.Old, } } -func makeRegionCacheKey(accessKey, bucketName string, bucketHosts Endpoints) string { - return fmt.Sprintf("%s:%s:%s", accessKey, bucketName, makeBucketHostsCacheKey(bucketHosts)) +func makeRegionCacheKey(accessKey, bucketName string, accelerateUploading bool, bucketHosts Endpoints) string { + enableAcceleration := uint8(0) + if accelerateUploading { + enableAcceleration = 1 + } + return fmt.Sprintf("%s:%s:%d:%s", accessKey, bucketName, enableAcceleration, makeBucketHostsCacheKey(bucketHosts)) } func makeBucketHostsCacheKey(serviceHosts Endpoints) string { - return fmt.Sprintf("%s:%s", makeHostsCacheKey(serviceHosts.Preferred), makeHostsCacheKey(serviceHosts.Alternative)) + return fmt.Sprintf("%s:%s:%s", makeHostsCacheKey(serviceHosts.Preferred), makeHostsCacheKey(serviceHosts.Alternative), makeHostsCacheKey(serviceHosts.Accelerated)) } func makeHostsCacheKey(hosts []string) string { @@ -319,6 +341,7 @@ func makeHostsCacheKey(hosts []string) string { func makeBucketQueryClient( client clientv2.Client, + credentials credentials.CredentialsProvider, bucketHosts Endpoints, useHttps bool, retryMax int, @@ -333,11 +356,13 @@ func makeBucketQueryClient( afterBackoff func(*http.Request, *retrier.RetrierOptions, time.Duration), beforeRequest func(*http.Request, *retrier.RetrierOptions), afterResponse func(*http.Response, *retrier.RetrierOptions, error), + beforeSign, afterSign func(*http.Request), + signError func(*http.Request, error), ) clientv2.Client { is := []clientv2.Interceptor{ clientv2.NewAntiHijackingInterceptor(), clientv2.NewHostsRetryInterceptor(clientv2.HostsRetryConfig{ - RetryMax: len(bucketHosts.Preferred) + len(bucketHosts.Alternative), + RetryMax: bucketHosts.HostsLength(), HostFreezeDuration: hostFreezeDuration, HostProvider: hostprovider.NewWithHosts(bucketHosts.allUrls(useHttps)), }), @@ -356,6 +381,15 @@ func makeBucketQueryClient( }), clientv2.NewBufferResponseInterceptor(), } + if credentials != nil { + is = append(is, clientv2.NewAuthInterceptor(clientv2.AuthConfig{ + Credentials: credentials, + TokenType: auth.TokenQiniu, + BeforeSign: beforeSign, + AfterSign: afterSign, + SignError: signError, + })) + } return clientv2.NewClient(client, is...) } diff --git a/storagev2/region/query_test.go b/storagev2/region/query_test.go index 197e75dc..51d02d7d 100644 --- a/storagev2/region/query_test.go +++ b/storagev2/region/query_test.go @@ -131,8 +131,7 @@ func mockUcQueryResponseBody() string { "domains": ["api-z1.qiniu.com"] } } - ], - "ttl": 86400 + ] } ` } diff --git a/storagev2/region/region.go b/storagev2/region/region.go index 62adae87..2f140181 100644 --- a/storagev2/region/region.go +++ b/storagev2/region/region.go @@ -17,8 +17,9 @@ type ( // // 可以存储域名或 IP,端口和协议可选 Endpoints struct { - Preferred []string `json:"preferred,omitempty"` - Alternative []string `json:"alternative,omitempty"` + Preferred []string `json:"preferred,omitempty"` // 首选服务地址 + Alternative []string `json:"alternative,omitempty"` // 备选服务地址 + Accelerated []string `json:"accelerated,omitempty"` // 加速服务地址 } // 区域信息 @@ -30,7 +31,7 @@ type ( RegionID string `json:"region_id,omitempty"` // 区域 ID Up Endpoints `json:"up,omitempty"` // Up 服务域名 Io Endpoints `json:"io,omitempty"` // Io 服务域名 - IoSrc Endpoints `json:"io_src,omitempty"` // IoSrc 服务域名 + IoSrc Endpoints `json:"io_src,omitempty"` // Io 源站服务域名 Rs Endpoints `json:"rs,omitempty"` // Rs 服务域名 Rsf Endpoints `json:"rsf,omitempty"` // Rsf 服务域名 Api Endpoints `json:"api,omitempty"` // Api 服务域名 @@ -45,11 +46,13 @@ type ( // 服务名称 ServiceName string + endpointsStatus uint8 + // 服务地址迭代器 EndpointsIter struct { - endpoints Endpoints - index int - isAlternative bool + endpoints Endpoints + index int + current endpointsStatus } // 服务地址提供者 @@ -64,12 +67,18 @@ type ( } ) +const ( + endpointsStatusAccelerated endpointsStatus = iota + endpointsStatusPreferred + endpointsStatusAlternative +) + const ( // Up 服务 ServiceUp ServiceName = "up" // Io 服务 ServiceIo ServiceName = "io" - // IoSrc 服务 + // Io 源站服务 ServiceIoSrc ServiceName = "io_src" // Rs 服务 ServiceRs ServiceName = "rs" @@ -164,35 +173,37 @@ func (left *Region) IsEqual(right *Region) bool { func (left Endpoints) Join(rights ...Endpoints) Endpoints { newEndpoint := left for _, right := range rights { - if len(newEndpoint.Preferred) == 0 { - newEndpoint.Preferred = right.Preferred - } else { - newEndpoint.Preferred = append(newEndpoint.Preferred, right.Preferred...) - } - if len(newEndpoint.Alternative) == 0 { - newEndpoint.Alternative = right.Alternative - } else { - newEndpoint.Alternative = append(newEndpoint.Alternative, right.Alternative...) - } + newEndpoint.Accelerated = append(newEndpoint.Accelerated, right.Accelerated...) + newEndpoint.Preferred = append(newEndpoint.Preferred, right.Preferred...) + newEndpoint.Alternative = append(newEndpoint.Alternative, right.Alternative...) } return newEndpoint } func (left Endpoints) IsEqual(right Endpoints) bool { - return reflect.DeepEqual(left.Preferred, right.Preferred) && + return reflect.DeepEqual(left.Accelerated, right.Accelerated) && + reflect.DeepEqual(left.Preferred, right.Preferred) && reflect.DeepEqual(left.Alternative, right.Alternative) + } func (hosts Endpoints) Iter() *EndpointsIter { return &EndpointsIter{endpoints: hosts} } +func (endpoints Endpoints) HostsLength() int { + return len(endpoints.Accelerated) + len(endpoints.Preferred) + len(endpoints.Alternative) +} + func (endpoints Endpoints) IsEmpty() bool { - return len(endpoints.Preferred) == 0 && len(endpoints.Alternative) == 0 + return len(endpoints.Accelerated) == 0 && len(endpoints.Preferred) == 0 && len(endpoints.Alternative) == 0 } func (endpoints Endpoints) firstUrl(useHttps bool) string { + for _, accelerated := range endpoints.Accelerated { + return makeUrlFromHost(accelerated, useHttps) + } for _, preferred := range endpoints.Preferred { return makeUrlFromHost(preferred, useHttps) } @@ -207,7 +218,10 @@ func (endpoints Endpoints) GetEndpoints(context.Context) (Endpoints, error) { } func (endpoints Endpoints) allUrls(useHttps bool) []string { - allHosts := make([]string, 0, len(endpoints.Preferred)+len(endpoints.Alternative)) + allHosts := make([]string, 0, len(endpoints.Accelerated)+len(endpoints.Preferred)+len(endpoints.Alternative)) + for _, accelerated := range endpoints.Accelerated { + allHosts = append(allHosts, makeUrlFromHost(accelerated, useHttps)) + } for _, preferred := range endpoints.Preferred { allHosts = append(allHosts, makeUrlFromHost(preferred, useHttps)) } @@ -228,6 +242,7 @@ func (endpoints Endpoints) Clone() Endpoints { return Endpoints{ Preferred: append([]string{}, endpoints.Preferred...), Alternative: append([]string{}, endpoints.Alternative...), + Accelerated: append([]string{}, endpoints.Accelerated...), } } @@ -243,38 +258,71 @@ func makeUrlFromHost(host string, useHttps bool) string { } func (iter *EndpointsIter) Next(nextHost *string) bool { - if iter.isAlternative { - if iter.index >= len(iter.endpoints.Alternative) { + for { + switch iter.current { + case endpointsStatusAccelerated: + if iter.index >= len(iter.endpoints.Accelerated) { + iter.current = endpointsStatusPreferred + iter.index = 0 + continue + } + host := iter.endpoints.Accelerated[iter.index] + iter.index += 1 + *nextHost = host + return true + case endpointsStatusPreferred: + if iter.index >= len(iter.endpoints.Preferred) { + iter.current = endpointsStatusAlternative + iter.index = 0 + continue + } + host := iter.endpoints.Preferred[iter.index] + iter.index += 1 + *nextHost = host + return true + case endpointsStatusAlternative: + if iter.index >= len(iter.endpoints.Alternative) { + return false + } + host := iter.endpoints.Alternative[iter.index] + iter.index += 1 + *nextHost = host + return true + default: return false } - host := iter.endpoints.Alternative[iter.index] - iter.index += 1 - *nextHost = host - return true - } - if iter.index >= len(iter.endpoints.Preferred) { - iter.isAlternative = true - iter.index = 0 - return iter.Next(nextHost) } - host := iter.endpoints.Preferred[iter.index] - iter.index += 1 - *nextHost = host - return true } func (iter *EndpointsIter) More() bool { - if iter.isAlternative { + switch iter.current { + case endpointsStatusAccelerated: + if iter.index >= len(iter.endpoints.Accelerated) { + return len(iter.endpoints.Preferred) > 0 + } + return true + case endpointsStatusPreferred: + if iter.index >= len(iter.endpoints.Preferred) { + return len(iter.endpoints.Alternative) > 0 + } + return true + case endpointsStatusAlternative: return iter.index < len(iter.endpoints.Alternative) - } else if iter.index >= len(iter.endpoints.Preferred) { - return len(iter.endpoints.Alternative) > 0 + default: + return false } - return true } func (iter *EndpointsIter) SwitchToAlternative() { - if len(iter.endpoints.Alternative) > 0 && !iter.isAlternative { - iter.isAlternative = true + if len(iter.endpoints.Alternative) > 0 && iter.current != endpointsStatusAlternative { + iter.current = endpointsStatusAlternative + iter.index = 0 + } +} + +func (iter *EndpointsIter) SwitchToPreferred() { + if len(iter.endpoints.Preferred) > 0 && iter.current != endpointsStatusPreferred { + iter.current = endpointsStatusPreferred iter.index = 0 } } diff --git a/storagev2/retrier/retrier.go b/storagev2/retrier/retrier.go index 5055865b..76cafaad 100644 --- a/storagev2/retrier/retrier.go +++ b/storagev2/retrier/retrier.go @@ -68,10 +68,12 @@ func NewErrorRetrier() Retrier { } func (errorRetrier) Retry(response *http.Response, err error, _ *RetrierOptions) RetryDecision { - if isResponseRetryable(response) || IsErrorRetryable(err) { + if isResponseRetryable(response) { return RetryRequest - } else { + } else if err == nil { return DontRetry + } else { + return getRetryDecisionForError(err) } } @@ -165,7 +167,9 @@ func getRetryDecisionForError(err error) RetryDecision { } else if unwrapedErr == context.Canceled { return DontRetry } else if clientErr, ok := unwrapedErr.(*clientv1.ErrorInfo); ok { - if IsStatusCodeRetryable(clientErr.Code) { + if clientErr.Code == http.StatusBadRequest && strings.Contains(unwrapedErr.Error(), "transfer acceleration is not configured on this bucket") { + return TryNextHost + } else if IsStatusCodeRetryable(clientErr.Code) { return RetryRequest } else { return DontRetry diff --git a/storagev2/uploader/form_uploader_test.go b/storagev2/uploader/form_uploader_test.go index 3e5533af..4bd54fa2 100644 --- a/storagev2/uploader/form_uploader_test.go +++ b/storagev2/uploader/form_uploader_test.go @@ -310,6 +310,128 @@ func TestFormUploaderRetry(t *testing.T) { } } +func TestFormUploaderAccelaratedUploading(t *testing.T) { + tmpFile, err := ioutil.TempFile("", "form-uploader-test-*") + if err != nil { + t.Fatal(err) + } + defer os.Remove(tmpFile.Name()) + defer tmpFile.Close() + + r := rand.New(rand.NewSource(time.Now().UnixNano())) + hasher := md5.New() + if _, err = io.CopyN(tmpFile, io.TeeReader(r, hasher), 1024*1024); err != nil { + t.Fatal(err) + } + if _, err = tmpFile.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + expectedMd5 := hasher.Sum(nil) + + var handlerCalled_1, handlerCalled_2 uint64 + + serveMux_1 := http.NewServeMux() + serveMux_1.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddUint64(&handlerCalled_1, 1) + if r.Method != http.MethodPost { + t.Fatalf("unexpected method: %s", r.Method) + } + if err := r.ParseMultipartForm(2 * 1024 * 1024); err != nil { + t.Fatal(err) + } + if values := r.MultipartForm.Value["key"]; len(values) != 1 || values[0] != "testkey" { + t.Fatalf("unexpected key") + } + if values := r.MultipartForm.Value["token"]; len(values) != 1 || !strings.HasPrefix(values[0], "testak:") { + t.Fatalf("unexpected token") + } + if values := r.MultipartForm.Value["x-qn-meta-a"]; len(values) != 1 || values[0] != "b" { + t.Fatalf("unexpected x-qn-meta-a") + } + if values := r.MultipartForm.Value["x-qn-meta-c"]; len(values) != 1 || values[0] != "d" { + t.Fatalf("unexpected x-qn-meta-c") + } + if values := r.MultipartForm.Value["x:a"]; len(values) != 1 || values[0] != "b" { + t.Fatalf("unexpected x:a") + } + if values := r.MultipartForm.Value["x:c"]; len(values) != 1 || values[0] != "d" { + t.Fatalf("unexpected x:c") + } + if files := r.MultipartForm.File["file"]; len(files) != 1 || files[0].Filename != "testfilename" || files[0].Size != 1024*1024 { + t.Fatalf("unexpected file") + } else if contentType := files[0].Header.Get("Content-Type"); contentType != "application/json" { + t.Fatalf("unexpected file content-type") + } else if file, err := files[0].Open(); err != nil { + t.Fatal(err) + } else { + defer file.Close() + hasher := md5.New() + if _, err = io.Copy(hasher, file); err != nil { + t.Fatal(err) + } + if !bytes.Equal(hasher.Sum(nil), expectedMd5) { + t.Fatalf("unexpected file content") + } + } + w.Header().Add("x-reqid", "fakereqid") + w.Write([]byte(`{"ok":true}`)) + }) + server_1 := httptest.NewServer(serveMux_1) + defer server_1.Close() + + serveMux_2 := http.NewServeMux() + serveMux_2.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddUint64(&handlerCalled_2, 1) + if r.Method != http.MethodPost { + t.Fatalf("unexpected method: %s", r.Method) + } + if err := r.ParseMultipartForm(2 * 1024 * 1024); err != nil { + t.Fatal(err) + } + w.Header().Set("Content-Type", "application/json") + w.Header().Add("x-reqid", "fakereqid") + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(`{"error":"transfer acceleration is not configured on this bucket"}`)) + }) + server_2 := httptest.NewServer(serveMux_2) + defer server_2.Close() + + var ( + returnValue struct { + Ok bool `json:"ok"` + } + key = "testkey" + ) + + formUploader := NewFormUploader(&FormUploaderOptions{ + Options: http_client.Options{ + Regions: regions{[]*region.Region{ + {Up: region.Endpoints{Accelerated: []string{server_2.URL}, Preferred: []string{server_1.URL}}}, + }}, + Credentials: credentials.NewCredentials("testak", "testsk"), + }, + }) + if err = formUploader.UploadFile(context.Background(), tmpFile.Name(), &ObjectOptions{ + BucketName: "testbucket", + ObjectName: &key, + FileName: "testfilename", + ContentType: "application/json", + Metadata: map[string]string{"a": "b", "c": "d"}, + CustomVars: map[string]string{"a": "b", "c": "d"}, + }, &returnValue); err != nil { + t.Fatal(err) + } + if !returnValue.Ok { + t.Fatalf("unexpected response value") + } + if count := atomic.LoadUint64(&handlerCalled_1); count != 1 { + t.Fatalf("unexpected handler call count: %d", count) + } + if count := atomic.LoadUint64(&handlerCalled_2); count != 1 { + t.Fatalf("unexpected handler call count: %d", count) + } +} + type regions struct { regions []*region.Region } diff --git a/storagev2/uploader/params.go b/storagev2/uploader/params.go index 0ecc651f..a8832024 100644 --- a/storagev2/uploader/params.go +++ b/storagev2/uploader/params.go @@ -97,7 +97,7 @@ type ( // 是否在空间内创建目录 ShouldCreateDirectory bool - // 是否上传指定对象 + // 是否上传指定对象,如果 objectOptions 为 nil 则表示是目录 ShouldUploadObject func(filePath string, objectOptions *ObjectOptions) bool // 更改对象名称 diff --git a/storagev2/uploader/resumable_recorder/json_file_system.go b/storagev2/uploader/resumable_recorder/json_file_system.go index c49707aa..8b407f13 100644 --- a/storagev2/uploader/resumable_recorder/json_file_system.go +++ b/storagev2/uploader/resumable_recorder/json_file_system.go @@ -184,6 +184,11 @@ func (frr jsonFileSystemResumableRecorder) fileName(options *ResumableRecorderOp hasher.Write([]byte{1}) } hasher.Write([]byte{0}) + for _, endpoint := range options.UpEndpoints.Accelerated { + hasher.Write([]byte(endpoint)) + hasher.Write([]byte{1}) + } + hasher.Write([]byte{0}) binary.Write(hasher, binary.LittleEndian, options.PartSize) binary.Write(hasher, binary.LittleEndian, options.TotalSize) return hex.EncodeToString(hasher.Sum(nil)) diff --git a/storagev2/uploader/upload_manager.go b/storagev2/uploader/upload_manager.go index 0ec29e1a..2989245c 100644 --- a/storagev2/uploader/upload_manager.go +++ b/storagev2/uploader/upload_manager.go @@ -160,6 +160,9 @@ func (uploadManager *UploadManager) UploadDirectory(ctx context.Context, directo directoryOptions.OnObjectUploaded(path, &UploadedObjectInfo{Size: uint64(info.Size())}) } } else if directoryOptions.ShouldCreateDirectory && info.IsDir() { + if directoryOptions.ShouldUploadObject != nil && !directoryOptions.ShouldUploadObject(path, nil) { + return nil + } if !strings.HasSuffix(objectName, pathSeparator) { objectName += pathSeparator } diff --git a/storagev2/uploader/upload_manager_test.go b/storagev2/uploader/upload_manager_test.go index 06434b7e..22a6e5a4 100644 --- a/storagev2/uploader/upload_manager_test.go +++ b/storagev2/uploader/upload_manager_test.go @@ -617,3 +617,78 @@ func testUploadManagerUploadDirectory(t *testing.T, createDirectory bool) { t.Fatal(err) } } + +func TestUploadManagerUploadDirectoryWithFilter(t *testing.T) { + tmpDir_1, err := ioutil.TempDir("", "multi-parts-uploader-test-*") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(tmpDir_1) + + tmpFile_1, err := ioutil.TempFile(tmpDir_1, "multi-parts-uploader-test-*") + if err != nil { + t.Fatal(err) + } + defer os.Remove(tmpFile_1.Name()) + defer tmpFile_1.Close() + + tmpFile_2, err := ioutil.TempFile(tmpDir_1, "multi-parts-uploader-test-*") + if err != nil { + t.Fatal(err) + } + defer os.Remove(tmpFile_2.Name()) + defer tmpFile_2.Close() + + keys := make(map[string]struct{}) + var keysMutex sync.Mutex + + serveMux := http.NewServeMux() + serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Fatalf("unexpected method: %s", r.Method) + } + if err := r.ParseMultipartForm(2 * 1024 * 1024); err != nil { + t.Fatal(err) + } + if values := r.MultipartForm.Value["token"]; len(values) != 1 || !strings.HasPrefix(values[0], "testak:") { + t.Fatalf("unexpected token") + } + + key := r.MultipartForm.Value["key"][0] + keysMutex.Lock() + keys[key] = struct{}{} + keysMutex.Unlock() + w.Header().Add("X-ReqId", "fakereqid") + w.Write([]byte(`{"ok":true}`)) + }) + server := httptest.NewServer(serveMux) + defer server.Close() + + var uploadManager = uploader.NewUploadManager(&uploader.UploadManagerOptions{ + Options: http_client.Options{ + Regions: ®ion.Region{Up: region.Endpoints{Preferred: []string{server.URL}}}, + Credentials: credentials.NewCredentials("testak", "testsk"), + }, + }) + + err = uploadManager.UploadDirectory(context.Background(), tmpDir_1, &uploader.DirectoryOptions{ + BucketName: "testbucket", + ShouldCreateDirectory: true, + ShouldUploadObject: func(_ string, objectOptions *uploader.ObjectOptions) bool { + return objectOptions != nil + }, + }) + if err != nil { + t.Fatal(err) + } + + if len(keys) != 2 { + t.Fatalf("unexpected uploaded oject names count") + } + if _, ok := keys[filepath.Base(tmpFile_1.Name())]; !ok { + t.Fatalf("unexpected uploaded oject name") + } + if _, ok := keys[filepath.Base(tmpFile_2.Name())]; !ok { + t.Fatalf("unexpected uploaded oject name") + } +} diff --git a/storagev2/uploader/uploaders.go b/storagev2/uploader/uploaders.go index 5566f8e4..5acde312 100644 --- a/storagev2/uploader/uploaders.go +++ b/storagev2/uploader/uploaders.go @@ -403,6 +403,7 @@ func getRegions(ctx context.Context, upToken uptoken.Provider, bucketName string UseInsecureProtocol: options.UseInsecureProtocol, HostFreezeDuration: options.HostFreezeDuration, Client: options.BasicHTTPClient, + AccelerateUploading: options.AccelerateUploading, } if hostRetryConfig := options.HostRetryConfig; hostRetryConfig != nil { queryOptions.RetryMax = hostRetryConfig.RetryMax diff --git a/storagev2/uplog/uplog.go b/storagev2/uplog/uplog.go index 3ef94d97..b6d40968 100644 --- a/storagev2/uplog/uplog.go +++ b/storagev2/uplog/uplog.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/qiniu/go-sdk/v7/storagev2/internal/uplog" + "github.com/qiniu/go-sdk/v7/internal/uplog" ) // UpApiVersion 表示上传接口的版本 diff --git a/storagev2/uptoken/putpolicy.go b/storagev2/uptoken/putpolicy.go index 4734b538..bf86d83e 100644 --- a/storagev2/uptoken/putpolicy.go +++ b/storagev2/uptoken/putpolicy.go @@ -26,6 +26,7 @@ const ( putPolicyKeyPersistentOps = "persistentOps" putPolicyKeyPersistentNotifyUrl = "persistentNotifyUrl" putPolicyKeyPersistentPipeline = "persistentPipeline" + putPolicyKeyPersistentType = "persistentType" putPolicyKeyForceSaveKey = "forceSaveKey" putPolicyKeySaveKey = "saveKey" putPolicyKeyFsizeMin = "fsizeMin" @@ -237,6 +238,17 @@ func (putPolicy PutPolicy) SetPersistentPipeline(value string) PutPolicy { return putPolicy } +// GetPersistentType 获取任务类型 +func (putPolicy PutPolicy) GetPersistentType() (int64, bool) { + return putPolicy.getInt64(putPolicyKeyPersistentType) +} + +// SetPersistentType 指定任务类型 +func (putPolicy PutPolicy) SetPersistentType(value int64) PutPolicy { + _ = putPolicy.Set(putPolicyKeyPersistentType, value) + return putPolicy +} + // GetForceSaveKey 获取 saveKey 的优先级设置 func (putPolicy PutPolicy) GetForceSaveKey() (bool, bool) { return putPolicy.getBool(putPolicyKeyForceSaveKey)