From a20240f997fed38afdc14ad19cdd2113dd4a2242 Mon Sep 17 00:00:00 2001 From: zhang21 Date: Wed, 26 Jul 2023 13:52:51 +0800 Subject: [PATCH 01/19] update: gitignore, makefile --- .gitignore | 9 +- Makefile | 42 +- .../aliyun/alibaba-cloud-sdk-go/LICENSE | 201 - .../alibaba-cloud-sdk-go/sdk/api_timeout.go | 249 - .../sdk/auth/credential.go | 18 - .../auth/credentials/access_key_credential.go | 34 - .../credentials/bearer_token_credential.go | 12 - .../sdk/auth/credentials/ecs_ram_role.go | 29 - .../sdk/auth/credentials/provider/env.go | 30 - .../provider/instance_credentials.go | 92 - .../provider/profile_credentials.go | 159 - .../sdk/auth/credentials/provider/provider.go | 19 - .../credentials/provider/provider_chain.go | 34 - .../credentials/rsa_key_pair_credential.go | 15 - .../sdk/auth/credentials/sts_credential.go | 15 - .../credentials/sts_role_arn_credential.go | 62 - .../sdk/auth/roa_signature_composer.go | 140 - .../sdk/auth/rpc_signature_composer.go | 94 - .../alibaba-cloud-sdk-go/sdk/auth/signer.go | 98 - .../sdk/auth/signers/algorithms.go | 57 - .../sdk/auth/signers/credential_updater.go | 54 - .../sdk/auth/signers/session_credential.go | 7 - .../sdk/auth/signers/signer_access_key.go | 54 - .../sdk/auth/signers/signer_bearer_token.go | 35 - .../sdk/auth/signers/signer_ecs_ram_role.go | 167 - .../sdk/auth/signers/signer_key_pair.go | 148 - .../sdk/auth/signers/signer_ram_role_arn.go | 180 - .../sdk/auth/signers/signer_sts_token.go | 54 - .../sdk/auth/signers/signer_v2.go | 54 - .../aliyun/alibaba-cloud-sdk-go/sdk/client.go | 853 - .../aliyun/alibaba-cloud-sdk-go/sdk/config.go | 92 - .../sdk/endpoints/endpoints_config.go | 4078 - .../sdk/endpoints/local_global_resolver.go | 43 - .../sdk/endpoints/local_regional_resolver.go | 48 - .../sdk/endpoints/location_resolver.go | 176 - .../sdk/endpoints/mapping_resolver.go | 49 - .../sdk/endpoints/resolver.go | 96 - .../sdk/errors/client_error.go | 92 - .../alibaba-cloud-sdk-go/sdk/errors/error.go | 23 - .../sdk/errors/server_error.go | 124 - .../signature_does_not_match_wrapper.go | 45 - .../aliyun/alibaba-cloud-sdk-go/sdk/logger.go | 117 - .../sdk/requests/acs_request.go | 525 - .../sdk/requests/common_request.go | 112 - .../sdk/requests/roa_request.go | 148 - .../sdk/requests/rpc_request.go | 81 - .../sdk/requests/types.go | 53 - .../sdk/responses/json_parser.go | 333 - .../sdk/responses/response.go | 144 - .../alibaba-cloud-sdk-go/sdk/utils/debug.go | 36 - .../alibaba-cloud-sdk-go/sdk/utils/utils.go | 141 - .../services/dysmsapi/add_sms_sign.go | 114 - .../services/dysmsapi/add_sms_template.go | 108 - .../services/dysmsapi/client.go | 129 - .../services/dysmsapi/delete_sms_sign.go | 105 - .../services/dysmsapi/delete_sms_template.go | 105 - .../services/dysmsapi/endpoint.go | 25 - .../services/dysmsapi/modify_sms_sign.go | 114 - .../services/dysmsapi/modify_sms_template.go | 109 - .../services/dysmsapi/query_send_details.go | 110 - .../services/dysmsapi/query_sms_sign.go | 108 - .../services/dysmsapi/query_sms_template.go | 111 - .../services/dysmsapi/send_batch_sms.go | 109 - .../services/dysmsapi/send_sms.go | 110 - .../dysmsapi/struct_sms_send_detail_dt_os.go | 21 - .../dysmsapi/struct_sms_send_detail_dto.go | 28 - .../services/dyvmsapi/add_rtc_account.go | 105 - .../dyvmsapi/batch_robot_smart_call.go | 115 - .../dyvmsapi/bind_number_and_voip_id.go | 106 - .../services/dyvmsapi/cancel_call.go | 105 - .../dyvmsapi/cancel_order_robot_task.go | 105 - .../services/dyvmsapi/cancel_robot_task.go | 105 - .../services/dyvmsapi/click_to_dial.go | 113 - .../services/dyvmsapi/client.go | 129 - .../services/dyvmsapi/create_robot_task.go | 114 - .../services/dyvmsapi/delete_robot_task.go | 105 - .../services/dyvmsapi/endpoint.go | 20 - .../services/dyvmsapi/get_rtc_token.go | 107 - .../services/dyvmsapi/ivr_call.go | 121 - .../dyvmsapi/query_call_detail_by_call_id.go | 107 - .../dyvmsapi/query_call_detail_by_task_id.go | 107 - .../dyvmsapi/query_robot_info_list.go | 105 - .../dyvmsapi/query_robot_task_call_detail.go | 107 - .../dyvmsapi/query_robot_task_call_list.go | 114 - .../dyvmsapi/query_robot_task_detail.go | 105 - .../dyvmsapi/query_robot_task_list.go | 112 - .../dyvmsapi/query_robotv2_all_list.go | 104 - .../dyvmsapi/query_voip_number_bind_infos.go | 106 - .../services/dyvmsapi/report_voip_problems.go | 108 - .../services/dyvmsapi/single_call_by_tts.go | 112 - .../services/dyvmsapi/single_call_by_voice.go | 111 - .../services/dyvmsapi/smart_call.go | 130 - .../services/dyvmsapi/smart_call_operate.go | 107 - .../services/dyvmsapi/start_robot_task.go | 106 - .../services/dyvmsapi/stop_robot_task.go | 105 - .../dyvmsapi/unbind_number_and_voip_id.go | 106 - .../dyvmsapi/upload_robot_task_called_file.go | 108 - .../services/dyvmsapi/voip_add_account.go | 105 - .../services/dyvmsapi/voip_get_token.go | 107 - vendor/github.com/astaxie/beego/.gitignore | 6 - vendor/github.com/astaxie/beego/.travis.yml | 73 - .../github.com/astaxie/beego/CONTRIBUTING.md | 52 - vendor/github.com/astaxie/beego/LICENSE | 13 - vendor/github.com/astaxie/beego/README.md | 73 - vendor/github.com/astaxie/beego/admin.go | 458 - vendor/github.com/astaxie/beego/adminui.go | 356 - vendor/github.com/astaxie/beego/app.go | 496 - vendor/github.com/astaxie/beego/beego.go | 123 - vendor/github.com/astaxie/beego/config.go | 533 - .../github.com/astaxie/beego/config/config.go | 242 - .../github.com/astaxie/beego/config/fake.go | 134 - vendor/github.com/astaxie/beego/config/ini.go | 504 - .../github.com/astaxie/beego/config/json.go | 269 - .../astaxie/beego/context/acceptencoder.go | 232 - .../astaxie/beego/context/context.go | 263 - .../github.com/astaxie/beego/context/input.go | 689 - .../astaxie/beego/context/output.go | 408 - .../astaxie/beego/context/param/conv.go | 78 - .../beego/context/param/methodparams.go | 69 - .../astaxie/beego/context/param/options.go | 37 - .../astaxie/beego/context/param/parsers.go | 149 - .../astaxie/beego/context/renderer.go | 12 - .../astaxie/beego/context/response.go | 27 - vendor/github.com/astaxie/beego/controller.go | 706 - vendor/github.com/astaxie/beego/doc.go | 17 - vendor/github.com/astaxie/beego/error.go | 488 - vendor/github.com/astaxie/beego/filter.go | 44 - vendor/github.com/astaxie/beego/flash.go | 110 - vendor/github.com/astaxie/beego/fs.go | 74 - vendor/github.com/astaxie/beego/go.mod | 41 - vendor/github.com/astaxie/beego/go.sum | 210 - .../github.com/astaxie/beego/grace/grace.go | 166 - .../github.com/astaxie/beego/grace/server.go | 356 - vendor/github.com/astaxie/beego/hooks.go | 105 - vendor/github.com/astaxie/beego/log.go | 127 - .../github.com/astaxie/beego/logs/README.md | 72 - .../astaxie/beego/logs/accesslog.go | 83 - vendor/github.com/astaxie/beego/logs/conn.go | 119 - .../github.com/astaxie/beego/logs/console.go | 99 - vendor/github.com/astaxie/beego/logs/file.go | 409 - .../github.com/astaxie/beego/logs/jianliao.go | 72 - vendor/github.com/astaxie/beego/logs/log.go | 669 - .../github.com/astaxie/beego/logs/logger.go | 176 - .../astaxie/beego/logs/multifile.go | 119 - vendor/github.com/astaxie/beego/logs/slack.go | 60 - vendor/github.com/astaxie/beego/logs/smtp.go | 149 - vendor/github.com/astaxie/beego/mime.go | 556 - vendor/github.com/astaxie/beego/namespace.go | 396 - vendor/github.com/astaxie/beego/orm/README.md | 159 - vendor/github.com/astaxie/beego/orm/cmd.go | 283 - .../github.com/astaxie/beego/orm/cmd_utils.go | 320 - vendor/github.com/astaxie/beego/orm/db.go | 1903 - .../github.com/astaxie/beego/orm/db_alias.go | 469 - .../github.com/astaxie/beego/orm/db_mysql.go | 184 - .../github.com/astaxie/beego/orm/db_oracle.go | 137 - .../astaxie/beego/orm/db_postgres.go | 189 - .../github.com/astaxie/beego/orm/db_sqlite.go | 161 - .../github.com/astaxie/beego/orm/db_tables.go | 482 - .../github.com/astaxie/beego/orm/db_tidb.go | 63 - .../github.com/astaxie/beego/orm/db_utils.go | 177 - vendor/github.com/astaxie/beego/orm/models.go | 99 - .../astaxie/beego/orm/models_boot.go | 347 - .../astaxie/beego/orm/models_fields.go | 783 - .../astaxie/beego/orm/models_info_f.go | 473 - .../astaxie/beego/orm/models_info_m.go | 148 - .../astaxie/beego/orm/models_utils.go | 227 - vendor/github.com/astaxie/beego/orm/orm.go | 579 - .../github.com/astaxie/beego/orm/orm_conds.go | 153 - .../github.com/astaxie/beego/orm/orm_log.go | 222 - .../astaxie/beego/orm/orm_object.go | 87 - .../astaxie/beego/orm/orm_querym2m.go | 140 - .../astaxie/beego/orm/orm_queryset.go | 300 - .../github.com/astaxie/beego/orm/orm_raw.go | 885 - vendor/github.com/astaxie/beego/orm/qb.go | 62 - .../github.com/astaxie/beego/orm/qb_mysql.go | 185 - .../github.com/astaxie/beego/orm/qb_tidb.go | 182 - vendor/github.com/astaxie/beego/orm/types.go | 473 - vendor/github.com/astaxie/beego/orm/utils.go | 319 - vendor/github.com/astaxie/beego/parser.go | 591 - vendor/github.com/astaxie/beego/policy.go | 97 - vendor/github.com/astaxie/beego/router.go | 1052 - .../astaxie/beego/session/README.md | 114 - .../astaxie/beego/session/sess_cookie.go | 180 - .../astaxie/beego/session/sess_file.go | 315 - .../astaxie/beego/session/sess_mem.go | 196 - .../astaxie/beego/session/sess_utils.go | 207 - .../astaxie/beego/session/session.go | 382 - vendor/github.com/astaxie/beego/staticfile.go | 234 - vendor/github.com/astaxie/beego/template.go | 406 - .../github.com/astaxie/beego/templatefunc.go | 780 - .../astaxie/beego/toolbox/healthcheck.go | 48 - .../astaxie/beego/toolbox/profile.go | 184 - .../astaxie/beego/toolbox/statistics.go | 149 - .../github.com/astaxie/beego/toolbox/task.go | 634 - vendor/github.com/astaxie/beego/tree.go | 585 - .../github.com/astaxie/beego/utils/caller.go | 25 - .../github.com/astaxie/beego/utils/debug.go | 478 - vendor/github.com/astaxie/beego/utils/file.go | 101 - vendor/github.com/astaxie/beego/utils/mail.go | 424 - vendor/github.com/astaxie/beego/utils/rand.go | 44 - .../github.com/astaxie/beego/utils/safemap.go | 91 - .../github.com/astaxie/beego/utils/slice.go | 170 - .../github.com/astaxie/beego/utils/utils.go | 89 - vendor/github.com/baidubce/bce-sdk-go/LICENSE | 177 - .../baidubce/bce-sdk-go/auth/credentials.go | 62 - .../baidubce/bce-sdk-go/auth/signer.go | 184 - .../baidubce/bce-sdk-go/bce/builder.go | 189 - .../baidubce/bce-sdk-go/bce/client.go | 267 - .../baidubce/bce-sdk-go/bce/config.go | 80 - .../baidubce/bce-sdk-go/bce/error.go | 64 - .../baidubce/bce-sdk-go/bce/request.go | 219 - .../baidubce/bce-sdk-go/bce/response.go | 128 - .../baidubce/bce-sdk-go/bce/retry.go | 118 - .../baidubce/bce-sdk-go/http/client.go | 174 - .../baidubce/bce-sdk-go/http/constants.go | 83 - .../baidubce/bce-sdk-go/http/request.go | 221 - .../baidubce/bce-sdk-go/http/response.go | 74 - .../bce-sdk-go/services/sms/api/model.go | 162 - .../bce-sdk-go/services/sms/api/quota_rate.go | 80 - .../bce-sdk-go/services/sms/api/send_sms.go | 76 - .../bce-sdk-go/services/sms/api/signature.go | 173 - .../bce-sdk-go/services/sms/api/template.go | 178 - .../bce-sdk-go/services/sms/api/util.go | 36 - .../bce-sdk-go/services/sms/client.go | 179 - .../baidubce/bce-sdk-go/util/log/logger.go | 393 - .../baidubce/bce-sdk-go/util/log/util.go | 227 - .../baidubce/bce-sdk-go/util/string.go | 88 - .../baidubce/bce-sdk-go/util/time.go | 46 - vendor/github.com/beorn7/perks/LICENSE | 20 - .../beorn7/perks/quantile/exampledata.txt | 2388 - .../beorn7/perks/quantile/stream.go | 316 - .../github.com/cespare/xxhash/v2/LICENSE.txt | 22 - vendor/github.com/cespare/xxhash/v2/README.md | 69 - vendor/github.com/cespare/xxhash/v2/go.mod | 3 - vendor/github.com/cespare/xxhash/v2/go.sum | 0 vendor/github.com/cespare/xxhash/v2/xxhash.go | 235 - .../cespare/xxhash/v2/xxhash_amd64.go | 13 - .../cespare/xxhash/v2/xxhash_amd64.s | 215 - .../cespare/xxhash/v2/xxhash_other.go | 76 - .../cespare/xxhash/v2/xxhash_safe.go | 15 - .../cespare/xxhash/v2/xxhash_unsafe.go | 57 - .../github.com/go-gomail/gomail/.travis.yml | 9 - .../github.com/go-gomail/gomail/CHANGELOG.md | 20 - .../go-gomail/gomail/CONTRIBUTING.md | 20 - vendor/github.com/go-gomail/gomail/LICENSE | 20 - vendor/github.com/go-gomail/gomail/README.md | 92 - vendor/github.com/go-gomail/gomail/auth.go | 49 - vendor/github.com/go-gomail/gomail/doc.go | 5 - vendor/github.com/go-gomail/gomail/message.go | 322 - vendor/github.com/go-gomail/gomail/mime.go | 21 - .../github.com/go-gomail/gomail/mime_go14.go | 25 - vendor/github.com/go-gomail/gomail/send.go | 116 - vendor/github.com/go-gomail/gomail/smtp.go | 202 - vendor/github.com/go-gomail/gomail/writeto.go | 306 - .../github.com/go-sql-driver/mysql/.gitignore | 9 - vendor/github.com/go-sql-driver/mysql/AUTHORS | 117 - .../go-sql-driver/mysql/CHANGELOG.md | 232 - vendor/github.com/go-sql-driver/mysql/LICENSE | 373 - .../github.com/go-sql-driver/mysql/README.md | 520 - vendor/github.com/go-sql-driver/mysql/auth.go | 425 - .../github.com/go-sql-driver/mysql/buffer.go | 182 - .../go-sql-driver/mysql/collations.go | 265 - .../go-sql-driver/mysql/connection.go | 650 - .../github.com/go-sql-driver/mysql/const.go | 174 - .../github.com/go-sql-driver/mysql/driver.go | 107 - vendor/github.com/go-sql-driver/mysql/dsn.go | 560 - .../github.com/go-sql-driver/mysql/errors.go | 65 - .../github.com/go-sql-driver/mysql/fields.go | 194 - .../github.com/go-sql-driver/mysql/infile.go | 182 - .../github.com/go-sql-driver/mysql/packets.go | 1349 - .../github.com/go-sql-driver/mysql/result.go | 22 - vendor/github.com/go-sql-driver/mysql/rows.go | 223 - .../go-sql-driver/mysql/statement.go | 220 - .../go-sql-driver/mysql/transaction.go | 31 - .../github.com/go-sql-driver/mysql/utils.go | 868 - .../telegram-bot-api/v5/.gitignore | 4 - .../telegram-bot-api/v5/LICENSE.txt | 21 - .../telegram-bot-api/v5/README.md | 121 - .../telegram-bot-api/v5/bot.go | 726 - .../telegram-bot-api/v5/configs.go | 2468 - .../telegram-bot-api/v5/go.mod | 3 - .../telegram-bot-api/v5/go.sum | 0 .../telegram-bot-api/v5/helpers.go | 927 - .../telegram-bot-api/v5/log.go | 27 - .../telegram-bot-api/v5/params.go | 97 - .../telegram-bot-api/v5/passport.go | 317 - .../telegram-bot-api/v5/types.go | 3225 - vendor/github.com/golang/protobuf/AUTHORS | 3 - .../github.com/golang/protobuf/CONTRIBUTORS | 3 - vendor/github.com/golang/protobuf/LICENSE | 28 - .../golang/protobuf/proto/buffer.go | 324 - .../golang/protobuf/proto/defaults.go | 63 - .../golang/protobuf/proto/deprecated.go | 113 - .../golang/protobuf/proto/discard.go | 58 - .../golang/protobuf/proto/extensions.go | 356 - .../golang/protobuf/proto/properties.go | 306 - .../github.com/golang/protobuf/proto/proto.go | 167 - .../golang/protobuf/proto/registry.go | 317 - .../golang/protobuf/proto/text_decode.go | 801 - .../golang/protobuf/proto/text_encode.go | 560 - .../github.com/golang/protobuf/proto/wire.go | 78 - .../golang/protobuf/proto/wrappers.go | 34 - .../github.com/golang/protobuf/ptypes/any.go | 179 - .../golang/protobuf/ptypes/any/any.pb.go | 62 - .../github.com/golang/protobuf/ptypes/doc.go | 10 - .../golang/protobuf/ptypes/duration.go | 76 - .../protobuf/ptypes/duration/duration.pb.go | 63 - .../golang/protobuf/ptypes/timestamp.go | 112 - .../protobuf/ptypes/timestamp/timestamp.pb.go | 64 - vendor/github.com/gopherjs/gopherjs/LICENSE | 24 - vendor/github.com/gopherjs/gopherjs/js/js.go | 168 - .../jmespath/go-jmespath/.gitignore | 4 - .../jmespath/go-jmespath/.travis.yml | 28 - .../github.com/jmespath/go-jmespath/LICENSE | 13 - .../github.com/jmespath/go-jmespath/Makefile | 51 - .../github.com/jmespath/go-jmespath/README.md | 87 - vendor/github.com/jmespath/go-jmespath/api.go | 49 - .../go-jmespath/astnodetype_string.go | 16 - .../jmespath/go-jmespath/functions.go | 842 - vendor/github.com/jmespath/go-jmespath/go.mod | 5 - vendor/github.com/jmespath/go-jmespath/go.sum | 11 - .../jmespath/go-jmespath/interpreter.go | 418 - .../github.com/jmespath/go-jmespath/lexer.go | 420 - .../github.com/jmespath/go-jmespath/parser.go | 603 - .../jmespath/go-jmespath/toktype_string.go | 16 - .../github.com/jmespath/go-jmespath/util.go | 185 - vendor/github.com/josharian/intern/README.md | 5 - vendor/github.com/josharian/intern/go.mod | 3 - vendor/github.com/josharian/intern/intern.go | 44 - vendor/github.com/josharian/intern/license.md | 21 - .../github.com/json-iterator/go/.codecov.yml | 3 - vendor/github.com/json-iterator/go/.gitignore | 4 - .../github.com/json-iterator/go/.travis.yml | 14 - vendor/github.com/json-iterator/go/Gopkg.lock | 21 - vendor/github.com/json-iterator/go/Gopkg.toml | 26 - vendor/github.com/json-iterator/go/LICENSE | 21 - vendor/github.com/json-iterator/go/README.md | 85 - vendor/github.com/json-iterator/go/adapter.go | 150 - vendor/github.com/json-iterator/go/any.go | 325 - .../github.com/json-iterator/go/any_array.go | 278 - .../github.com/json-iterator/go/any_bool.go | 137 - .../github.com/json-iterator/go/any_float.go | 83 - .../github.com/json-iterator/go/any_int32.go | 74 - .../github.com/json-iterator/go/any_int64.go | 74 - .../json-iterator/go/any_invalid.go | 82 - vendor/github.com/json-iterator/go/any_nil.go | 69 - .../github.com/json-iterator/go/any_number.go | 123 - .../github.com/json-iterator/go/any_object.go | 374 - vendor/github.com/json-iterator/go/any_str.go | 166 - .../github.com/json-iterator/go/any_uint32.go | 74 - .../github.com/json-iterator/go/any_uint64.go | 74 - vendor/github.com/json-iterator/go/build.sh | 12 - vendor/github.com/json-iterator/go/config.go | 375 - .../go/fuzzy_mode_convert_table.md | 7 - vendor/github.com/json-iterator/go/go.mod | 11 - vendor/github.com/json-iterator/go/go.sum | 14 - vendor/github.com/json-iterator/go/iter.go | 349 - .../github.com/json-iterator/go/iter_array.go | 64 - .../github.com/json-iterator/go/iter_float.go | 342 - .../github.com/json-iterator/go/iter_int.go | 346 - .../json-iterator/go/iter_object.go | 267 - .../github.com/json-iterator/go/iter_skip.go | 130 - .../json-iterator/go/iter_skip_sloppy.go | 163 - .../json-iterator/go/iter_skip_strict.go | 99 - .../github.com/json-iterator/go/iter_str.go | 215 - .../github.com/json-iterator/go/jsoniter.go | 18 - vendor/github.com/json-iterator/go/pool.go | 42 - vendor/github.com/json-iterator/go/reflect.go | 337 - .../json-iterator/go/reflect_array.go | 104 - .../json-iterator/go/reflect_dynamic.go | 70 - .../json-iterator/go/reflect_extension.go | 483 - .../json-iterator/go/reflect_json_number.go | 112 - .../go/reflect_json_raw_message.go | 76 - .../json-iterator/go/reflect_map.go | 346 - .../json-iterator/go/reflect_marshaler.go | 225 - .../json-iterator/go/reflect_native.go | 453 - .../json-iterator/go/reflect_optional.go | 129 - .../json-iterator/go/reflect_slice.go | 99 - .../go/reflect_struct_decoder.go | 1097 - .../go/reflect_struct_encoder.go | 211 - vendor/github.com/json-iterator/go/stream.go | 210 - .../json-iterator/go/stream_float.go | 111 - .../github.com/json-iterator/go/stream_int.go | 190 - .../github.com/json-iterator/go/stream_str.go | 372 - vendor/github.com/json-iterator/go/test.sh | 12 - vendor/github.com/jtolds/gls/LICENSE | 18 - vendor/github.com/jtolds/gls/README.md | 89 - vendor/github.com/jtolds/gls/context.go | 153 - vendor/github.com/jtolds/gls/gen_sym.go | 21 - vendor/github.com/jtolds/gls/gid.go | 25 - vendor/github.com/jtolds/gls/id_pool.go | 34 - vendor/github.com/jtolds/gls/stack_tags.go | 147 - vendor/github.com/jtolds/gls/stack_tags_js.go | 75 - .../github.com/jtolds/gls/stack_tags_main.go | 30 - vendor/github.com/lib/pq/.gitignore | 6 - vendor/github.com/lib/pq/LICENSE.md | 8 - vendor/github.com/lib/pq/README.md | 36 - vendor/github.com/lib/pq/TESTS.md | 33 - vendor/github.com/lib/pq/array.go | 895 - vendor/github.com/lib/pq/buf.go | 91 - vendor/github.com/lib/pq/conn.go | 2060 - vendor/github.com/lib/pq/conn_go18.go | 247 - vendor/github.com/lib/pq/connector.go | 115 - vendor/github.com/lib/pq/copy.go | 303 - vendor/github.com/lib/pq/doc.go | 268 - vendor/github.com/lib/pq/encode.go | 628 - vendor/github.com/lib/pq/error.go | 518 - vendor/github.com/lib/pq/go.mod | 3 - vendor/github.com/lib/pq/krb.go | 27 - vendor/github.com/lib/pq/notice.go | 72 - vendor/github.com/lib/pq/notify.go | 858 - vendor/github.com/lib/pq/oid/doc.go | 6 - vendor/github.com/lib/pq/oid/types.go | 343 - vendor/github.com/lib/pq/rows.go | 93 - vendor/github.com/lib/pq/scram/scram.go | 264 - vendor/github.com/lib/pq/ssl.go | 193 - vendor/github.com/lib/pq/ssl_permissions.go | 21 - vendor/github.com/lib/pq/ssl_windows.go | 10 - vendor/github.com/lib/pq/url.go | 76 - vendor/github.com/lib/pq/user_posix.go | 25 - vendor/github.com/lib/pq/user_windows.go | 27 - vendor/github.com/lib/pq/uuid.go | 23 - vendor/github.com/mailru/easyjson/.gitignore | 6 - vendor/github.com/mailru/easyjson/.travis.yml | 15 - vendor/github.com/mailru/easyjson/LICENSE | 7 - vendor/github.com/mailru/easyjson/Makefile | 72 - vendor/github.com/mailru/easyjson/README.md | 387 - .../github.com/mailru/easyjson/buffer/pool.go | 278 - vendor/github.com/mailru/easyjson/go.mod | 5 - vendor/github.com/mailru/easyjson/go.sum | 2 - vendor/github.com/mailru/easyjson/helpers.go | 114 - .../mailru/easyjson/jlexer/bytestostr.go | 24 - .../easyjson/jlexer/bytestostr_nounsafe.go | 13 - .../mailru/easyjson/jlexer/error.go | 15 - .../mailru/easyjson/jlexer/lexer.go | 1244 - .../mailru/easyjson/jwriter/writer.go | 405 - vendor/github.com/mailru/easyjson/raw.go | 45 - .../mailru/easyjson/unknown_fields.go | 32 - vendor/github.com/mattn/go-sqlite3/.gitignore | 14 - .../github.com/mattn/go-sqlite3/.travis.yml | 33 - vendor/github.com/mattn/go-sqlite3/LICENSE | 21 - vendor/github.com/mattn/go-sqlite3/README.md | 572 - vendor/github.com/mattn/go-sqlite3/backup.go | 85 - .../github.com/mattn/go-sqlite3/callback.go | 398 - vendor/github.com/mattn/go-sqlite3/convert.go | 299 - vendor/github.com/mattn/go-sqlite3/doc.go | 112 - vendor/github.com/mattn/go-sqlite3/error.go | 150 - .../mattn/go-sqlite3/sqlite3-binding.c | 228809 --------------- .../mattn/go-sqlite3/sqlite3-binding.h | 12185 - vendor/github.com/mattn/go-sqlite3/sqlite3.go | 2112 - .../mattn/go-sqlite3/sqlite3_context.go | 103 - .../mattn/go-sqlite3/sqlite3_func_crypt.go | 120 - .../mattn/go-sqlite3/sqlite3_go18.go | 70 - .../mattn/go-sqlite3/sqlite3_libsqlite3.go | 18 - .../go-sqlite3/sqlite3_load_extension.go | 70 - .../go-sqlite3/sqlite3_load_extension_omit.go | 24 - .../sqlite3_opt_allow_uri_authority.go | 15 - .../mattn/go-sqlite3/sqlite3_opt_app_armor.go | 16 - .../go-sqlite3/sqlite3_opt_foreign_keys.go | 15 - .../mattn/go-sqlite3/sqlite3_opt_fts5.go | 14 - .../mattn/go-sqlite3/sqlite3_opt_icu.go | 17 - .../go-sqlite3/sqlite3_opt_introspect.go | 15 - .../mattn/go-sqlite3/sqlite3_opt_json1.go | 13 - .../mattn/go-sqlite3/sqlite3_opt_preupdate.go | 20 - .../go-sqlite3/sqlite3_opt_preupdate_hook.go | 112 - .../go-sqlite3/sqlite3_opt_preupdate_omit.go | 21 - .../go-sqlite3/sqlite3_opt_secure_delete.go | 15 - .../sqlite3_opt_secure_delete_fast.go | 15 - .../mattn/go-sqlite3/sqlite3_opt_stat4.go | 15 - .../go-sqlite3/sqlite3_opt_unlock_notify.c | 85 - .../go-sqlite3/sqlite3_opt_unlock_notify.go | 93 - .../mattn/go-sqlite3/sqlite3_opt_userauth.go | 289 - .../go-sqlite3/sqlite3_opt_userauth_omit.go | 152 - .../go-sqlite3/sqlite3_opt_vacuum_full.go | 15 - .../go-sqlite3/sqlite3_opt_vacuum_incr.go | 15 - .../mattn/go-sqlite3/sqlite3_opt_vtable.go | 650 - .../mattn/go-sqlite3/sqlite3_other.go | 17 - .../mattn/go-sqlite3/sqlite3_solaris.go | 14 - .../mattn/go-sqlite3/sqlite3_trace.go | 289 - .../mattn/go-sqlite3/sqlite3_type.go | 62 - .../go-sqlite3/sqlite3_usleep_windows.go | 39 - .../mattn/go-sqlite3/sqlite3_windows.go | 18 - .../github.com/mattn/go-sqlite3/sqlite3ext.h | 655 - .../mattn/go-sqlite3/static_mock.go | 26 - .../golang_protobuf_extensions/LICENSE | 201 - .../golang_protobuf_extensions/NOTICE | 1 - .../pbutil/.gitignore | 1 - .../pbutil/Makefile | 7 - .../pbutil/decode.go | 75 - .../golang_protobuf_extensions/pbutil/doc.go | 16 - .../pbutil/encode.go | 46 - .../modern-go/concurrent/.gitignore | 1 - .../modern-go/concurrent/.travis.yml | 14 - .../github.com/modern-go/concurrent/LICENSE | 201 - .../github.com/modern-go/concurrent/README.md | 49 - .../modern-go/concurrent/executor.go | 14 - .../modern-go/concurrent/go_above_19.go | 15 - .../modern-go/concurrent/go_below_19.go | 33 - vendor/github.com/modern-go/concurrent/log.go | 13 - .../github.com/modern-go/concurrent/test.sh | 12 - .../concurrent/unbounded_executor.go | 119 - .../github.com/modern-go/reflect2/.gitignore | 2 - .../github.com/modern-go/reflect2/.travis.yml | 15 - .../github.com/modern-go/reflect2/Gopkg.lock | 9 - .../github.com/modern-go/reflect2/Gopkg.toml | 31 - vendor/github.com/modern-go/reflect2/LICENSE | 201 - .../github.com/modern-go/reflect2/README.md | 71 - .../modern-go/reflect2/go_above_19.go | 17 - .../github.com/modern-go/reflect2/reflect2.go | 300 - .../modern-go/reflect2/reflect2_amd64.s | 0 .../modern-go/reflect2/reflect2_kind.go | 30 - .../modern-go/reflect2/relfect2_386.s | 0 .../modern-go/reflect2/relfect2_amd64p32.s | 0 .../modern-go/reflect2/relfect2_arm.s | 0 .../modern-go/reflect2/relfect2_arm64.s | 0 .../modern-go/reflect2/relfect2_mips64x.s | 0 .../modern-go/reflect2/relfect2_mipsx.s | 0 .../modern-go/reflect2/relfect2_ppc64x.s | 0 .../modern-go/reflect2/relfect2_s390x.s | 0 .../modern-go/reflect2/safe_field.go | 58 - .../github.com/modern-go/reflect2/safe_map.go | 101 - .../modern-go/reflect2/safe_slice.go | 92 - .../modern-go/reflect2/safe_struct.go | 29 - .../modern-go/reflect2/safe_type.go | 78 - .../github.com/modern-go/reflect2/type_map.go | 70 - .../modern-go/reflect2/unsafe_array.go | 65 - .../modern-go/reflect2/unsafe_eface.go | 59 - .../modern-go/reflect2/unsafe_field.go | 74 - .../modern-go/reflect2/unsafe_iface.go | 64 - .../modern-go/reflect2/unsafe_link.go | 76 - .../modern-go/reflect2/unsafe_map.go | 130 - .../modern-go/reflect2/unsafe_ptr.go | 46 - .../modern-go/reflect2/unsafe_slice.go | 177 - .../modern-go/reflect2/unsafe_struct.go | 59 - .../modern-go/reflect2/unsafe_type.go | 85 - .../github.com/olivere/elastic/v7/.gitignore | 38 - .../olivere/elastic/v7/CHANGELOG-3.0.md | 363 - .../olivere/elastic/v7/CHANGELOG-5.0.md | 195 - .../olivere/elastic/v7/CHANGELOG-6.0.md | 18 - .../olivere/elastic/v7/CHANGELOG-7.0.md | 55 - .../olivere/elastic/v7/CODE_OF_CONDUCT.md | 46 - .../olivere/elastic/v7/CONTRIBUTING.md | 40 - .../olivere/elastic/v7/CONTRIBUTORS | 213 - .../olivere/elastic/v7/ISSUE_TEMPLATE.md | 19 - vendor/github.com/olivere/elastic/v7/LICENSE | 20 - vendor/github.com/olivere/elastic/v7/Makefile | 3 - .../github.com/olivere/elastic/v7/README.md | 451 - .../elastic/v7/acknowledged_response.go | 13 - .../github.com/olivere/elastic/v7/backoff.go | 148 - vendor/github.com/olivere/elastic/v7/bulk.go | 470 - .../olivere/elastic/v7/bulk_create_request.go | 250 - .../v7/bulk_create_request_easyjson.go | 302 - .../olivere/elastic/v7/bulk_delete_request.go | 186 - .../v7/bulk_delete_request_easyjson.go | 262 - .../olivere/elastic/v7/bulk_index_request.go | 260 - .../elastic/v7/bulk_index_request_easyjson.go | 302 - .../olivere/elastic/v7/bulk_processor.go | 656 - .../olivere/elastic/v7/bulk_request.go | 17 - .../olivere/elastic/v7/bulk_update_request.go | 334 - .../v7/bulk_update_request_easyjson.go | 489 - .../olivere/elastic/v7/canonicalize.go | 39 - .../olivere/elastic/v7/cat_aliases.go | 222 - .../olivere/elastic/v7/cat_allocation.go | 239 - .../olivere/elastic/v7/cat_count.go | 215 - .../olivere/elastic/v7/cat_fielddata.go | 211 - .../olivere/elastic/v7/cat_health.go | 211 - .../olivere/elastic/v7/cat_indices.go | 531 - .../olivere/elastic/v7/cat_master.go | 191 - .../olivere/elastic/v7/cat_shards.go | 389 - .../olivere/elastic/v7/cat_snapshots.go | 250 - .../olivere/elastic/v7/clear_scroll.go | 162 - .../github.com/olivere/elastic/v7/client.go | 2348 - .../olivere/elastic/v7/cluster_health.go | 296 - .../olivere/elastic/v7/cluster_reroute.go | 438 - .../olivere/elastic/v7/cluster_state.go | 375 - .../olivere/elastic/v7/cluster_stats.go | 506 - .../olivere/elastic/v7/config/config.go | 87 - .../olivere/elastic/v7/config/doc.go | 9 - .../olivere/elastic/v7/connection.go | 90 - vendor/github.com/olivere/elastic/v7/count.go | 392 - .../github.com/olivere/elastic/v7/decoder.go | 38 - .../github.com/olivere/elastic/v7/delete.go | 305 - .../olivere/elastic/v7/delete_by_query.go | 792 - vendor/github.com/olivere/elastic/v7/doc.go | 51 - .../elastic/v7/docker-compose.cluster.yml | 78 - .../olivere/elastic/v7/docker-compose.yml | 61 - .../olivere/elastic/v7/docvalue_field.go | 42 - .../github.com/olivere/elastic/v7/errors.go | 240 - .../github.com/olivere/elastic/v7/exists.go | 236 - .../github.com/olivere/elastic/v7/explain.go | 390 - .../elastic/v7/fetch_source_context.go | 90 - .../olivere/elastic/v7/field_caps.go | 271 - .../olivere/elastic/v7/geo_point.go | 54 - vendor/github.com/olivere/elastic/v7/get.go | 317 - vendor/github.com/olivere/elastic/v7/go.mod | 26 - .../olivere/elastic/v7/highlight.go | 478 - vendor/github.com/olivere/elastic/v7/index.go | 377 - .../olivere/elastic/v7/indices_analyze.go | 320 - .../olivere/elastic/v7/indices_clear_cache.go | 240 - .../olivere/elastic/v7/indices_close.go | 214 - .../olivere/elastic/v7/indices_create.go | 199 - .../olivere/elastic/v7/indices_delete.go | 216 - .../v7/indices_delete_component_template.go | 182 - .../v7/indices_delete_index_template.go | 186 - .../elastic/v7/indices_delete_template.go | 190 - .../olivere/elastic/v7/indices_exists.go | 204 - .../elastic/v7/indices_exists_template.go | 183 - .../olivere/elastic/v7/indices_flush.go | 224 - .../elastic/v7/indices_flush_synced.go | 284 - .../olivere/elastic/v7/indices_forcemerge.go | 235 - .../olivere/elastic/v7/indices_freeze.go | 235 - .../olivere/elastic/v7/indices_get.go | 237 - .../olivere/elastic/v7/indices_get_aliases.go | 230 - .../v7/indices_get_component_template.go | 207 - .../elastic/v7/indices_get_field_mapping.go | 238 - .../elastic/v7/indices_get_index_template.go | 250 - .../olivere/elastic/v7/indices_get_mapping.go | 225 - .../elastic/v7/indices_get_settings.go | 238 - .../elastic/v7/indices_get_template.go | 194 - .../olivere/elastic/v7/indices_open.go | 227 - .../olivere/elastic/v7/indices_put_alias.go | 399 - .../v7/indices_put_component_template.go | 221 - .../elastic/v7/indices_put_index_template.go | 226 - .../olivere/elastic/v7/indices_put_mapping.go | 270 - .../elastic/v7/indices_put_settings.go | 242 - .../elastic/v7/indices_put_template.go | 279 - .../olivere/elastic/v7/indices_refresh.go | 149 - .../olivere/elastic/v7/indices_rollover.go | 324 - .../olivere/elastic/v7/indices_segments.go | 278 - .../olivere/elastic/v7/indices_shrink.go | 231 - .../olivere/elastic/v7/indices_stats.go | 539 - .../olivere/elastic/v7/indices_unfreeze.go | 235 - .../elastic/v7/ingest_delete_pipeline.go | 181 - .../olivere/elastic/v7/ingest_get_pipeline.go | 177 - .../olivere/elastic/v7/ingest_put_pipeline.go | 210 - .../elastic/v7/ingest_simulate_pipeline.go | 213 - .../olivere/elastic/v7/inner_hit.go | 175 - .../github.com/olivere/elastic/v7/logger.go | 10 - vendor/github.com/olivere/elastic/v7/mget.go | 314 - .../github.com/olivere/elastic/v7/msearch.go | 169 - .../olivere/elastic/v7/mtermvectors.go | 526 - .../olivere/elastic/v7/nodes_info.go | 419 - .../olivere/elastic/v7/nodes_stats.go | 733 - vendor/github.com/olivere/elastic/v7/ping.go | 200 - vendor/github.com/olivere/elastic/v7/pit.go | 47 - .../olivere/elastic/v7/pit_close.go | 176 - .../github.com/olivere/elastic/v7/pit_open.go | 247 - .../github.com/olivere/elastic/v7/plugins.go | 40 - vendor/github.com/olivere/elastic/v7/query.go | 13 - .../github.com/olivere/elastic/v7/reindex.go | 745 - .../github.com/olivere/elastic/v7/request.go | 121 - .../github.com/olivere/elastic/v7/rescore.go | 44 - .../github.com/olivere/elastic/v7/rescorer.go | 64 - .../github.com/olivere/elastic/v7/response.go | 66 - .../github.com/olivere/elastic/v7/retrier.go | 68 - vendor/github.com/olivere/elastic/v7/retry.go | 56 - .../olivere/elastic/v7/runtime_mappings.go | 16 - .../github.com/olivere/elastic/v7/script.go | 160 - .../olivere/elastic/v7/script_delete.go | 186 - .../olivere/elastic/v7/script_get.go | 169 - .../olivere/elastic/v7/script_put.go | 226 - .../github.com/olivere/elastic/v7/scroll.go | 668 - .../github.com/olivere/elastic/v7/search.go | 928 - .../olivere/elastic/v7/search_aggs.go | 1915 - .../v7/search_aggs_bucket_adjacency_matrix.go | 96 - .../search_aggs_bucket_auto_date_histogram.go | 163 - .../elastic/v7/search_aggs_bucket_children.go | 76 - .../v7/search_aggs_bucket_composite.go | 577 - .../v7/search_aggs_bucket_count_thresholds.go | 13 - .../v7/search_aggs_bucket_date_histogram.go | 341 - .../v7/search_aggs_bucket_date_range.go | 255 - .../search_aggs_bucket_diversified_sampler.go | 126 - .../elastic/v7/search_aggs_bucket_filter.go | 77 - .../elastic/v7/search_aggs_bucket_filters.go | 161 - .../v7/search_aggs_bucket_geo_distance.go | 198 - .../v7/search_aggs_bucket_geohash_grid.go | 104 - .../v7/search_aggs_bucket_geotile_grid.go | 119 - .../elastic/v7/search_aggs_bucket_global.go | 71 - .../v7/search_aggs_bucket_histogram.go | 265 - .../elastic/v7/search_aggs_bucket_ip_range.go | 195 - .../elastic/v7/search_aggs_bucket_missing.go | 81 - .../v7/search_aggs_bucket_multi_terms.go | 316 - .../elastic/v7/search_aggs_bucket_nested.go | 82 - .../elastic/v7/search_aggs_bucket_range.go | 244 - .../v7/search_aggs_bucket_rare_terms.go | 156 - .../v7/search_aggs_bucket_reverse_nested.go | 86 - .../elastic/v7/search_aggs_bucket_sampler.go | 92 - .../search_aggs_bucket_significant_terms.go | 450 - .../v7/search_aggs_bucket_significant_text.go | 250 - .../elastic/v7/search_aggs_bucket_terms.go | 422 - .../elastic/v7/search_aggs_matrix_stats.go | 126 - .../elastic/v7/search_aggs_metrics_avg.go | 112 - .../v7/search_aggs_metrics_cardinality.go | 127 - .../v7/search_aggs_metrics_extended_stats.go | 117 - .../v7/search_aggs_metrics_geo_bounds.go | 105 - .../v7/search_aggs_metrics_geo_centroid.go | 95 - .../elastic/v7/search_aggs_metrics_max.go | 108 - ..._aggs_metrics_median_absolute_deviation.go | 119 - .../elastic/v7/search_aggs_metrics_min.go | 109 - .../search_aggs_metrics_percentile_ranks.go | 140 - .../v7/search_aggs_metrics_percentiles.go | 169 - .../v7/search_aggs_metrics_scripted_metric.go | 112 - .../elastic/v7/search_aggs_metrics_stats.go | 108 - .../elastic/v7/search_aggs_metrics_sum.go | 108 - .../v7/search_aggs_metrics_top_hits.go | 161 - .../v7/search_aggs_metrics_top_metrics.go | 83 - .../v7/search_aggs_metrics_value_count.go | 102 - .../v7/search_aggs_metrics_weighted_avg.go | 156 - .../v7/search_aggs_pipeline_avg_bucket.go | 94 - .../v7/search_aggs_pipeline_bucket_script.go | 113 - .../search_aggs_pipeline_bucket_selector.go | 115 - .../v7/search_aggs_pipeline_bucket_sort.go | 119 - .../v7/search_aggs_pipeline_cumulative_sum.go | 71 - .../v7/search_aggs_pipeline_derivative.go | 105 - ...rch_aggs_pipeline_extended_stats_bucket.go | 107 - .../v7/search_aggs_pipeline_max_bucket.go | 95 - .../v7/search_aggs_pipeline_min_bucket.go | 95 - .../v7/search_aggs_pipeline_mov_avg.go | 378 - .../elastic/v7/search_aggs_pipeline_mov_fn.go | 132 - ...search_aggs_pipeline_percentiles_bucket.go | 104 - .../v7/search_aggs_pipeline_serial_diff.go | 105 - .../v7/search_aggs_pipeline_stats_bucket.go | 94 - .../v7/search_aggs_pipeline_sum_bucket.go | 94 - .../elastic/v7/search_collapse_builder.go | 72 - .../olivere/elastic/v7/search_queries_bool.go | 203 - .../elastic/v7/search_queries_boosting.go | 97 - .../v7/search_queries_combined_fields.go | 110 - .../elastic/v7/search_queries_common_terms.go | 143 - .../v7/search_queries_constant_score.go | 59 - .../elastic/v7/search_queries_dis_max.go | 104 - .../search_queries_distance_feature_query.go | 119 - .../elastic/v7/search_queries_exists.go | 49 - .../olivere/elastic/v7/search_queries_fsq.go | 159 - .../v7/search_queries_fsq_score_funcs.go | 582 - .../elastic/v7/search_queries_fuzzy.go | 120 - .../v7/search_queries_geo_bounding_box.go | 180 - .../elastic/v7/search_queries_geo_distance.go | 107 - .../elastic/v7/search_queries_geo_polygon.go | 72 - .../elastic/v7/search_queries_has_child.go | 131 - .../elastic/v7/search_queries_has_parent.go | 108 - .../olivere/elastic/v7/search_queries_ids.go | 79 - .../elastic/v7/search_queries_interval.go | 52 - .../v7/search_queries_interval_filter.go | 175 - .../search_queries_interval_rules_all_of.go | 82 - .../search_queries_interval_rules_any_of.go | 60 - .../v7/search_queries_interval_rules_match.go | 94 - .../search_queries_interval_rules_prefix.go | 57 - .../search_queries_interval_rules_wildcard.go | 57 - .../elastic/v7/search_queries_match.go | 189 - .../elastic/v7/search_queries_match_all.go | 65 - .../v7/search_queries_match_bool_prefix.go | 130 - .../elastic/v7/search_queries_match_none.go | 39 - .../elastic/v7/search_queries_match_phrase.go | 89 - .../v7/search_queries_match_phrase_prefix.go | 89 - .../v7/search_queries_more_like_this.go | 414 - .../elastic/v7/search_queries_multi_match.go | 270 - .../elastic/v7/search_queries_nested.go | 96 - .../elastic/v7/search_queries_parent_id.go | 99 - .../elastic/v7/search_queries_percolator.go | 131 - .../elastic/v7/search_queries_pinned.go | 61 - .../elastic/v7/search_queries_prefix.go | 76 - .../elastic/v7/search_queries_query_string.go | 350 - .../elastic/v7/search_queries_range.go | 155 - .../elastic/v7/search_queries_raw_string.go | 26 - .../elastic/v7/search_queries_regexp.go | 91 - .../elastic/v7/search_queries_script.go | 51 - .../elastic/v7/search_queries_script_score.go | 110 - .../v7/search_queries_simple_query_string.go | 246 - .../elastic/v7/search_queries_slice.go | 53 - .../elastic/v7/search_queries_span_first.go | 74 - .../elastic/v7/search_queries_span_near.go | 98 - .../elastic/v7/search_queries_span_term.go | 70 - .../olivere/elastic/v7/search_queries_term.go | 67 - .../elastic/v7/search_queries_terms.go | 88 - .../elastic/v7/search_queries_terms_set.go | 97 - .../olivere/elastic/v7/search_queries_type.go | 26 - .../elastic/v7/search_queries_wildcard.go | 92 - .../elastic/v7/search_queries_wrapper.go | 28 - .../olivere/elastic/v7/search_request.go | 593 - .../olivere/elastic/v7/search_shards.go | 258 - .../olivere/elastic/v7/search_source.go | 677 - .../olivere/elastic/v7/search_terms_lookup.go | 76 - .../olivere/elastic/v7/snapshot_create.go | 227 - .../elastic/v7/snapshot_create_repository.go | 257 - .../olivere/elastic/v7/snapshot_delete.go | 154 - .../elastic/v7/snapshot_delete_repository.go | 183 - .../olivere/elastic/v7/snapshot_get.go | 225 - .../elastic/v7/snapshot_get_repository.go | 185 - .../olivere/elastic/v7/snapshot_restore.go | 298 - .../olivere/elastic/v7/snapshot_status.go | 258 - .../elastic/v7/snapshot_verify_repository.go | 184 - vendor/github.com/olivere/elastic/v7/sort.go | 667 - .../olivere/elastic/v7/suggest_field.go | 90 - .../olivere/elastic/v7/suggester.go | 15 - .../elastic/v7/suggester_completion.go | 358 - .../olivere/elastic/v7/suggester_context.go | 124 - .../elastic/v7/suggester_context_category.go | 154 - .../elastic/v7/suggester_context_geo.go | 178 - .../olivere/elastic/v7/suggester_phrase.go | 550 - .../olivere/elastic/v7/suggester_term.go | 233 - .../olivere/elastic/v7/tasks_cancel.go | 207 - .../olivere/elastic/v7/tasks_get_task.go | 169 - .../olivere/elastic/v7/tasks_list.go | 276 - .../olivere/elastic/v7/termvectors.go | 520 - .../github.com/olivere/elastic/v7/update.go | 412 - .../olivere/elastic/v7/update_by_query.go | 783 - .../olivere/elastic/v7/uritemplates/LICENSE | 18 - .../elastic/v7/uritemplates/uritemplates.go | 359 - .../olivere/elastic/v7/uritemplates/utils.go | 13 - .../github.com/olivere/elastic/v7/validate.go | 339 - .../elastic/v7/xpack_async_search_delete.go | 154 - .../elastic/v7/xpack_async_search_get.go | 178 - .../elastic/v7/xpack_async_search_submit.go | 725 - .../elastic/v7/xpack_ilm_delete_lifecycle.go | 194 - .../elastic/v7/xpack_ilm_get_lifecycle.go | 203 - .../elastic/v7/xpack_ilm_put_lifecycle.go | 214 - .../olivere/elastic/v7/xpack_info.go | 225 - .../olivere/elastic/v7/xpack_rollup_delete.go | 159 - .../olivere/elastic/v7/xpack_rollup_get.go | 202 - .../olivere/elastic/v7/xpack_rollup_put.go | 170 - .../olivere/elastic/v7/xpack_rollup_start.go | 159 - .../olivere/elastic/v7/xpack_rollup_stop.go | 159 - .../v7/xpack_security_change_password.go | 201 - .../elastic/v7/xpack_security_delete_role.go | 159 - .../v7/xpack_security_delete_role_mapping.go | 159 - .../elastic/v7/xpack_security_delete_user.go | 170 - .../elastic/v7/xpack_security_disable_user.go | 168 - .../elastic/v7/xpack_security_enable_user.go | 168 - .../elastic/v7/xpack_security_get_role.go | 186 - .../v7/xpack_security_get_role_mapping.go | 165 - .../elastic/v7/xpack_security_get_user.go | 176 - .../elastic/v7/xpack_security_put_role.go | 174 - .../v7/xpack_security_put_role_mapping.go | 174 - .../elastic/v7/xpack_security_put_user.go | 210 - .../elastic/v7/xpack_watcher_ack_watch.go | 198 - .../v7/xpack_watcher_activate_watch.go | 169 - .../v7/xpack_watcher_deactivate_watch.go | 169 - .../elastic/v7/xpack_watcher_delete_watch.go | 171 - .../elastic/v7/xpack_watcher_execute_watch.go | 214 - .../elastic/v7/xpack_watcher_get_watch.go | 214 - .../elastic/v7/xpack_watcher_put_watch.go | 212 - .../olivere/elastic/v7/xpack_watcher_start.go | 137 - .../olivere/elastic/v7/xpack_watcher_stats.go | 165 - .../olivere/elastic/v7/xpack_watcher_stop.go | 137 - vendor/github.com/pkg/errors/.gitignore | 24 - vendor/github.com/pkg/errors/.travis.yml | 10 - vendor/github.com/pkg/errors/LICENSE | 23 - vendor/github.com/pkg/errors/Makefile | 44 - vendor/github.com/pkg/errors/README.md | 59 - vendor/github.com/pkg/errors/appveyor.yml | 32 - vendor/github.com/pkg/errors/errors.go | 288 - vendor/github.com/pkg/errors/go113.go | 38 - vendor/github.com/pkg/errors/stack.go | 177 - .../prometheus/client_golang/LICENSE | 201 - .../prometheus/client_golang/NOTICE | 23 - .../client_golang/prometheus/.gitignore | 1 - .../client_golang/prometheus/README.md | 1 - .../client_golang/prometheus/collector.go | 128 - .../client_golang/prometheus/counter.go | 325 - .../client_golang/prometheus/desc.go | 186 - .../client_golang/prometheus/doc.go | 199 - .../prometheus/expvar_collector.go | 86 - .../client_golang/prometheus/fnv.go | 42 - .../client_golang/prometheus/gauge.go | 289 - .../client_golang/prometheus/go_collector.go | 285 - .../client_golang/prometheus/histogram.go | 670 - .../prometheus/internal/metric.go | 85 - .../client_golang/prometheus/labels.go | 87 - .../client_golang/prometheus/metric.go | 176 - .../client_golang/prometheus/observer.go | 64 - .../prometheus/process_collector.go | 166 - .../prometheus/process_collector_other.go | 66 - .../prometheus/process_collector_windows.go | 116 - .../prometheus/promhttp/delegator.go | 368 - .../client_golang/prometheus/promhttp/http.go | 383 - .../prometheus/promhttp/instrument_client.go | 235 - .../prometheus/promhttp/instrument_server.go | 517 - .../client_golang/prometheus/registry.go | 950 - .../client_golang/prometheus/summary.go | 744 - .../client_golang/prometheus/timer.go | 54 - .../client_golang/prometheus/untyped.go | 42 - .../client_golang/prometheus/value.go | 212 - .../client_golang/prometheus/vec.go | 556 - .../client_golang/prometheus/wrap.go | 214 - .../prometheus/client_model/LICENSE | 201 - .../github.com/prometheus/client_model/NOTICE | 5 - .../prometheus/client_model/go/metrics.pb.go | 723 - vendor/github.com/prometheus/common/LICENSE | 201 - vendor/github.com/prometheus/common/NOTICE | 5 - .../prometheus/common/expfmt/decode.go | 429 - .../prometheus/common/expfmt/encode.go | 162 - .../prometheus/common/expfmt/expfmt.go | 41 - .../prometheus/common/expfmt/fuzz.go | 36 - .../common/expfmt/openmetrics_create.go | 527 - .../prometheus/common/expfmt/text_create.go | 465 - .../prometheus/common/expfmt/text_parse.go | 775 - .../bitbucket.org/ww/goautoneg/README.txt | 67 - .../bitbucket.org/ww/goautoneg/autoneg.go | 162 - .../prometheus/common/model/alert.go | 136 - .../prometheus/common/model/fingerprinting.go | 105 - .../github.com/prometheus/common/model/fnv.go | 42 - .../prometheus/common/model/labels.go | 218 - .../prometheus/common/model/labelset.go | 169 - .../prometheus/common/model/metric.go | 102 - .../prometheus/common/model/model.go | 16 - .../prometheus/common/model/signature.go | 144 - .../prometheus/common/model/silence.go | 106 - .../prometheus/common/model/time.go | 317 - .../prometheus/common/model/value.go | 416 - .../github.com/prometheus/procfs/.gitignore | 1 - .../prometheus/procfs/.golangci.yml | 4 - .../prometheus/procfs/CODE_OF_CONDUCT.md | 3 - .../prometheus/procfs/CONTRIBUTING.md | 121 - vendor/github.com/prometheus/procfs/LICENSE | 201 - .../prometheus/procfs/MAINTAINERS.md | 2 - vendor/github.com/prometheus/procfs/Makefile | 31 - .../prometheus/procfs/Makefile.common | 311 - vendor/github.com/prometheus/procfs/NOTICE | 7 - vendor/github.com/prometheus/procfs/README.md | 61 - vendor/github.com/prometheus/procfs/arp.go | 85 - .../github.com/prometheus/procfs/buddyinfo.go | 85 - .../github.com/prometheus/procfs/cpuinfo.go | 481 - .../prometheus/procfs/cpuinfo_armx.go | 19 - .../prometheus/procfs/cpuinfo_mipsx.go | 19 - .../prometheus/procfs/cpuinfo_others.go | 19 - .../prometheus/procfs/cpuinfo_ppcx.go | 19 - .../prometheus/procfs/cpuinfo_s390x.go | 18 - .../prometheus/procfs/cpuinfo_x86.go | 19 - vendor/github.com/prometheus/procfs/crypto.go | 153 - vendor/github.com/prometheus/procfs/doc.go | 45 - .../prometheus/procfs/fixtures.ttar | 7673 - vendor/github.com/prometheus/procfs/fs.go | 43 - .../github.com/prometheus/procfs/fscache.go | 422 - vendor/github.com/prometheus/procfs/go.mod | 9 - vendor/github.com/prometheus/procfs/go.sum | 8 - .../prometheus/procfs/internal/fs/fs.go | 55 - .../prometheus/procfs/internal/util/parse.go | 97 - .../procfs/internal/util/readfile.go | 38 - .../procfs/internal/util/sysreadfile.go | 48 - .../internal/util/sysreadfile_compat.go | 26 - .../procfs/internal/util/valueparser.go | 91 - vendor/github.com/prometheus/procfs/ipvs.go | 241 - .../prometheus/procfs/kernel_random.go | 62 - .../github.com/prometheus/procfs/loadavg.go | 62 - vendor/github.com/prometheus/procfs/mdstat.go | 262 - .../github.com/prometheus/procfs/meminfo.go | 277 - .../github.com/prometheus/procfs/mountinfo.go | 180 - .../prometheus/procfs/mountstats.go | 638 - .../prometheus/procfs/net_conntrackstat.go | 153 - .../github.com/prometheus/procfs/net_dev.go | 205 - .../prometheus/procfs/net_sockstat.go | 163 - .../prometheus/procfs/net_softnet.go | 102 - .../github.com/prometheus/procfs/net_udp.go | 64 - .../github.com/prometheus/procfs/net_unix.go | 257 - vendor/github.com/prometheus/procfs/proc.go | 319 - .../prometheus/procfs/proc_cgroup.go | 98 - .../prometheus/procfs/proc_environ.go | 37 - .../prometheus/procfs/proc_fdinfo.go | 133 - .../github.com/prometheus/procfs/proc_io.go | 59 - .../prometheus/procfs/proc_limits.go | 160 - .../github.com/prometheus/procfs/proc_maps.go | 209 - .../github.com/prometheus/procfs/proc_ns.go | 68 - .../github.com/prometheus/procfs/proc_psi.go | 100 - .../prometheus/procfs/proc_smaps.go | 165 - .../github.com/prometheus/procfs/proc_stat.go | 217 - .../prometheus/procfs/proc_status.go | 170 - .../github.com/prometheus/procfs/schedstat.go | 121 - vendor/github.com/prometheus/procfs/stat.go | 244 - vendor/github.com/prometheus/procfs/swaps.go | 89 - vendor/github.com/prometheus/procfs/ttar | 413 - vendor/github.com/prometheus/procfs/vm.go | 210 - vendor/github.com/prometheus/procfs/xfrm.go | 186 - .../github.com/prometheus/procfs/zoneinfo.go | 195 - vendor/github.com/shiena/ansicolor/.gitignore | 27 - vendor/github.com/shiena/ansicolor/LICENSE | 21 - vendor/github.com/shiena/ansicolor/README.md | 101 - .../github.com/shiena/ansicolor/ansicolor.go | 42 - .../shiena/ansicolor/ansicolor_ansi.go | 18 - .../shiena/ansicolor/ansicolor_windows.go | 417 - .../smartystreets/assertions/.gitignore | 4 - .../smartystreets/assertions/.travis.yml | 23 - .../smartystreets/assertions/CONTRIBUTING.md | 12 - .../smartystreets/assertions/LICENSE.md | 23 - .../smartystreets/assertions/Makefile | 14 - .../smartystreets/assertions/README.md | 4 - .../smartystreets/assertions/collections.go | 244 - .../smartystreets/assertions/doc.go | 109 - .../smartystreets/assertions/equal_method.go | 75 - .../smartystreets/assertions/equality.go | 331 - .../smartystreets/assertions/equality_diff.go | 37 - .../smartystreets/assertions/filter.go | 31 - .../smartystreets/assertions/go.mod | 3 - .../assertions/internal/go-diff/AUTHORS | 25 - .../assertions/internal/go-diff/CONTRIBUTORS | 32 - .../assertions/internal/go-diff/LICENSE | 20 - .../internal/go-diff/diffmatchpatch/diff.go | 1345 - .../go-diff/diffmatchpatch/diffmatchpatch.go | 46 - .../internal/go-diff/diffmatchpatch/match.go | 160 - .../go-diff/diffmatchpatch/mathutil.go | 23 - .../diffmatchpatch/operation_string.go | 17 - .../internal/go-diff/diffmatchpatch/patch.go | 556 - .../go-diff/diffmatchpatch/stringutil.go | 88 - .../assertions/internal/go-render/LICENSE | 27 - .../internal/go-render/render/render.go | 481 - .../internal/go-render/render/render_time.go | 26 - .../internal/oglematchers/.gitignore | 5 - .../internal/oglematchers/.travis.yml | 4 - .../assertions/internal/oglematchers/LICENSE | 202 - .../internal/oglematchers/README.md | 58 - .../internal/oglematchers/any_of.go | 94 - .../internal/oglematchers/contains.go | 61 - .../internal/oglematchers/deep_equals.go | 88 - .../internal/oglematchers/equals.go | 541 - .../internal/oglematchers/greater_or_equal.go | 39 - .../internal/oglematchers/greater_than.go | 39 - .../internal/oglematchers/less_or_equal.go | 41 - .../internal/oglematchers/less_than.go | 152 - .../internal/oglematchers/matcher.go | 86 - .../assertions/internal/oglematchers/not.go | 53 - .../oglematchers/transform_description.go | 36 - .../smartystreets/assertions/messages.go | 108 - .../smartystreets/assertions/panic.go | 128 - .../smartystreets/assertions/quantity.go | 141 - .../smartystreets/assertions/serializer.go | 70 - .../smartystreets/assertions/strings.go | 227 - .../smartystreets/assertions/time.go | 218 - .../smartystreets/assertions/type.go | 154 - .../smartystreets/goconvey/LICENSE.md | 23 - .../goconvey/convey/assertions.go | 73 - .../smartystreets/goconvey/convey/context.go | 290 - .../goconvey/convey/convey.goconvey | 4 - .../goconvey/convey/discovery.go | 112 - .../smartystreets/goconvey/convey/doc.go | 262 - .../goconvey/convey/gotest/utils.go | 28 - .../smartystreets/goconvey/convey/init.go | 81 - .../goconvey/convey/nilReporter.go | 15 - .../goconvey/convey/reporting/console.go | 16 - .../goconvey/convey/reporting/doc.go | 5 - .../goconvey/convey/reporting/dot.go | 40 - .../goconvey/convey/reporting/gotest.go | 33 - .../goconvey/convey/reporting/init.go | 95 - .../goconvey/convey/reporting/json.go | 88 - .../goconvey/convey/reporting/printer.go | 60 - .../goconvey/convey/reporting/problems.go | 83 - .../goconvey/convey/reporting/reporter.go | 39 - .../convey/reporting/reporting.goconvey | 2 - .../goconvey/convey/reporting/reports.go | 181 - .../goconvey/convey/reporting/statistics.go | 108 - .../goconvey/convey/reporting/story.go | 73 - .../github.com/ysicing/workwxbot/.gitignore | 26 - vendor/github.com/ysicing/workwxbot/Makefile | 67 - vendor/github.com/ysicing/workwxbot/README.md | 21 - vendor/github.com/ysicing/workwxbot/go.mod | 3 - .../github.com/ysicing/workwxbot/message.go | 160 - .../ysicing/workwxbot/workwechat.go | 141 - .../github.com/ysicing/workwxbot/workwxbot.go | 63 - vendor/golang.org/x/crypto/AUTHORS | 3 - vendor/golang.org/x/crypto/CONTRIBUTORS | 3 - vendor/golang.org/x/crypto/LICENSE | 27 - vendor/golang.org/x/crypto/PATENTS | 22 - vendor/golang.org/x/crypto/acme/acme.go | 1098 - .../x/crypto/acme/autocert/autocert.go | 1249 - .../x/crypto/acme/autocert/cache.go | 136 - .../x/crypto/acme/autocert/listener.go | 155 - .../x/crypto/acme/autocert/renewal.go | 141 - vendor/golang.org/x/crypto/acme/http.go | 321 - vendor/golang.org/x/crypto/acme/jws.go | 187 - vendor/golang.org/x/crypto/acme/rfc8555.go | 392 - vendor/golang.org/x/crypto/acme/types.go | 560 - .../golang.org/x/crypto/acme/version_go112.go | 27 - vendor/golang.org/x/net/AUTHORS | 3 - vendor/golang.org/x/net/CONTRIBUTORS | 3 - vendor/golang.org/x/net/LICENSE | 27 - vendor/golang.org/x/net/PATENTS | 22 - vendor/golang.org/x/net/idna/idna10.0.0.go | 770 - vendor/golang.org/x/net/idna/idna9.0.0.go | 718 - vendor/golang.org/x/net/idna/punycode.go | 217 - vendor/golang.org/x/net/idna/tables10.0.0.go | 4560 - vendor/golang.org/x/net/idna/tables11.0.0.go | 4654 - vendor/golang.org/x/net/idna/tables12.0.0.go | 4734 - vendor/golang.org/x/net/idna/tables13.0.0.go | 4840 - vendor/golang.org/x/net/idna/tables9.0.0.go | 4487 - vendor/golang.org/x/net/idna/trie.go | 72 - vendor/golang.org/x/net/idna/trieval.go | 119 - vendor/golang.org/x/sys/AUTHORS | 3 - vendor/golang.org/x/sys/CONTRIBUTORS | 3 - vendor/golang.org/x/sys/LICENSE | 27 - vendor/golang.org/x/sys/PATENTS | 22 - .../sys/internal/unsafeheader/unsafeheader.go | 30 - vendor/golang.org/x/sys/unix/.gitignore | 2 - vendor/golang.org/x/sys/unix/README.md | 184 - .../golang.org/x/sys/unix/affinity_linux.go | 86 - vendor/golang.org/x/sys/unix/aliases.go | 15 - vendor/golang.org/x/sys/unix/asm_aix_ppc64.s | 18 - vendor/golang.org/x/sys/unix/asm_bsd_386.s | 29 - vendor/golang.org/x/sys/unix/asm_bsd_amd64.s | 29 - vendor/golang.org/x/sys/unix/asm_bsd_arm.s | 29 - vendor/golang.org/x/sys/unix/asm_bsd_arm64.s | 29 - vendor/golang.org/x/sys/unix/asm_linux_386.s | 66 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 58 - vendor/golang.org/x/sys/unix/asm_linux_arm.s | 57 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 53 - .../golang.org/x/sys/unix/asm_linux_mips64x.s | 57 - .../golang.org/x/sys/unix/asm_linux_mipsx.s | 55 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 45 - .../golang.org/x/sys/unix/asm_linux_riscv64.s | 49 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 57 - .../x/sys/unix/asm_openbsd_mips64.s | 30 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 18 - vendor/golang.org/x/sys/unix/asm_zos_s390x.s | 426 - .../golang.org/x/sys/unix/bluetooth_linux.go | 36 - vendor/golang.org/x/sys/unix/cap_freebsd.go | 196 - vendor/golang.org/x/sys/unix/constants.go | 14 - vendor/golang.org/x/sys/unix/dev_aix_ppc.go | 27 - vendor/golang.org/x/sys/unix/dev_aix_ppc64.go | 29 - vendor/golang.org/x/sys/unix/dev_darwin.go | 24 - vendor/golang.org/x/sys/unix/dev_dragonfly.go | 30 - vendor/golang.org/x/sys/unix/dev_freebsd.go | 30 - vendor/golang.org/x/sys/unix/dev_linux.go | 42 - vendor/golang.org/x/sys/unix/dev_netbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_openbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_zos.go | 29 - vendor/golang.org/x/sys/unix/dirent.go | 103 - vendor/golang.org/x/sys/unix/endian_big.go | 10 - vendor/golang.org/x/sys/unix/endian_little.go | 10 - vendor/golang.org/x/sys/unix/env_unix.go | 32 - vendor/golang.org/x/sys/unix/epoll_zos.go | 221 - .../x/sys/unix/errors_freebsd_386.go | 233 - .../x/sys/unix/errors_freebsd_amd64.go | 233 - .../x/sys/unix/errors_freebsd_arm.go | 226 - .../x/sys/unix/errors_freebsd_arm64.go | 17 - vendor/golang.org/x/sys/unix/fcntl.go | 37 - vendor/golang.org/x/sys/unix/fcntl_darwin.go | 24 - .../x/sys/unix/fcntl_linux_32bit.go | 14 - vendor/golang.org/x/sys/unix/fdset.go | 30 - vendor/golang.org/x/sys/unix/fstatfs_zos.go | 164 - vendor/golang.org/x/sys/unix/gccgo.go | 60 - vendor/golang.org/x/sys/unix/gccgo_c.c | 45 - .../x/sys/unix/gccgo_linux_amd64.go | 21 - vendor/golang.org/x/sys/unix/ioctl.go | 75 - vendor/golang.org/x/sys/unix/ioctl_linux.go | 196 - vendor/golang.org/x/sys/unix/ioctl_zos.go | 74 - vendor/golang.org/x/sys/unix/mkall.sh | 231 - vendor/golang.org/x/sys/unix/mkerrors.sh | 765 - vendor/golang.org/x/sys/unix/pagesize_unix.go | 16 - .../golang.org/x/sys/unix/pledge_openbsd.go | 163 - vendor/golang.org/x/sys/unix/ptrace_darwin.go | 12 - vendor/golang.org/x/sys/unix/ptrace_ios.go | 12 - vendor/golang.org/x/sys/unix/race.go | 31 - vendor/golang.org/x/sys/unix/race0.go | 26 - .../x/sys/unix/readdirent_getdents.go | 13 - .../x/sys/unix/readdirent_getdirentries.go | 20 - .../x/sys/unix/sockcmsg_dragonfly.go | 16 - .../golang.org/x/sys/unix/sockcmsg_linux.go | 85 - vendor/golang.org/x/sys/unix/sockcmsg_unix.go | 93 - .../x/sys/unix/sockcmsg_unix_other.go | 47 - vendor/golang.org/x/sys/unix/str.go | 27 - vendor/golang.org/x/sys/unix/syscall.go | 95 - vendor/golang.org/x/sys/unix/syscall_aix.go | 551 - .../golang.org/x/sys/unix/syscall_aix_ppc.go | 54 - .../x/sys/unix/syscall_aix_ppc64.go | 85 - vendor/golang.org/x/sys/unix/syscall_bsd.go | 652 - .../x/sys/unix/syscall_darwin.1_12.go | 32 - .../x/sys/unix/syscall_darwin.1_13.go | 108 - .../golang.org/x/sys/unix/syscall_darwin.go | 772 - .../x/sys/unix/syscall_darwin_amd64.go | 51 - .../x/sys/unix/syscall_darwin_arm64.go | 51 - .../x/sys/unix/syscall_darwin_libSystem.go | 27 - .../x/sys/unix/syscall_dragonfly.go | 547 - .../x/sys/unix/syscall_dragonfly_amd64.go | 57 - .../golang.org/x/sys/unix/syscall_freebsd.go | 874 - .../x/sys/unix/syscall_freebsd_386.go | 67 - .../x/sys/unix/syscall_freebsd_amd64.go | 67 - .../x/sys/unix/syscall_freebsd_arm.go | 63 - .../x/sys/unix/syscall_freebsd_arm64.go | 63 - .../golang.org/x/sys/unix/syscall_illumos.go | 186 - vendor/golang.org/x/sys/unix/syscall_linux.go | 2416 - .../x/sys/unix/syscall_linux_386.go | 354 - .../x/sys/unix/syscall_linux_amd64.go | 151 - .../x/sys/unix/syscall_linux_amd64_gc.go | 13 - .../x/sys/unix/syscall_linux_arm.go | 249 - .../x/sys/unix/syscall_linux_arm64.go | 199 - .../golang.org/x/sys/unix/syscall_linux_gc.go | 15 - .../x/sys/unix/syscall_linux_gc_386.go | 17 - .../x/sys/unix/syscall_linux_gc_arm.go | 14 - .../x/sys/unix/syscall_linux_gccgo_386.go | 31 - .../x/sys/unix/syscall_linux_gccgo_arm.go | 21 - .../x/sys/unix/syscall_linux_mips64x.go | 196 - .../x/sys/unix/syscall_linux_mipsx.go | 208 - .../x/sys/unix/syscall_linux_ppc.go | 237 - .../x/sys/unix/syscall_linux_ppc64x.go | 123 - .../x/sys/unix/syscall_linux_riscv64.go | 184 - .../x/sys/unix/syscall_linux_s390x.go | 311 - .../x/sys/unix/syscall_linux_sparc64.go | 119 - .../golang.org/x/sys/unix/syscall_netbsd.go | 614 - .../x/sys/unix/syscall_netbsd_386.go | 38 - .../x/sys/unix/syscall_netbsd_amd64.go | 38 - .../x/sys/unix/syscall_netbsd_arm.go | 38 - .../x/sys/unix/syscall_netbsd_arm64.go | 38 - .../golang.org/x/sys/unix/syscall_openbsd.go | 392 - .../x/sys/unix/syscall_openbsd_386.go | 42 - .../x/sys/unix/syscall_openbsd_amd64.go | 42 - .../x/sys/unix/syscall_openbsd_arm.go | 42 - .../x/sys/unix/syscall_openbsd_arm64.go | 42 - .../x/sys/unix/syscall_openbsd_mips64.go | 35 - .../golang.org/x/sys/unix/syscall_solaris.go | 982 - .../x/sys/unix/syscall_solaris_amd64.go | 28 - vendor/golang.org/x/sys/unix/syscall_unix.go | 435 - .../golang.org/x/sys/unix/syscall_unix_gc.go | 18 - .../x/sys/unix/syscall_unix_gc_ppc64x.go | 25 - .../x/sys/unix/syscall_zos_s390x.go | 1823 - vendor/golang.org/x/sys/unix/timestruct.go | 77 - .../golang.org/x/sys/unix/unveil_openbsd.go | 42 - vendor/golang.org/x/sys/unix/xattr_bsd.go | 241 - .../golang.org/x/sys/unix/zerrors_aix_ppc.go | 1385 - .../x/sys/unix/zerrors_aix_ppc64.go | 1386 - .../x/sys/unix/zerrors_darwin_amd64.go | 1892 - .../x/sys/unix/zerrors_darwin_arm64.go | 1892 - .../x/sys/unix/zerrors_dragonfly_amd64.go | 1738 - .../x/sys/unix/zerrors_freebsd_386.go | 1948 - .../x/sys/unix/zerrors_freebsd_amd64.go | 1947 - .../x/sys/unix/zerrors_freebsd_arm.go | 1846 - .../x/sys/unix/zerrors_freebsd_arm64.go | 1948 - vendor/golang.org/x/sys/unix/zerrors_linux.go | 3035 - .../x/sys/unix/zerrors_linux_386.go | 826 - .../x/sys/unix/zerrors_linux_amd64.go | 826 - .../x/sys/unix/zerrors_linux_arm.go | 832 - .../x/sys/unix/zerrors_linux_arm64.go | 823 - .../x/sys/unix/zerrors_linux_mips.go | 833 - .../x/sys/unix/zerrors_linux_mips64.go | 833 - .../x/sys/unix/zerrors_linux_mips64le.go | 833 - .../x/sys/unix/zerrors_linux_mipsle.go | 833 - .../x/sys/unix/zerrors_linux_ppc.go | 885 - .../x/sys/unix/zerrors_linux_ppc64.go | 889 - .../x/sys/unix/zerrors_linux_ppc64le.go | 889 - .../x/sys/unix/zerrors_linux_riscv64.go | 813 - .../x/sys/unix/zerrors_linux_s390x.go | 888 - .../x/sys/unix/zerrors_linux_sparc64.go | 883 - .../x/sys/unix/zerrors_netbsd_386.go | 1780 - .../x/sys/unix/zerrors_netbsd_amd64.go | 1770 - .../x/sys/unix/zerrors_netbsd_arm.go | 1759 - .../x/sys/unix/zerrors_netbsd_arm64.go | 1770 - .../x/sys/unix/zerrors_openbsd_386.go | 1668 - .../x/sys/unix/zerrors_openbsd_amd64.go | 1775 - .../x/sys/unix/zerrors_openbsd_arm.go | 1670 - .../x/sys/unix/zerrors_openbsd_arm64.go | 1798 - .../x/sys/unix/zerrors_openbsd_mips64.go | 1863 - .../x/sys/unix/zerrors_solaris_amd64.go | 1557 - .../x/sys/unix/zerrors_zos_s390x.go | 860 - .../x/sys/unix/zptrace_armnn_linux.go | 42 - .../x/sys/unix/zptrace_linux_arm64.go | 17 - .../x/sys/unix/zptrace_mipsnn_linux.go | 51 - .../x/sys/unix/zptrace_mipsnnle_linux.go | 51 - .../x/sys/unix/zptrace_x86_linux.go | 81 - .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1485 - .../x/sys/unix/zsyscall_aix_ppc64.go | 1443 - .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 1192 - .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 1070 - .../x/sys/unix/zsyscall_darwin_amd64.1_13.go | 40 - .../x/sys/unix/zsyscall_darwin_amd64.1_13.s | 25 - .../x/sys/unix/zsyscall_darwin_amd64.go | 2490 - .../x/sys/unix/zsyscall_darwin_amd64.s | 883 - .../x/sys/unix/zsyscall_darwin_arm64.1_13.go | 40 - .../x/sys/unix/zsyscall_darwin_arm64.1_13.s | 25 - .../x/sys/unix/zsyscall_darwin_arm64.go | 2490 - .../x/sys/unix/zsyscall_darwin_arm64.s | 883 - .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1679 - .../x/sys/unix/zsyscall_freebsd_386.go | 2016 - .../x/sys/unix/zsyscall_freebsd_amd64.go | 2016 - .../x/sys/unix/zsyscall_freebsd_arm.go | 2016 - .../x/sys/unix/zsyscall_freebsd_arm64.go | 2016 - .../x/sys/unix/zsyscall_illumos_amd64.go | 128 - .../golang.org/x/sys/unix/zsyscall_linux.go | 2034 - .../x/sys/unix/zsyscall_linux_386.go | 526 - .../x/sys/unix/zsyscall_linux_amd64.go | 693 - .../x/sys/unix/zsyscall_linux_arm.go | 663 - .../x/sys/unix/zsyscall_linux_arm64.go | 603 - .../x/sys/unix/zsyscall_linux_mips.go | 704 - .../x/sys/unix/zsyscall_linux_mips64.go | 698 - .../x/sys/unix/zsyscall_linux_mips64le.go | 698 - .../x/sys/unix/zsyscall_linux_mipsle.go | 704 - .../x/sys/unix/zsyscall_linux_ppc.go | 709 - .../x/sys/unix/zsyscall_linux_ppc64.go | 755 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 755 - .../x/sys/unix/zsyscall_linux_riscv64.go | 583 - .../x/sys/unix/zsyscall_linux_s390x.go | 535 - .../x/sys/unix/zsyscall_linux_sparc64.go | 699 - .../x/sys/unix/zsyscall_netbsd_386.go | 1850 - .../x/sys/unix/zsyscall_netbsd_amd64.go | 1850 - .../x/sys/unix/zsyscall_netbsd_arm.go | 1850 - .../x/sys/unix/zsyscall_netbsd_arm64.go | 1850 - .../x/sys/unix/zsyscall_openbsd_386.go | 1693 - .../x/sys/unix/zsyscall_openbsd_amd64.go | 1693 - .../x/sys/unix/zsyscall_openbsd_arm.go | 1693 - .../x/sys/unix/zsyscall_openbsd_arm64.go | 1693 - .../x/sys/unix/zsyscall_openbsd_mips64.go | 1693 - .../x/sys/unix/zsyscall_solaris_amd64.go | 2053 - .../x/sys/unix/zsyscall_zos_s390x.go | 1255 - .../x/sys/unix/zsysctl_openbsd_386.go | 274 - .../x/sys/unix/zsysctl_openbsd_amd64.go | 272 - .../x/sys/unix/zsysctl_openbsd_arm.go | 274 - .../x/sys/unix/zsysctl_openbsd_arm64.go | 276 - .../x/sys/unix/zsysctl_openbsd_mips64.go | 280 - .../x/sys/unix/zsysnum_darwin_amd64.go | 440 - .../x/sys/unix/zsysnum_darwin_arm64.go | 438 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 317 - .../x/sys/unix/zsysnum_freebsd_386.go | 397 - .../x/sys/unix/zsysnum_freebsd_amd64.go | 397 - .../x/sys/unix/zsysnum_freebsd_arm.go | 397 - .../x/sys/unix/zsysnum_freebsd_arm64.go | 397 - .../x/sys/unix/zsysnum_linux_386.go | 449 - .../x/sys/unix/zsysnum_linux_amd64.go | 371 - .../x/sys/unix/zsysnum_linux_arm.go | 413 - .../x/sys/unix/zsysnum_linux_arm64.go | 316 - .../x/sys/unix/zsysnum_linux_mips.go | 433 - .../x/sys/unix/zsysnum_linux_mips64.go | 363 - .../x/sys/unix/zsysnum_linux_mips64le.go | 363 - .../x/sys/unix/zsysnum_linux_mipsle.go | 433 - .../x/sys/unix/zsysnum_linux_ppc.go | 440 - .../x/sys/unix/zsysnum_linux_ppc64.go | 412 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 412 - .../x/sys/unix/zsysnum_linux_riscv64.go | 314 - .../x/sys/unix/zsysnum_linux_s390x.go | 377 - .../x/sys/unix/zsysnum_linux_sparc64.go | 391 - .../x/sys/unix/zsysnum_netbsd_386.go | 275 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 275 - .../x/sys/unix/zsysnum_netbsd_arm.go | 275 - .../x/sys/unix/zsysnum_netbsd_arm64.go | 275 - .../x/sys/unix/zsysnum_openbsd_386.go | 219 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 219 - .../x/sys/unix/zsysnum_openbsd_arm.go | 219 - .../x/sys/unix/zsysnum_openbsd_arm64.go | 218 - .../x/sys/unix/zsysnum_openbsd_mips64.go | 221 - .../x/sys/unix/zsysnum_zos_s390x.go | 2670 - .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 354 - .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 358 - .../x/sys/unix/ztypes_darwin_amd64.go | 768 - .../x/sys/unix/ztypes_darwin_arm64.go | 768 - .../x/sys/unix/ztypes_dragonfly_amd64.go | 474 - .../x/sys/unix/ztypes_freebsd_386.go | 723 - .../x/sys/unix/ztypes_freebsd_amd64.go | 726 - .../x/sys/unix/ztypes_freebsd_arm.go | 707 - .../x/sys/unix/ztypes_freebsd_arm64.go | 704 - .../x/sys/unix/ztypes_illumos_amd64.go | 42 - vendor/golang.org/x/sys/unix/ztypes_linux.go | 4067 - .../golang.org/x/sys/unix/ztypes_linux_386.go | 670 - .../x/sys/unix/ztypes_linux_amd64.go | 685 - .../golang.org/x/sys/unix/ztypes_linux_arm.go | 665 - .../x/sys/unix/ztypes_linux_arm64.go | 664 - .../x/sys/unix/ztypes_linux_mips.go | 670 - .../x/sys/unix/ztypes_linux_mips64.go | 667 - .../x/sys/unix/ztypes_linux_mips64le.go | 667 - .../x/sys/unix/ztypes_linux_mipsle.go | 670 - .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 678 - .../x/sys/unix/ztypes_linux_ppc64.go | 673 - .../x/sys/unix/ztypes_linux_ppc64le.go | 673 - .../x/sys/unix/ztypes_linux_riscv64.go | 692 - .../x/sys/unix/ztypes_linux_s390x.go | 687 - .../x/sys/unix/ztypes_linux_sparc64.go | 668 - .../x/sys/unix/ztypes_netbsd_386.go | 502 - .../x/sys/unix/ztypes_netbsd_amd64.go | 510 - .../x/sys/unix/ztypes_netbsd_arm.go | 507 - .../x/sys/unix/ztypes_netbsd_arm64.go | 510 - .../x/sys/unix/ztypes_openbsd_386.go | 574 - .../x/sys/unix/ztypes_openbsd_amd64.go | 574 - .../x/sys/unix/ztypes_openbsd_arm.go | 575 - .../x/sys/unix/ztypes_openbsd_arm64.go | 568 - .../x/sys/unix/ztypes_openbsd_mips64.go | 568 - .../x/sys/unix/ztypes_solaris_amd64.go | 482 - .../golang.org/x/sys/unix/ztypes_zos_s390x.go | 406 - vendor/golang.org/x/sys/windows/aliases.go | 13 - .../golang.org/x/sys/windows/dll_windows.go | 416 - vendor/golang.org/x/sys/windows/empty.s | 9 - .../golang.org/x/sys/windows/env_windows.go | 54 - vendor/golang.org/x/sys/windows/eventlog.go | 21 - .../golang.org/x/sys/windows/exec_windows.go | 178 - .../x/sys/windows/memory_windows.go | 48 - vendor/golang.org/x/sys/windows/mkerrors.bash | 70 - .../x/sys/windows/mkknownfolderids.bash | 27 - vendor/golang.org/x/sys/windows/mksyscall.go | 10 - vendor/golang.org/x/sys/windows/race.go | 31 - vendor/golang.org/x/sys/windows/race0.go | 26 - .../x/sys/windows/security_windows.go | 1444 - vendor/golang.org/x/sys/windows/service.go | 247 - vendor/golang.org/x/sys/windows/str.go | 23 - vendor/golang.org/x/sys/windows/syscall.go | 113 - .../x/sys/windows/syscall_windows.go | 1689 - .../golang.org/x/sys/windows/types_windows.go | 3176 - .../x/sys/windows/types_windows_386.go | 35 - .../x/sys/windows/types_windows_amd64.go | 34 - .../x/sys/windows/types_windows_arm.go | 35 - .../x/sys/windows/types_windows_arm64.go | 34 - .../x/sys/windows/zerrors_windows.go | 9468 - .../x/sys/windows/zknownfolderids_windows.go | 149 - .../x/sys/windows/zsyscall_windows.go | 4196 - vendor/golang.org/x/text/AUTHORS | 3 - vendor/golang.org/x/text/CONTRIBUTORS | 3 - vendor/golang.org/x/text/LICENSE | 27 - vendor/golang.org/x/text/PATENTS | 22 - .../x/text/secure/bidirule/bidirule.go | 336 - .../x/text/secure/bidirule/bidirule10.0.0.go | 12 - .../x/text/secure/bidirule/bidirule9.0.0.go | 15 - .../golang.org/x/text/transform/transform.go | 709 - vendor/golang.org/x/text/unicode/bidi/bidi.go | 359 - .../golang.org/x/text/unicode/bidi/bracket.go | 335 - vendor/golang.org/x/text/unicode/bidi/core.go | 1071 - vendor/golang.org/x/text/unicode/bidi/prop.go | 206 - .../x/text/unicode/bidi/tables10.0.0.go | 1816 - .../x/text/unicode/bidi/tables11.0.0.go | 1888 - .../x/text/unicode/bidi/tables12.0.0.go | 1924 - .../x/text/unicode/bidi/tables13.0.0.go | 1956 - .../x/text/unicode/bidi/tables9.0.0.go | 1782 - .../golang.org/x/text/unicode/bidi/trieval.go | 60 - .../x/text/unicode/norm/composition.go | 512 - .../x/text/unicode/norm/forminfo.go | 278 - .../golang.org/x/text/unicode/norm/input.go | 109 - vendor/golang.org/x/text/unicode/norm/iter.go | 458 - .../x/text/unicode/norm/normalize.go | 609 - .../x/text/unicode/norm/readwriter.go | 125 - .../x/text/unicode/norm/tables10.0.0.go | 7658 - .../x/text/unicode/norm/tables11.0.0.go | 7694 - .../x/text/unicode/norm/tables12.0.0.go | 7711 - .../x/text/unicode/norm/tables13.0.0.go | 7761 - .../x/text/unicode/norm/tables9.0.0.go | 7638 - .../x/text/unicode/norm/transform.go | 88 - vendor/golang.org/x/text/unicode/norm/trie.go | 54 - vendor/google.golang.org/protobuf/AUTHORS | 3 - .../google.golang.org/protobuf/CONTRIBUTORS | 3 - vendor/google.golang.org/protobuf/LICENSE | 27 - vendor/google.golang.org/protobuf/PATENTS | 22 - .../protobuf/encoding/prototext/decode.go | 773 - .../protobuf/encoding/prototext/doc.go | 7 - .../protobuf/encoding/prototext/encode.go | 371 - .../protobuf/encoding/protowire/wire.go | 538 - .../protobuf/internal/descfmt/stringer.go | 318 - .../protobuf/internal/descopts/options.go | 29 - .../protobuf/internal/detrand/rand.go | 69 - .../internal/encoding/defval/default.go | 213 - .../encoding/messageset/messageset.go | 241 - .../protobuf/internal/encoding/tag/tag.go | 207 - .../protobuf/internal/encoding/text/decode.go | 665 - .../internal/encoding/text/decode_number.go | 190 - .../internal/encoding/text/decode_string.go | 161 - .../internal/encoding/text/decode_token.go | 373 - .../protobuf/internal/encoding/text/doc.go | 29 - .../protobuf/internal/encoding/text/encode.go | 265 - .../protobuf/internal/errors/errors.go | 89 - .../protobuf/internal/errors/is_go112.go | 39 - .../protobuf/internal/errors/is_go113.go | 12 - .../protobuf/internal/filedesc/build.go | 158 - .../protobuf/internal/filedesc/desc.go | 631 - .../protobuf/internal/filedesc/desc_init.go | 471 - .../protobuf/internal/filedesc/desc_lazy.go | 704 - .../protobuf/internal/filedesc/desc_list.go | 450 - .../internal/filedesc/desc_list_gen.go | 356 - .../protobuf/internal/filedesc/placeholder.go | 107 - .../protobuf/internal/filetype/build.go | 297 - .../protobuf/internal/flags/flags.go | 24 - .../internal/flags/proto_legacy_disable.go | 9 - .../internal/flags/proto_legacy_enable.go | 9 - .../protobuf/internal/genid/any_gen.go | 34 - .../protobuf/internal/genid/api_gen.go | 106 - .../protobuf/internal/genid/descriptor_gen.go | 829 - .../protobuf/internal/genid/doc.go | 11 - .../protobuf/internal/genid/duration_gen.go | 34 - .../protobuf/internal/genid/empty_gen.go | 19 - .../protobuf/internal/genid/field_mask_gen.go | 31 - .../protobuf/internal/genid/goname.go | 25 - .../protobuf/internal/genid/map_entry.go | 16 - .../internal/genid/source_context_gen.go | 31 - .../protobuf/internal/genid/struct_gen.go | 116 - .../protobuf/internal/genid/timestamp_gen.go | 34 - .../protobuf/internal/genid/type_gen.go | 184 - .../protobuf/internal/genid/wrappers.go | 13 - .../protobuf/internal/genid/wrappers_gen.go | 175 - .../protobuf/internal/impl/api_export.go | 177 - .../protobuf/internal/impl/checkinit.go | 141 - .../protobuf/internal/impl/codec_extension.go | 223 - .../protobuf/internal/impl/codec_field.go | 830 - .../protobuf/internal/impl/codec_gen.go | 5637 - .../protobuf/internal/impl/codec_map.go | 388 - .../protobuf/internal/impl/codec_map_go111.go | 37 - .../protobuf/internal/impl/codec_map_go112.go | 11 - .../protobuf/internal/impl/codec_message.go | 217 - .../internal/impl/codec_messageset.go | 123 - .../protobuf/internal/impl/codec_reflect.go | 209 - .../protobuf/internal/impl/codec_tables.go | 557 - .../protobuf/internal/impl/codec_unsafe.go | 17 - .../protobuf/internal/impl/convert.go | 496 - .../protobuf/internal/impl/convert_list.go | 141 - .../protobuf/internal/impl/convert_map.go | 121 - .../protobuf/internal/impl/decode.go | 276 - .../protobuf/internal/impl/encode.go | 201 - .../protobuf/internal/impl/enum.go | 21 - .../protobuf/internal/impl/extension.go | 156 - .../protobuf/internal/impl/legacy_enum.go | 219 - .../protobuf/internal/impl/legacy_export.go | 92 - .../internal/impl/legacy_extension.go | 176 - .../protobuf/internal/impl/legacy_file.go | 81 - .../protobuf/internal/impl/legacy_message.go | 558 - .../protobuf/internal/impl/merge.go | 176 - .../protobuf/internal/impl/merge_gen.go | 209 - .../protobuf/internal/impl/message.go | 276 - .../protobuf/internal/impl/message_reflect.go | 465 - .../internal/impl/message_reflect_field.go | 543 - .../internal/impl/message_reflect_gen.go | 249 - .../protobuf/internal/impl/pointer_reflect.go | 178 - .../protobuf/internal/impl/pointer_unsafe.go | 174 - .../protobuf/internal/impl/validate.go | 576 - .../protobuf/internal/impl/weak.go | 74 - .../protobuf/internal/pragma/pragma.go | 29 - .../protobuf/internal/set/ints.go | 58 - .../protobuf/internal/strs/strings.go | 196 - .../protobuf/internal/strs/strings_pure.go | 27 - .../protobuf/internal/strs/strings_unsafe.go | 94 - .../protobuf/internal/version/version.go | 79 - .../protobuf/proto/checkinit.go | 71 - .../protobuf/proto/decode.go | 278 - .../protobuf/proto/decode_gen.go | 603 - .../google.golang.org/protobuf/proto/doc.go | 94 - .../protobuf/proto/encode.go | 319 - .../protobuf/proto/encode_gen.go | 97 - .../google.golang.org/protobuf/proto/equal.go | 167 - .../protobuf/proto/extension.go | 92 - .../google.golang.org/protobuf/proto/merge.go | 139 - .../protobuf/proto/messageset.go | 93 - .../google.golang.org/protobuf/proto/proto.go | 43 - .../protobuf/proto/proto_methods.go | 19 - .../protobuf/proto/proto_reflect.go | 19 - .../google.golang.org/protobuf/proto/reset.go | 43 - .../google.golang.org/protobuf/proto/size.go | 97 - .../protobuf/proto/size_gen.go | 55 - .../protobuf/proto/wrappers.go | 29 - .../protobuf/reflect/protoreflect/methods.go | 77 - .../protobuf/reflect/protoreflect/proto.go | 504 - .../protobuf/reflect/protoreflect/source.go | 128 - .../protobuf/reflect/protoreflect/type.go | 665 - .../protobuf/reflect/protoreflect/value.go | 285 - .../reflect/protoreflect/value_pure.go | 59 - .../reflect/protoreflect/value_union.go | 411 - .../reflect/protoreflect/value_unsafe.go | 98 - .../reflect/protoregistry/registry.go | 869 - .../protobuf/runtime/protoiface/legacy.go | 15 - .../protobuf/runtime/protoiface/methods.go | 167 - .../protobuf/runtime/protoimpl/impl.go | 44 - .../protobuf/runtime/protoimpl/version.go | 56 - .../protobuf/types/known/anypb/any.pb.go | 498 - .../types/known/durationpb/duration.pb.go | 379 - .../types/known/timestamppb/timestamp.pb.go | 390 - .../alexcesaro/quotedprintable.v3/LICENSE | 20 - .../alexcesaro/quotedprintable.v3/README.md | 16 - .../quotedprintable.v3/encodedword.go | 279 - .../alexcesaro/quotedprintable.v3/pool.go | 26 - .../quotedprintable.v3/pool_go12.go | 24 - .../alexcesaro/quotedprintable.v3/reader.go | 121 - .../alexcesaro/quotedprintable.v3/writer.go | 166 - vendor/gopkg.in/ini.v1/.gitignore | 6 - vendor/gopkg.in/ini.v1/LICENSE | 191 - vendor/gopkg.in/ini.v1/Makefile | 15 - vendor/gopkg.in/ini.v1/README.md | 43 - vendor/gopkg.in/ini.v1/error.go | 34 - vendor/gopkg.in/ini.v1/file.go | 524 - vendor/gopkg.in/ini.v1/ini.go | 176 - vendor/gopkg.in/ini.v1/key.go | 828 - vendor/gopkg.in/ini.v1/parser.go | 513 - vendor/gopkg.in/ini.v1/section.go | 256 - vendor/gopkg.in/ini.v1/struct.go | 747 - vendor/gopkg.in/yaml.v2/.travis.yml | 17 - vendor/gopkg.in/yaml.v2/LICENSE | 201 - vendor/gopkg.in/yaml.v2/LICENSE.libyaml | 31 - vendor/gopkg.in/yaml.v2/NOTICE | 13 - vendor/gopkg.in/yaml.v2/README.md | 133 - vendor/gopkg.in/yaml.v2/apic.go | 744 - vendor/gopkg.in/yaml.v2/decode.go | 815 - vendor/gopkg.in/yaml.v2/emitterc.go | 1685 - vendor/gopkg.in/yaml.v2/encode.go | 390 - vendor/gopkg.in/yaml.v2/go.mod | 5 - vendor/gopkg.in/yaml.v2/parserc.go | 1095 - vendor/gopkg.in/yaml.v2/readerc.go | 412 - vendor/gopkg.in/yaml.v2/resolve.go | 258 - vendor/gopkg.in/yaml.v2/scannerc.go | 2711 - vendor/gopkg.in/yaml.v2/sorter.go | 113 - vendor/gopkg.in/yaml.v2/writerc.go | 26 - vendor/gopkg.in/yaml.v2/yaml.go | 478 - vendor/gopkg.in/yaml.v2/yamlh.go | 739 - vendor/gopkg.in/yaml.v2/yamlprivateh.go | 173 - vendor/modules.txt | 180 - 1587 files changed, 34 insertions(+), 757860 deletions(-) delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/api_timeout.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/bearer_token_credential.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/env.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/instance_credentials.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/profile_credentials.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider_chain.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_bearer_token.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/logger.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_request.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/debug.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_sign.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_template.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/client.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_sign.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_template.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/endpoint.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_sign.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_template.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_send_details.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_sign.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_template.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_batch_sms.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_sms.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dt_os.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dto.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/add_rtc_account.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/batch_robot_smart_call.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/bind_number_and_voip_id.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_call.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_order_robot_task.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_robot_task.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/click_to_dial.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/client.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/create_robot_task.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/delete_robot_task.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/endpoint.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/get_rtc_token.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/ivr_call.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_call_id.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_task_id.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_info_list.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_detail.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_list.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_detail.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_list.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robotv2_all_list.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_voip_number_bind_infos.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/report_voip_problems.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_tts.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_voice.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call_operate.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/start_robot_task.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/stop_robot_task.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/unbind_number_and_voip_id.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/upload_robot_task_called_file.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_add_account.go delete mode 100644 vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_get_token.go delete mode 100644 vendor/github.com/astaxie/beego/.gitignore delete mode 100644 vendor/github.com/astaxie/beego/.travis.yml delete mode 100644 vendor/github.com/astaxie/beego/CONTRIBUTING.md delete mode 100644 vendor/github.com/astaxie/beego/LICENSE delete mode 100644 vendor/github.com/astaxie/beego/README.md delete mode 100644 vendor/github.com/astaxie/beego/admin.go delete mode 100644 vendor/github.com/astaxie/beego/adminui.go delete mode 100644 vendor/github.com/astaxie/beego/app.go delete mode 100644 vendor/github.com/astaxie/beego/beego.go delete mode 100644 vendor/github.com/astaxie/beego/config.go delete mode 100644 vendor/github.com/astaxie/beego/config/config.go delete mode 100644 vendor/github.com/astaxie/beego/config/fake.go delete mode 100644 vendor/github.com/astaxie/beego/config/ini.go delete mode 100644 vendor/github.com/astaxie/beego/config/json.go delete mode 100644 vendor/github.com/astaxie/beego/context/acceptencoder.go delete mode 100644 vendor/github.com/astaxie/beego/context/context.go delete mode 100644 vendor/github.com/astaxie/beego/context/input.go delete mode 100644 vendor/github.com/astaxie/beego/context/output.go delete mode 100644 vendor/github.com/astaxie/beego/context/param/conv.go delete mode 100644 vendor/github.com/astaxie/beego/context/param/methodparams.go delete mode 100644 vendor/github.com/astaxie/beego/context/param/options.go delete mode 100644 vendor/github.com/astaxie/beego/context/param/parsers.go delete mode 100644 vendor/github.com/astaxie/beego/context/renderer.go delete mode 100644 vendor/github.com/astaxie/beego/context/response.go delete mode 100644 vendor/github.com/astaxie/beego/controller.go delete mode 100644 vendor/github.com/astaxie/beego/doc.go delete mode 100644 vendor/github.com/astaxie/beego/error.go delete mode 100644 vendor/github.com/astaxie/beego/filter.go delete mode 100644 vendor/github.com/astaxie/beego/flash.go delete mode 100644 vendor/github.com/astaxie/beego/fs.go delete mode 100644 vendor/github.com/astaxie/beego/go.mod delete mode 100644 vendor/github.com/astaxie/beego/go.sum delete mode 100644 vendor/github.com/astaxie/beego/grace/grace.go delete mode 100644 vendor/github.com/astaxie/beego/grace/server.go delete mode 100644 vendor/github.com/astaxie/beego/hooks.go delete mode 100644 vendor/github.com/astaxie/beego/log.go delete mode 100644 vendor/github.com/astaxie/beego/logs/README.md delete mode 100644 vendor/github.com/astaxie/beego/logs/accesslog.go delete mode 100644 vendor/github.com/astaxie/beego/logs/conn.go delete mode 100644 vendor/github.com/astaxie/beego/logs/console.go delete mode 100644 vendor/github.com/astaxie/beego/logs/file.go delete mode 100644 vendor/github.com/astaxie/beego/logs/jianliao.go delete mode 100644 vendor/github.com/astaxie/beego/logs/log.go delete mode 100644 vendor/github.com/astaxie/beego/logs/logger.go delete mode 100644 vendor/github.com/astaxie/beego/logs/multifile.go delete mode 100644 vendor/github.com/astaxie/beego/logs/slack.go delete mode 100644 vendor/github.com/astaxie/beego/logs/smtp.go delete mode 100644 vendor/github.com/astaxie/beego/mime.go delete mode 100644 vendor/github.com/astaxie/beego/namespace.go delete mode 100644 vendor/github.com/astaxie/beego/orm/README.md delete mode 100644 vendor/github.com/astaxie/beego/orm/cmd.go delete mode 100644 vendor/github.com/astaxie/beego/orm/cmd_utils.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_alias.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_mysql.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_oracle.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_postgres.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_sqlite.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_tables.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_tidb.go delete mode 100644 vendor/github.com/astaxie/beego/orm/db_utils.go delete mode 100644 vendor/github.com/astaxie/beego/orm/models.go delete mode 100644 vendor/github.com/astaxie/beego/orm/models_boot.go delete mode 100644 vendor/github.com/astaxie/beego/orm/models_fields.go delete mode 100644 vendor/github.com/astaxie/beego/orm/models_info_f.go delete mode 100644 vendor/github.com/astaxie/beego/orm/models_info_m.go delete mode 100644 vendor/github.com/astaxie/beego/orm/models_utils.go delete mode 100644 vendor/github.com/astaxie/beego/orm/orm.go delete mode 100644 vendor/github.com/astaxie/beego/orm/orm_conds.go delete mode 100644 vendor/github.com/astaxie/beego/orm/orm_log.go delete mode 100644 vendor/github.com/astaxie/beego/orm/orm_object.go delete mode 100644 vendor/github.com/astaxie/beego/orm/orm_querym2m.go delete mode 100644 vendor/github.com/astaxie/beego/orm/orm_queryset.go delete mode 100644 vendor/github.com/astaxie/beego/orm/orm_raw.go delete mode 100644 vendor/github.com/astaxie/beego/orm/qb.go delete mode 100644 vendor/github.com/astaxie/beego/orm/qb_mysql.go delete mode 100644 vendor/github.com/astaxie/beego/orm/qb_tidb.go delete mode 100644 vendor/github.com/astaxie/beego/orm/types.go delete mode 100644 vendor/github.com/astaxie/beego/orm/utils.go delete mode 100644 vendor/github.com/astaxie/beego/parser.go delete mode 100644 vendor/github.com/astaxie/beego/policy.go delete mode 100644 vendor/github.com/astaxie/beego/router.go delete mode 100644 vendor/github.com/astaxie/beego/session/README.md delete mode 100644 vendor/github.com/astaxie/beego/session/sess_cookie.go delete mode 100644 vendor/github.com/astaxie/beego/session/sess_file.go delete mode 100644 vendor/github.com/astaxie/beego/session/sess_mem.go delete mode 100644 vendor/github.com/astaxie/beego/session/sess_utils.go delete mode 100644 vendor/github.com/astaxie/beego/session/session.go delete mode 100644 vendor/github.com/astaxie/beego/staticfile.go delete mode 100644 vendor/github.com/astaxie/beego/template.go delete mode 100644 vendor/github.com/astaxie/beego/templatefunc.go delete mode 100644 vendor/github.com/astaxie/beego/toolbox/healthcheck.go delete mode 100644 vendor/github.com/astaxie/beego/toolbox/profile.go delete mode 100644 vendor/github.com/astaxie/beego/toolbox/statistics.go delete mode 100644 vendor/github.com/astaxie/beego/toolbox/task.go delete mode 100644 vendor/github.com/astaxie/beego/tree.go delete mode 100644 vendor/github.com/astaxie/beego/utils/caller.go delete mode 100644 vendor/github.com/astaxie/beego/utils/debug.go delete mode 100644 vendor/github.com/astaxie/beego/utils/file.go delete mode 100644 vendor/github.com/astaxie/beego/utils/mail.go delete mode 100644 vendor/github.com/astaxie/beego/utils/rand.go delete mode 100644 vendor/github.com/astaxie/beego/utils/safemap.go delete mode 100644 vendor/github.com/astaxie/beego/utils/slice.go delete mode 100644 vendor/github.com/astaxie/beego/utils/utils.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/LICENSE delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/auth/credentials.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/auth/signer.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/bce/builder.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/bce/client.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/bce/config.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/bce/error.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/bce/request.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/bce/response.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/bce/retry.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/http/client.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/http/constants.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/http/request.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/http/response.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/services/sms/api/model.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/services/sms/api/quota_rate.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/services/sms/api/send_sms.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/services/sms/api/signature.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/services/sms/api/template.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/services/sms/api/util.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/services/sms/client.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/util/log/logger.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/util/log/util.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/util/string.go delete mode 100644 vendor/github.com/baidubce/bce-sdk-go/util/time.go delete mode 100644 vendor/github.com/beorn7/perks/LICENSE delete mode 100644 vendor/github.com/beorn7/perks/quantile/exampledata.txt delete mode 100644 vendor/github.com/beorn7/perks/quantile/stream.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/LICENSE.txt delete mode 100644 vendor/github.com/cespare/xxhash/v2/README.md delete mode 100644 vendor/github.com/cespare/xxhash/v2/go.mod delete mode 100644 vendor/github.com/cespare/xxhash/v2/go.sum delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_amd64.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_other.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_safe.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go delete mode 100644 vendor/github.com/go-gomail/gomail/.travis.yml delete mode 100644 vendor/github.com/go-gomail/gomail/CHANGELOG.md delete mode 100644 vendor/github.com/go-gomail/gomail/CONTRIBUTING.md delete mode 100644 vendor/github.com/go-gomail/gomail/LICENSE delete mode 100644 vendor/github.com/go-gomail/gomail/README.md delete mode 100644 vendor/github.com/go-gomail/gomail/auth.go delete mode 100644 vendor/github.com/go-gomail/gomail/doc.go delete mode 100644 vendor/github.com/go-gomail/gomail/message.go delete mode 100644 vendor/github.com/go-gomail/gomail/mime.go delete mode 100644 vendor/github.com/go-gomail/gomail/mime_go14.go delete mode 100644 vendor/github.com/go-gomail/gomail/send.go delete mode 100644 vendor/github.com/go-gomail/gomail/smtp.go delete mode 100644 vendor/github.com/go-gomail/gomail/writeto.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/.gitignore delete mode 100644 vendor/github.com/go-sql-driver/mysql/AUTHORS delete mode 100644 vendor/github.com/go-sql-driver/mysql/CHANGELOG.md delete mode 100644 vendor/github.com/go-sql-driver/mysql/LICENSE delete mode 100644 vendor/github.com/go-sql-driver/mysql/README.md delete mode 100644 vendor/github.com/go-sql-driver/mysql/auth.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/buffer.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/collations.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/connection.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/const.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/driver.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/dsn.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/errors.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/fields.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/infile.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/packets.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/result.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/rows.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/statement.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/transaction.go delete mode 100644 vendor/github.com/go-sql-driver/mysql/utils.go delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/.gitignore delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/LICENSE.txt delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/README.md delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/bot.go delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/configs.go delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/go.mod delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/go.sum delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/helpers.go delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/log.go delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/params.go delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/passport.go delete mode 100644 vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/types.go delete mode 100644 vendor/github.com/golang/protobuf/AUTHORS delete mode 100644 vendor/github.com/golang/protobuf/CONTRIBUTORS delete mode 100644 vendor/github.com/golang/protobuf/LICENSE delete mode 100644 vendor/github.com/golang/protobuf/proto/buffer.go delete mode 100644 vendor/github.com/golang/protobuf/proto/defaults.go delete mode 100644 vendor/github.com/golang/protobuf/proto/deprecated.go delete mode 100644 vendor/github.com/golang/protobuf/proto/discard.go delete mode 100644 vendor/github.com/golang/protobuf/proto/extensions.go delete mode 100644 vendor/github.com/golang/protobuf/proto/properties.go delete mode 100644 vendor/github.com/golang/protobuf/proto/proto.go delete mode 100644 vendor/github.com/golang/protobuf/proto/registry.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_decode.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_encode.go delete mode 100644 vendor/github.com/golang/protobuf/proto/wire.go delete mode 100644 vendor/github.com/golang/protobuf/proto/wrappers.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any/any.pb.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/doc.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go delete mode 100644 vendor/github.com/gopherjs/gopherjs/LICENSE delete mode 100644 vendor/github.com/gopherjs/gopherjs/js/js.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/.gitignore delete mode 100644 vendor/github.com/jmespath/go-jmespath/.travis.yml delete mode 100644 vendor/github.com/jmespath/go-jmespath/LICENSE delete mode 100644 vendor/github.com/jmespath/go-jmespath/Makefile delete mode 100644 vendor/github.com/jmespath/go-jmespath/README.md delete mode 100644 vendor/github.com/jmespath/go-jmespath/api.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/astnodetype_string.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/functions.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/go.mod delete mode 100644 vendor/github.com/jmespath/go-jmespath/go.sum delete mode 100644 vendor/github.com/jmespath/go-jmespath/interpreter.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/lexer.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/parser.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/toktype_string.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/util.go delete mode 100644 vendor/github.com/josharian/intern/README.md delete mode 100644 vendor/github.com/josharian/intern/go.mod delete mode 100644 vendor/github.com/josharian/intern/intern.go delete mode 100644 vendor/github.com/josharian/intern/license.md delete mode 100644 vendor/github.com/json-iterator/go/.codecov.yml delete mode 100644 vendor/github.com/json-iterator/go/.gitignore delete mode 100644 vendor/github.com/json-iterator/go/.travis.yml delete mode 100644 vendor/github.com/json-iterator/go/Gopkg.lock delete mode 100644 vendor/github.com/json-iterator/go/Gopkg.toml delete mode 100644 vendor/github.com/json-iterator/go/LICENSE delete mode 100644 vendor/github.com/json-iterator/go/README.md delete mode 100644 vendor/github.com/json-iterator/go/adapter.go delete mode 100644 vendor/github.com/json-iterator/go/any.go delete mode 100644 vendor/github.com/json-iterator/go/any_array.go delete mode 100644 vendor/github.com/json-iterator/go/any_bool.go delete mode 100644 vendor/github.com/json-iterator/go/any_float.go delete mode 100644 vendor/github.com/json-iterator/go/any_int32.go delete mode 100644 vendor/github.com/json-iterator/go/any_int64.go delete mode 100644 vendor/github.com/json-iterator/go/any_invalid.go delete mode 100644 vendor/github.com/json-iterator/go/any_nil.go delete mode 100644 vendor/github.com/json-iterator/go/any_number.go delete mode 100644 vendor/github.com/json-iterator/go/any_object.go delete mode 100644 vendor/github.com/json-iterator/go/any_str.go delete mode 100644 vendor/github.com/json-iterator/go/any_uint32.go delete mode 100644 vendor/github.com/json-iterator/go/any_uint64.go delete mode 100644 vendor/github.com/json-iterator/go/build.sh delete mode 100644 vendor/github.com/json-iterator/go/config.go delete mode 100644 vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md delete mode 100644 vendor/github.com/json-iterator/go/go.mod delete mode 100644 vendor/github.com/json-iterator/go/go.sum delete mode 100644 vendor/github.com/json-iterator/go/iter.go delete mode 100644 vendor/github.com/json-iterator/go/iter_array.go delete mode 100644 vendor/github.com/json-iterator/go/iter_float.go delete mode 100644 vendor/github.com/json-iterator/go/iter_int.go delete mode 100644 vendor/github.com/json-iterator/go/iter_object.go delete mode 100644 vendor/github.com/json-iterator/go/iter_skip.go delete mode 100644 vendor/github.com/json-iterator/go/iter_skip_sloppy.go delete mode 100644 vendor/github.com/json-iterator/go/iter_skip_strict.go delete mode 100644 vendor/github.com/json-iterator/go/iter_str.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter.go delete mode 100644 vendor/github.com/json-iterator/go/pool.go delete mode 100644 vendor/github.com/json-iterator/go/reflect.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_array.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_dynamic.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_extension.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_json_number.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_json_raw_message.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_map.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_marshaler.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_native.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_optional.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_slice.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_struct_decoder.go delete mode 100644 vendor/github.com/json-iterator/go/reflect_struct_encoder.go delete mode 100644 vendor/github.com/json-iterator/go/stream.go delete mode 100644 vendor/github.com/json-iterator/go/stream_float.go delete mode 100644 vendor/github.com/json-iterator/go/stream_int.go delete mode 100644 vendor/github.com/json-iterator/go/stream_str.go delete mode 100644 vendor/github.com/json-iterator/go/test.sh delete mode 100644 vendor/github.com/jtolds/gls/LICENSE delete mode 100644 vendor/github.com/jtolds/gls/README.md delete mode 100644 vendor/github.com/jtolds/gls/context.go delete mode 100644 vendor/github.com/jtolds/gls/gen_sym.go delete mode 100644 vendor/github.com/jtolds/gls/gid.go delete mode 100644 vendor/github.com/jtolds/gls/id_pool.go delete mode 100644 vendor/github.com/jtolds/gls/stack_tags.go delete mode 100644 vendor/github.com/jtolds/gls/stack_tags_js.go delete mode 100644 vendor/github.com/jtolds/gls/stack_tags_main.go delete mode 100644 vendor/github.com/lib/pq/.gitignore delete mode 100644 vendor/github.com/lib/pq/LICENSE.md delete mode 100644 vendor/github.com/lib/pq/README.md delete mode 100644 vendor/github.com/lib/pq/TESTS.md delete mode 100644 vendor/github.com/lib/pq/array.go delete mode 100644 vendor/github.com/lib/pq/buf.go delete mode 100644 vendor/github.com/lib/pq/conn.go delete mode 100644 vendor/github.com/lib/pq/conn_go18.go delete mode 100644 vendor/github.com/lib/pq/connector.go delete mode 100644 vendor/github.com/lib/pq/copy.go delete mode 100644 vendor/github.com/lib/pq/doc.go delete mode 100644 vendor/github.com/lib/pq/encode.go delete mode 100644 vendor/github.com/lib/pq/error.go delete mode 100644 vendor/github.com/lib/pq/go.mod delete mode 100644 vendor/github.com/lib/pq/krb.go delete mode 100644 vendor/github.com/lib/pq/notice.go delete mode 100644 vendor/github.com/lib/pq/notify.go delete mode 100644 vendor/github.com/lib/pq/oid/doc.go delete mode 100644 vendor/github.com/lib/pq/oid/types.go delete mode 100644 vendor/github.com/lib/pq/rows.go delete mode 100644 vendor/github.com/lib/pq/scram/scram.go delete mode 100644 vendor/github.com/lib/pq/ssl.go delete mode 100644 vendor/github.com/lib/pq/ssl_permissions.go delete mode 100644 vendor/github.com/lib/pq/ssl_windows.go delete mode 100644 vendor/github.com/lib/pq/url.go delete mode 100644 vendor/github.com/lib/pq/user_posix.go delete mode 100644 vendor/github.com/lib/pq/user_windows.go delete mode 100644 vendor/github.com/lib/pq/uuid.go delete mode 100644 vendor/github.com/mailru/easyjson/.gitignore delete mode 100644 vendor/github.com/mailru/easyjson/.travis.yml delete mode 100644 vendor/github.com/mailru/easyjson/LICENSE delete mode 100644 vendor/github.com/mailru/easyjson/Makefile delete mode 100644 vendor/github.com/mailru/easyjson/README.md delete mode 100644 vendor/github.com/mailru/easyjson/buffer/pool.go delete mode 100644 vendor/github.com/mailru/easyjson/go.mod delete mode 100644 vendor/github.com/mailru/easyjson/go.sum delete mode 100644 vendor/github.com/mailru/easyjson/helpers.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/bytestostr.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/error.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/lexer.go delete mode 100644 vendor/github.com/mailru/easyjson/jwriter/writer.go delete mode 100644 vendor/github.com/mailru/easyjson/raw.go delete mode 100644 vendor/github.com/mailru/easyjson/unknown_fields.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/.gitignore delete mode 100644 vendor/github.com/mattn/go-sqlite3/.travis.yml delete mode 100644 vendor/github.com/mattn/go-sqlite3/LICENSE delete mode 100644 vendor/github.com/mattn/go-sqlite3/README.md delete mode 100644 vendor/github.com/mattn/go-sqlite3/backup.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/callback.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/convert.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/doc.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/error.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_context.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_func_crypt.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_go18.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_libsqlite3.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension_omit.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_allow_uri_authority.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_app_armor.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_foreign_keys.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_fts5.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_icu.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_introspect.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_json1.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_omit.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_secure_delete.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_secure_delete_fast.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_stat4.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.c delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth_omit.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vacuum_full.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vacuum_incr.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_other.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_solaris.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_type.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_usleep_windows.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3_windows.go delete mode 100644 vendor/github.com/mattn/go-sqlite3/sqlite3ext.h delete mode 100644 vendor/github.com/mattn/go-sqlite3/static_mock.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/.gitignore delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go delete mode 100644 vendor/github.com/modern-go/concurrent/.gitignore delete mode 100644 vendor/github.com/modern-go/concurrent/.travis.yml delete mode 100644 vendor/github.com/modern-go/concurrent/LICENSE delete mode 100644 vendor/github.com/modern-go/concurrent/README.md delete mode 100644 vendor/github.com/modern-go/concurrent/executor.go delete mode 100644 vendor/github.com/modern-go/concurrent/go_above_19.go delete mode 100644 vendor/github.com/modern-go/concurrent/go_below_19.go delete mode 100644 vendor/github.com/modern-go/concurrent/log.go delete mode 100644 vendor/github.com/modern-go/concurrent/test.sh delete mode 100644 vendor/github.com/modern-go/concurrent/unbounded_executor.go delete mode 100644 vendor/github.com/modern-go/reflect2/.gitignore delete mode 100644 vendor/github.com/modern-go/reflect2/.travis.yml delete mode 100644 vendor/github.com/modern-go/reflect2/Gopkg.lock delete mode 100644 vendor/github.com/modern-go/reflect2/Gopkg.toml delete mode 100644 vendor/github.com/modern-go/reflect2/LICENSE delete mode 100644 vendor/github.com/modern-go/reflect2/README.md delete mode 100644 vendor/github.com/modern-go/reflect2/go_above_19.go delete mode 100644 vendor/github.com/modern-go/reflect2/reflect2.go delete mode 100644 vendor/github.com/modern-go/reflect2/reflect2_amd64.s delete mode 100644 vendor/github.com/modern-go/reflect2/reflect2_kind.go delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_386.s delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_amd64p32.s delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_arm.s delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_arm64.s delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_mips64x.s delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_mipsx.s delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_ppc64x.s delete mode 100644 vendor/github.com/modern-go/reflect2/relfect2_s390x.s delete mode 100644 vendor/github.com/modern-go/reflect2/safe_field.go delete mode 100644 vendor/github.com/modern-go/reflect2/safe_map.go delete mode 100644 vendor/github.com/modern-go/reflect2/safe_slice.go delete mode 100644 vendor/github.com/modern-go/reflect2/safe_struct.go delete mode 100644 vendor/github.com/modern-go/reflect2/safe_type.go delete mode 100644 vendor/github.com/modern-go/reflect2/type_map.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_array.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_eface.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_field.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_iface.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_link.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_map.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_ptr.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_slice.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_struct.go delete mode 100644 vendor/github.com/modern-go/reflect2/unsafe_type.go delete mode 100644 vendor/github.com/olivere/elastic/v7/.gitignore delete mode 100644 vendor/github.com/olivere/elastic/v7/CHANGELOG-3.0.md delete mode 100644 vendor/github.com/olivere/elastic/v7/CHANGELOG-5.0.md delete mode 100644 vendor/github.com/olivere/elastic/v7/CHANGELOG-6.0.md delete mode 100644 vendor/github.com/olivere/elastic/v7/CHANGELOG-7.0.md delete mode 100644 vendor/github.com/olivere/elastic/v7/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/olivere/elastic/v7/CONTRIBUTING.md delete mode 100644 vendor/github.com/olivere/elastic/v7/CONTRIBUTORS delete mode 100644 vendor/github.com/olivere/elastic/v7/ISSUE_TEMPLATE.md delete mode 100644 vendor/github.com/olivere/elastic/v7/LICENSE delete mode 100644 vendor/github.com/olivere/elastic/v7/Makefile delete mode 100644 vendor/github.com/olivere/elastic/v7/README.md delete mode 100644 vendor/github.com/olivere/elastic/v7/acknowledged_response.go delete mode 100644 vendor/github.com/olivere/elastic/v7/backoff.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_create_request.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_create_request_easyjson.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_delete_request.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_delete_request_easyjson.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_index_request.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_index_request_easyjson.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_processor.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_request.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_update_request.go delete mode 100644 vendor/github.com/olivere/elastic/v7/bulk_update_request_easyjson.go delete mode 100644 vendor/github.com/olivere/elastic/v7/canonicalize.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_aliases.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_allocation.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_count.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_fielddata.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_health.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_indices.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_master.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_shards.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cat_snapshots.go delete mode 100644 vendor/github.com/olivere/elastic/v7/clear_scroll.go delete mode 100644 vendor/github.com/olivere/elastic/v7/client.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cluster_health.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cluster_reroute.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cluster_state.go delete mode 100644 vendor/github.com/olivere/elastic/v7/cluster_stats.go delete mode 100644 vendor/github.com/olivere/elastic/v7/config/config.go delete mode 100644 vendor/github.com/olivere/elastic/v7/config/doc.go delete mode 100644 vendor/github.com/olivere/elastic/v7/connection.go delete mode 100644 vendor/github.com/olivere/elastic/v7/count.go delete mode 100644 vendor/github.com/olivere/elastic/v7/decoder.go delete mode 100644 vendor/github.com/olivere/elastic/v7/delete.go delete mode 100644 vendor/github.com/olivere/elastic/v7/delete_by_query.go delete mode 100644 vendor/github.com/olivere/elastic/v7/doc.go delete mode 100644 vendor/github.com/olivere/elastic/v7/docker-compose.cluster.yml delete mode 100644 vendor/github.com/olivere/elastic/v7/docker-compose.yml delete mode 100644 vendor/github.com/olivere/elastic/v7/docvalue_field.go delete mode 100644 vendor/github.com/olivere/elastic/v7/errors.go delete mode 100644 vendor/github.com/olivere/elastic/v7/exists.go delete mode 100644 vendor/github.com/olivere/elastic/v7/explain.go delete mode 100644 vendor/github.com/olivere/elastic/v7/fetch_source_context.go delete mode 100644 vendor/github.com/olivere/elastic/v7/field_caps.go delete mode 100644 vendor/github.com/olivere/elastic/v7/geo_point.go delete mode 100644 vendor/github.com/olivere/elastic/v7/get.go delete mode 100644 vendor/github.com/olivere/elastic/v7/go.mod delete mode 100644 vendor/github.com/olivere/elastic/v7/highlight.go delete mode 100644 vendor/github.com/olivere/elastic/v7/index.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_analyze.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_clear_cache.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_close.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_create.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_delete.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_delete_component_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_delete_index_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_delete_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_exists.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_exists_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_flush.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_flush_synced.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_forcemerge.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_freeze.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get_aliases.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get_component_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get_field_mapping.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get_index_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get_mapping.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get_settings.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_get_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_open.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_put_alias.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_put_component_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_put_index_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_put_mapping.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_put_settings.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_put_template.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_refresh.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_rollover.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_segments.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_shrink.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_stats.go delete mode 100644 vendor/github.com/olivere/elastic/v7/indices_unfreeze.go delete mode 100644 vendor/github.com/olivere/elastic/v7/ingest_delete_pipeline.go delete mode 100644 vendor/github.com/olivere/elastic/v7/ingest_get_pipeline.go delete mode 100644 vendor/github.com/olivere/elastic/v7/ingest_put_pipeline.go delete mode 100644 vendor/github.com/olivere/elastic/v7/ingest_simulate_pipeline.go delete mode 100644 vendor/github.com/olivere/elastic/v7/inner_hit.go delete mode 100644 vendor/github.com/olivere/elastic/v7/logger.go delete mode 100644 vendor/github.com/olivere/elastic/v7/mget.go delete mode 100644 vendor/github.com/olivere/elastic/v7/msearch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/mtermvectors.go delete mode 100644 vendor/github.com/olivere/elastic/v7/nodes_info.go delete mode 100644 vendor/github.com/olivere/elastic/v7/nodes_stats.go delete mode 100644 vendor/github.com/olivere/elastic/v7/ping.go delete mode 100644 vendor/github.com/olivere/elastic/v7/pit.go delete mode 100644 vendor/github.com/olivere/elastic/v7/pit_close.go delete mode 100644 vendor/github.com/olivere/elastic/v7/pit_open.go delete mode 100644 vendor/github.com/olivere/elastic/v7/plugins.go delete mode 100644 vendor/github.com/olivere/elastic/v7/query.go delete mode 100644 vendor/github.com/olivere/elastic/v7/reindex.go delete mode 100644 vendor/github.com/olivere/elastic/v7/request.go delete mode 100644 vendor/github.com/olivere/elastic/v7/rescore.go delete mode 100644 vendor/github.com/olivere/elastic/v7/rescorer.go delete mode 100644 vendor/github.com/olivere/elastic/v7/response.go delete mode 100644 vendor/github.com/olivere/elastic/v7/retrier.go delete mode 100644 vendor/github.com/olivere/elastic/v7/retry.go delete mode 100644 vendor/github.com/olivere/elastic/v7/runtime_mappings.go delete mode 100644 vendor/github.com/olivere/elastic/v7/script.go delete mode 100644 vendor/github.com/olivere/elastic/v7/script_delete.go delete mode 100644 vendor/github.com/olivere/elastic/v7/script_get.go delete mode 100644 vendor/github.com/olivere/elastic/v7/script_put.go delete mode 100644 vendor/github.com/olivere/elastic/v7/scroll.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_adjacency_matrix.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_auto_date_histogram.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_children.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_composite.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_count_thresholds.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_date_histogram.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_date_range.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_diversified_sampler.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_filter.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_filters.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geo_distance.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geohash_grid.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_geotile_grid.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_global.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_histogram.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_ip_range.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_missing.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_multi_terms.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_nested.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_range.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_rare_terms.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_reverse_nested.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_sampler.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_terms.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_significant_text.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_bucket_terms.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_matrix_stats.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_avg.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_cardinality.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_extended_stats.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_geo_bounds.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_geo_centroid.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_max.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_median_absolute_deviation.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_min.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentile_ranks.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_percentiles.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_scripted_metric.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_stats.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_sum.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_top_hits.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_top_metrics.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_value_count.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_metrics_weighted_avg.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_avg_bucket.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_script.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_selector.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_bucket_sort.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_cumulative_sum.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_derivative.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_extended_stats_bucket.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_max_bucket.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_min_bucket.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_avg.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_mov_fn.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_percentiles_bucket.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_serial_diff.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_stats_bucket.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_aggs_pipeline_sum_bucket.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_collapse_builder.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_bool.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_boosting.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_combined_fields.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_common_terms.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_constant_score.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_dis_max.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_distance_feature_query.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_exists.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_fsq.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_fsq_score_funcs.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_fuzzy.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_geo_bounding_box.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_geo_distance.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_geo_polygon.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_has_child.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_has_parent.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_ids.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_filter.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_all_of.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_any_of.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_match.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_prefix.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_interval_rules_wildcard.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_match.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_match_all.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_match_bool_prefix.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_match_none.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_match_phrase.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_match_phrase_prefix.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_more_like_this.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_multi_match.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_nested.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_parent_id.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_percolator.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_pinned.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_prefix.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_query_string.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_range.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_raw_string.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_regexp.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_script.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_script_score.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_simple_query_string.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_slice.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_span_first.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_span_near.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_span_term.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_term.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_terms.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_terms_set.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_type.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_wildcard.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_queries_wrapper.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_request.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_shards.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_source.go delete mode 100644 vendor/github.com/olivere/elastic/v7/search_terms_lookup.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_create.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_create_repository.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_delete.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_delete_repository.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_get.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_get_repository.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_restore.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_status.go delete mode 100644 vendor/github.com/olivere/elastic/v7/snapshot_verify_repository.go delete mode 100644 vendor/github.com/olivere/elastic/v7/sort.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggest_field.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggester.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggester_completion.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggester_context.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggester_context_category.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggester_context_geo.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggester_phrase.go delete mode 100644 vendor/github.com/olivere/elastic/v7/suggester_term.go delete mode 100644 vendor/github.com/olivere/elastic/v7/tasks_cancel.go delete mode 100644 vendor/github.com/olivere/elastic/v7/tasks_get_task.go delete mode 100644 vendor/github.com/olivere/elastic/v7/tasks_list.go delete mode 100644 vendor/github.com/olivere/elastic/v7/termvectors.go delete mode 100644 vendor/github.com/olivere/elastic/v7/update.go delete mode 100644 vendor/github.com/olivere/elastic/v7/update_by_query.go delete mode 100644 vendor/github.com/olivere/elastic/v7/uritemplates/LICENSE delete mode 100644 vendor/github.com/olivere/elastic/v7/uritemplates/uritemplates.go delete mode 100644 vendor/github.com/olivere/elastic/v7/uritemplates/utils.go delete mode 100644 vendor/github.com/olivere/elastic/v7/validate.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_async_search_delete.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_async_search_get.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_async_search_submit.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_ilm_delete_lifecycle.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_ilm_get_lifecycle.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_ilm_put_lifecycle.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_info.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_rollup_delete.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_rollup_get.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_rollup_put.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_rollup_start.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_rollup_stop.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_change_password.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_delete_role.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_delete_role_mapping.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_delete_user.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_disable_user.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_enable_user.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_get_role.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_get_role_mapping.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_get_user.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_put_role.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_put_role_mapping.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_security_put_user.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_ack_watch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_activate_watch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_deactivate_watch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_delete_watch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_execute_watch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_get_watch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_put_watch.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_start.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_stats.go delete mode 100644 vendor/github.com/olivere/elastic/v7/xpack_watcher_stop.go delete mode 100644 vendor/github.com/pkg/errors/.gitignore delete mode 100644 vendor/github.com/pkg/errors/.travis.yml delete mode 100644 vendor/github.com/pkg/errors/LICENSE delete mode 100644 vendor/github.com/pkg/errors/Makefile delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/errors.go delete mode 100644 vendor/github.com/pkg/errors/go113.go delete mode 100644 vendor/github.com/pkg/errors/stack.go delete mode 100644 vendor/github.com/prometheus/client_golang/LICENSE delete mode 100644 vendor/github.com/prometheus/client_golang/NOTICE delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/.gitignore delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/README.md delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/counter.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/desc.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/doc.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/fnv.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/gauge.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/histogram.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/metric.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/labels.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/metric.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/observer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/registry.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/summary.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/timer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/untyped.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/value.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vec.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/wrap.go delete mode 100644 vendor/github.com/prometheus/client_model/LICENSE delete mode 100644 vendor/github.com/prometheus/client_model/NOTICE delete mode 100644 vendor/github.com/prometheus/client_model/go/metrics.pb.go delete mode 100644 vendor/github.com/prometheus/common/LICENSE delete mode 100644 vendor/github.com/prometheus/common/NOTICE delete mode 100644 vendor/github.com/prometheus/common/expfmt/decode.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/encode.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/expfmt.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/openmetrics_create.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_create.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_parse.go delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go delete mode 100644 vendor/github.com/prometheus/common/model/alert.go delete mode 100644 vendor/github.com/prometheus/common/model/fingerprinting.go delete mode 100644 vendor/github.com/prometheus/common/model/fnv.go delete mode 100644 vendor/github.com/prometheus/common/model/labels.go delete mode 100644 vendor/github.com/prometheus/common/model/labelset.go delete mode 100644 vendor/github.com/prometheus/common/model/metric.go delete mode 100644 vendor/github.com/prometheus/common/model/model.go delete mode 100644 vendor/github.com/prometheus/common/model/signature.go delete mode 100644 vendor/github.com/prometheus/common/model/silence.go delete mode 100644 vendor/github.com/prometheus/common/model/time.go delete mode 100644 vendor/github.com/prometheus/common/model/value.go delete mode 100644 vendor/github.com/prometheus/procfs/.gitignore delete mode 100644 vendor/github.com/prometheus/procfs/.golangci.yml delete mode 100644 vendor/github.com/prometheus/procfs/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/prometheus/procfs/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/procfs/LICENSE delete mode 100644 vendor/github.com/prometheus/procfs/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/procfs/Makefile delete mode 100644 vendor/github.com/prometheus/procfs/Makefile.common delete mode 100644 vendor/github.com/prometheus/procfs/NOTICE delete mode 100644 vendor/github.com/prometheus/procfs/README.md delete mode 100644 vendor/github.com/prometheus/procfs/arp.go delete mode 100644 vendor/github.com/prometheus/procfs/buddyinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_armx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_others.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_s390x.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_x86.go delete mode 100644 vendor/github.com/prometheus/procfs/crypto.go delete mode 100644 vendor/github.com/prometheus/procfs/doc.go delete mode 100644 vendor/github.com/prometheus/procfs/fixtures.ttar delete mode 100644 vendor/github.com/prometheus/procfs/fs.go delete mode 100644 vendor/github.com/prometheus/procfs/fscache.go delete mode 100644 vendor/github.com/prometheus/procfs/go.mod delete mode 100644 vendor/github.com/prometheus/procfs/go.sum delete mode 100644 vendor/github.com/prometheus/procfs/internal/fs/fs.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/parse.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/readfile.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/valueparser.go delete mode 100644 vendor/github.com/prometheus/procfs/ipvs.go delete mode 100644 vendor/github.com/prometheus/procfs/kernel_random.go delete mode 100644 vendor/github.com/prometheus/procfs/loadavg.go delete mode 100644 vendor/github.com/prometheus/procfs/mdstat.go delete mode 100644 vendor/github.com/prometheus/procfs/meminfo.go delete mode 100644 vendor/github.com/prometheus/procfs/mountinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/mountstats.go delete mode 100644 vendor/github.com/prometheus/procfs/net_conntrackstat.go delete mode 100644 vendor/github.com/prometheus/procfs/net_dev.go delete mode 100644 vendor/github.com/prometheus/procfs/net_sockstat.go delete mode 100644 vendor/github.com/prometheus/procfs/net_softnet.go delete mode 100644 vendor/github.com/prometheus/procfs/net_udp.go delete mode 100644 vendor/github.com/prometheus/procfs/net_unix.go delete mode 100644 vendor/github.com/prometheus/procfs/proc.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_cgroup.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_environ.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_fdinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_io.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_limits.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_maps.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_ns.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_psi.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_smaps.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_stat.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_status.go delete mode 100644 vendor/github.com/prometheus/procfs/schedstat.go delete mode 100644 vendor/github.com/prometheus/procfs/stat.go delete mode 100644 vendor/github.com/prometheus/procfs/swaps.go delete mode 100644 vendor/github.com/prometheus/procfs/ttar delete mode 100644 vendor/github.com/prometheus/procfs/vm.go delete mode 100644 vendor/github.com/prometheus/procfs/xfrm.go delete mode 100644 vendor/github.com/prometheus/procfs/zoneinfo.go delete mode 100644 vendor/github.com/shiena/ansicolor/.gitignore delete mode 100644 vendor/github.com/shiena/ansicolor/LICENSE delete mode 100644 vendor/github.com/shiena/ansicolor/README.md delete mode 100644 vendor/github.com/shiena/ansicolor/ansicolor.go delete mode 100644 vendor/github.com/shiena/ansicolor/ansicolor_ansi.go delete mode 100644 vendor/github.com/shiena/ansicolor/ansicolor_windows.go delete mode 100644 vendor/github.com/smartystreets/assertions/.gitignore delete mode 100644 vendor/github.com/smartystreets/assertions/.travis.yml delete mode 100644 vendor/github.com/smartystreets/assertions/CONTRIBUTING.md delete mode 100644 vendor/github.com/smartystreets/assertions/LICENSE.md delete mode 100644 vendor/github.com/smartystreets/assertions/Makefile delete mode 100644 vendor/github.com/smartystreets/assertions/README.md delete mode 100644 vendor/github.com/smartystreets/assertions/collections.go delete mode 100644 vendor/github.com/smartystreets/assertions/doc.go delete mode 100644 vendor/github.com/smartystreets/assertions/equal_method.go delete mode 100644 vendor/github.com/smartystreets/assertions/equality.go delete mode 100644 vendor/github.com/smartystreets/assertions/equality_diff.go delete mode 100644 vendor/github.com/smartystreets/assertions/filter.go delete mode 100644 vendor/github.com/smartystreets/assertions/go.mod delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/mathutil.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go delete mode 100644 vendor/github.com/smartystreets/assertions/messages.go delete mode 100644 vendor/github.com/smartystreets/assertions/panic.go delete mode 100644 vendor/github.com/smartystreets/assertions/quantity.go delete mode 100644 vendor/github.com/smartystreets/assertions/serializer.go delete mode 100644 vendor/github.com/smartystreets/assertions/strings.go delete mode 100644 vendor/github.com/smartystreets/assertions/time.go delete mode 100644 vendor/github.com/smartystreets/assertions/type.go delete mode 100644 vendor/github.com/smartystreets/goconvey/LICENSE.md delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/assertions.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/context.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/convey.goconvey delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/discovery.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/doc.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/init.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/nilReporter.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/console.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/init.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/json.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/story.go delete mode 100644 vendor/github.com/ysicing/workwxbot/.gitignore delete mode 100644 vendor/github.com/ysicing/workwxbot/Makefile delete mode 100644 vendor/github.com/ysicing/workwxbot/README.md delete mode 100644 vendor/github.com/ysicing/workwxbot/go.mod delete mode 100644 vendor/github.com/ysicing/workwxbot/message.go delete mode 100644 vendor/github.com/ysicing/workwxbot/workwechat.go delete mode 100644 vendor/github.com/ysicing/workwxbot/workwxbot.go delete mode 100644 vendor/golang.org/x/crypto/AUTHORS delete mode 100644 vendor/golang.org/x/crypto/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/crypto/LICENSE delete mode 100644 vendor/golang.org/x/crypto/PATENTS delete mode 100644 vendor/golang.org/x/crypto/acme/acme.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/autocert.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/cache.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/listener.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/renewal.go delete mode 100644 vendor/golang.org/x/crypto/acme/http.go delete mode 100644 vendor/golang.org/x/crypto/acme/jws.go delete mode 100644 vendor/golang.org/x/crypto/acme/rfc8555.go delete mode 100644 vendor/golang.org/x/crypto/acme/types.go delete mode 100644 vendor/golang.org/x/crypto/acme/version_go112.go delete mode 100644 vendor/golang.org/x/net/AUTHORS delete mode 100644 vendor/golang.org/x/net/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/net/LICENSE delete mode 100644 vendor/golang.org/x/net/PATENTS delete mode 100644 vendor/golang.org/x/net/idna/idna10.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/idna9.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/punycode.go delete mode 100644 vendor/golang.org/x/net/idna/tables10.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables11.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables12.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables13.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables9.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/trie.go delete mode 100644 vendor/golang.org/x/net/idna/trieval.go delete mode 100644 vendor/golang.org/x/sys/AUTHORS delete mode 100644 vendor/golang.org/x/sys/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/sys/LICENSE delete mode 100644 vendor/golang.org/x/sys/PATENTS delete mode 100644 vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go delete mode 100644 vendor/golang.org/x/sys/unix/.gitignore delete mode 100644 vendor/golang.org/x/sys/unix/README.md delete mode 100644 vendor/golang.org/x/sys/unix/affinity_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/aliases.go delete mode 100644 vendor/golang.org/x/sys/unix/asm_aix_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mips64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mipsx.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_riscv64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_solaris_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_zos_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/bluetooth_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/cap_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/constants.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/dirent.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_big.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_little.go delete mode 100644 vendor/golang.org/x/sys/unix/env_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/epoll_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go delete mode 100644 vendor/golang.org/x/sys/unix/fdset.go delete mode 100644 vendor/golang.org/x/sys/unix/fstatfs_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_c.c delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/mkall.sh delete mode 100644 vendor/golang.org/x/sys/unix/mkerrors.sh delete mode 100644 vendor/golang.org/x/sys/unix/pagesize_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/pledge_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/ptrace_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/ptrace_ios.go delete mode 100644 vendor/golang.org/x/sys/unix/race.go delete mode 100644 vendor/golang.org/x/sys/unix/race0.go delete mode 100644 vendor/golang.org/x/sys/unix/readdirent_getdents.go delete mode 100644 vendor/golang.org/x/sys/unix/readdirent_getdirentries.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go delete mode 100644 vendor/golang.org/x/sys/unix/str.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_illumos.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/timestruct.go delete mode 100644 vendor/golang.org/x/sys/unix/unveil_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/xattr_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_x86_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_illumos_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/windows/aliases.go delete mode 100644 vendor/golang.org/x/sys/windows/dll_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/empty.s delete mode 100644 vendor/golang.org/x/sys/windows/env_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/eventlog.go delete mode 100644 vendor/golang.org/x/sys/windows/exec_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/memory_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/mkerrors.bash delete mode 100644 vendor/golang.org/x/sys/windows/mkknownfolderids.bash delete mode 100644 vendor/golang.org/x/sys/windows/mksyscall.go delete mode 100644 vendor/golang.org/x/sys/windows/race.go delete mode 100644 vendor/golang.org/x/sys/windows/race0.go delete mode 100644 vendor/golang.org/x/sys/windows/security_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/service.go delete mode 100644 vendor/golang.org/x/sys/windows/str.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_386.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_amd64.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_arm.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_arm64.go delete mode 100644 vendor/golang.org/x/sys/windows/zerrors_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/zknownfolderids_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/zsyscall_windows.go delete mode 100644 vendor/golang.org/x/text/AUTHORS delete mode 100644 vendor/golang.org/x/text/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/text/LICENSE delete mode 100644 vendor/golang.org/x/text/PATENTS delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go delete mode 100644 vendor/golang.org/x/text/transform/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bidi.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bracket.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/core.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/prop.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/composition.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/input.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/iter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/normalize.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/trie.go delete mode 100644 vendor/google.golang.org/protobuf/AUTHORS delete mode 100644 vendor/google.golang.org/protobuf/CONTRIBUTORS delete mode 100644 vendor/google.golang.org/protobuf/LICENSE delete mode 100644 vendor/google.golang.org/protobuf/PATENTS delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/decode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/doc.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/encode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/protowire/wire.go delete mode 100644 vendor/google.golang.org/protobuf/internal/descfmt/stringer.go delete mode 100644 vendor/google.golang.org/protobuf/internal/descopts/options.go delete mode 100644 vendor/google.golang.org/protobuf/internal/detrand/rand.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/defval/default.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/messageset/messageset.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_number.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_string.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_token.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/doc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/encode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/errors.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/is_go112.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/is_go113.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/build.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_list.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/placeholder.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filetype/build.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/flags.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/any_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/api_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/doc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/duration_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/empty_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/goname.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/map_entry.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/struct_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/type_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/wrappers.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/api_export.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/checkinit.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_field.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_tables.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert_list.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert_map.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/decode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/encode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/enum.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_export.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_file.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/merge.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/merge_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/validate.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/weak.go delete mode 100644 vendor/google.golang.org/protobuf/internal/pragma/pragma.go delete mode 100644 vendor/google.golang.org/protobuf/internal/set/ints.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings_pure.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/version/version.go delete mode 100644 vendor/google.golang.org/protobuf/proto/checkinit.go delete mode 100644 vendor/google.golang.org/protobuf/proto/decode.go delete mode 100644 vendor/google.golang.org/protobuf/proto/decode_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/doc.go delete mode 100644 vendor/google.golang.org/protobuf/proto/encode.go delete mode 100644 vendor/google.golang.org/protobuf/proto/encode_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/equal.go delete mode 100644 vendor/google.golang.org/protobuf/proto/extension.go delete mode 100644 vendor/google.golang.org/protobuf/proto/merge.go delete mode 100644 vendor/google.golang.org/protobuf/proto/messageset.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto_methods.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/proto/reset.go delete mode 100644 vendor/google.golang.org/protobuf/proto/size.go delete mode 100644 vendor/google.golang.org/protobuf/proto/size_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/wrappers.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/proto.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/source.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/type.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoregistry/registry.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoiface/methods.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoimpl/version.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go delete mode 100644 vendor/gopkg.in/alexcesaro/quotedprintable.v3/LICENSE delete mode 100644 vendor/gopkg.in/alexcesaro/quotedprintable.v3/README.md delete mode 100644 vendor/gopkg.in/alexcesaro/quotedprintable.v3/encodedword.go delete mode 100644 vendor/gopkg.in/alexcesaro/quotedprintable.v3/pool.go delete mode 100644 vendor/gopkg.in/alexcesaro/quotedprintable.v3/pool_go12.go delete mode 100644 vendor/gopkg.in/alexcesaro/quotedprintable.v3/reader.go delete mode 100644 vendor/gopkg.in/alexcesaro/quotedprintable.v3/writer.go delete mode 100644 vendor/gopkg.in/ini.v1/.gitignore delete mode 100644 vendor/gopkg.in/ini.v1/LICENSE delete mode 100644 vendor/gopkg.in/ini.v1/Makefile delete mode 100644 vendor/gopkg.in/ini.v1/README.md delete mode 100644 vendor/gopkg.in/ini.v1/error.go delete mode 100644 vendor/gopkg.in/ini.v1/file.go delete mode 100644 vendor/gopkg.in/ini.v1/ini.go delete mode 100644 vendor/gopkg.in/ini.v1/key.go delete mode 100644 vendor/gopkg.in/ini.v1/parser.go delete mode 100644 vendor/gopkg.in/ini.v1/section.go delete mode 100644 vendor/gopkg.in/ini.v1/struct.go delete mode 100644 vendor/gopkg.in/yaml.v2/.travis.yml delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE.libyaml delete mode 100644 vendor/gopkg.in/yaml.v2/NOTICE delete mode 100644 vendor/gopkg.in/yaml.v2/README.md delete mode 100644 vendor/gopkg.in/yaml.v2/apic.go delete mode 100644 vendor/gopkg.in/yaml.v2/decode.go delete mode 100644 vendor/gopkg.in/yaml.v2/emitterc.go delete mode 100644 vendor/gopkg.in/yaml.v2/encode.go delete mode 100644 vendor/gopkg.in/yaml.v2/go.mod delete mode 100644 vendor/gopkg.in/yaml.v2/parserc.go delete mode 100644 vendor/gopkg.in/yaml.v2/readerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/resolve.go delete mode 100644 vendor/gopkg.in/yaml.v2/scannerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/sorter.go delete mode 100644 vendor/gopkg.in/yaml.v2/writerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/yaml.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlh.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlprivateh.go delete mode 100644 vendor/modules.txt diff --git a/.gitignore b/.gitignore index 4edf42c4..f4e7f2f3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,13 @@ conf/app.conf +conf/alertgroup.conf PrometheusAlert PrometheusAlert.exe logo .idea -logs/ +logs/*.log example/linux example/windows -vendor -old_delete/ \ No newline at end of file +vendor/ +old_delete/ +build/* +.vscode/ diff --git a/Makefile b/Makefile index 4b8ae451..e1e95742 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,14 @@ +SHELL:=/bin/sh +.PHONY: all vet test build clean docker docker-push docker-test + +export GO111MODULE=on +export GOPROXY=https://goproxy.io + +# path related +MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) +MKFILE_DIR := $(dir $(MKFILE_PATH)) +RELEASE_DIR := ${MKFILE_DIR}/build/bin + pkgs = $(shell go list ./... | grep -v vendor/) DOCKER_IMAGE_NAME ?= feiyu563/prometheus-alert @@ -14,44 +25,47 @@ VERSION_LDFLAGS := \ -X main.BuildUser=$(BUILDUSER) \ -X main.BuildDate=$(BUILDDATE) -all: format vet test build +# go source files, ignore vendor directory +SOURCE = $(shell find ${MKFILE_DIR} -type f -name "*.go") +TARGET = ${RELEASE_DIR}/PrometheusAlert + +all: ${TARGET} + +${TARGET}: ${SOURCE} + @echo ">> building code" + go mod tidy + go mod vendor + mkdir -p ${RELEASE_DIR} + go build -ldflags "$(VERSION_LDFLAGS)" -o ${TARGET} -.PHONY: format format: @echo ">> formatting code" go fmt $(pkgs) -.PHONY: vet vet: @echo ">> vetting code" go vet $(pkgs) -.PHONY: test test: @echo ">> running short tests" go test -short $(pkgs) -.PHONY: build -build: - @echo ">> building code" - go mod tidy - go mod vendor - GO11MODULE=on GO111MODULE=on GOPROXY=https://goproxy.io \ - go build -ldflags "$(VERSION_LDFLAGS)" -o PrometheusAlert +build: all + +clean: + @echo ">> cleaning build" + rm -rf ${MKFILE_DIR}build -.PHONY: docker docker: @echo ">> building docker image" docker build -t "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)" . docker tag "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)" "$(DOCKER_IMAGE_NAME):latest" -.PHONY: docker-push docker-push: @echo ">> pushing docker image" docker push "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)" docker push "$(DOCKER_IMAGE_NAME):latest" -.PHONY: docker-test docker-test: @echo ">> testing docker image and PrometheusAlert's health" cmd/test_image.sh "$(DOCKER_IMAGE_NAME):$(TAG_VERSION)" 8080 diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE deleted file mode 100644 index 0c44dcef..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright (c) 2009-present, Alibaba Cloud All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/api_timeout.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/api_timeout.go deleted file mode 100644 index d7968dab..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/api_timeout.go +++ /dev/null @@ -1,249 +0,0 @@ -package sdk - -import ( - "encoding/json" - "strings" - "time" -) - -var apiTimeouts = `{ - "ecs": { - "ActivateRouterInterface": 10, - "AddTags": 61, - "AllocateDedicatedHosts": 10, - "AllocateEipAddress": 17, - "AllocatePublicIpAddress": 36, - "ApplyAutoSnapshotPolicy": 10, - "AssignIpv6Addresses": 10, - "AssignPrivateIpAddresses": 10, - "AssociateEipAddress": 17, - "AttachClassicLinkVpc": 14, - "AttachDisk": 36, - "AttachInstanceRamRole": 11, - "AttachKeyPair": 16, - "AttachNetworkInterface": 16, - "AuthorizeSecurityGroupEgress": 16, - "AuthorizeSecurityGroup": 16, - "CancelAutoSnapshotPolicy": 10, - "CancelCopyImage": 10, - "CancelPhysicalConnection": 10, - "CancelSimulatedSystemEvents": 10, - "CancelTask": 10, - "ConnectRouterInterface": 10, - "ConvertNatPublicIpToEip": 12, - "CopyImage": 10, - "CreateAutoSnapshotPolicy": 10, - "CreateCommand": 16, - "CreateDeploymentSet": 16, - "CreateDisk": 36, - "CreateHpcCluster": 10, - "CreateImage": 36, - "CreateInstance": 86, - "CreateKeyPair": 10, - "CreateLaunchTemplate": 10, - "CreateLaunchTemplateVersion": 10, - "CreateNatGateway": 36, - "CreateNetworkInterfacePermission": 13, - "CreateNetworkInterface": 16, - "CreatePhysicalConnection": 10, - "CreateRouteEntry": 17, - "CreateRouterInterface": 10, - "CreateSecurityGroup": 86, - "CreateSimulatedSystemEvents": 10, - "CreateSnapshot": 86, - "CreateVirtualBorderRouter": 10, - "CreateVpc": 16, - "CreateVSwitch": 17, - "DeactivateRouterInterface": 10, - "DeleteAutoSnapshotPolicy": 10, - "DeleteBandwidthPackage": 10, - "DeleteCommand": 16, - "DeleteDeploymentSet": 12, - "DeleteDisk": 16, - "DeleteHpcCluster": 10, - "DeleteImage": 36, - "DeleteInstance": 66, - "DeleteKeyPairs": 10, - "DeleteLaunchTemplate": 10, - "DeleteLaunchTemplateVersion": 10, - "DeleteNatGateway": 10, - "DeleteNetworkInterfacePermission": 10, - "DeleteNetworkInterface": 16, - "DeletePhysicalConnection": 10, - "DeleteRouteEntry": 16, - "DeleteRouterInterface": 10, - "DeleteSecurityGroup": 87, - "DeleteSnapshot": 17, - "DeleteVirtualBorderRouter": 10, - "DeleteVpc": 17, - "DeleteVSwitch": 17, - "DescribeAccessPoints": 10, - "DescribeAccountAttributes": 10, - "DescribeAutoSnapshotPolicyEx": 16, - "DescribeAvailableResource": 10, - "DescribeBandwidthLimitation": 16, - "DescribeBandwidthPackages": 10, - "DescribeClassicLinkInstances": 15, - "DescribeCloudAssistantStatus": 16, - "DescribeClusters": 10, - "DescribeCommands": 16, - "DescribeDedicatedHosts": 10, - "DescribeDedicatedHostTypes": 10, - "DescribeDeploymentSets": 26, - "DescribeDiskMonitorData": 16, - "DescribeDisksFullStatus": 14, - "DescribeDisks": 19, - "DescribeEipAddresses": 16, - "DescribeEipMonitorData": 16, - "DescribeEniMonitorData": 10, - "DescribeHaVips": 10, - "DescribeHpcClusters": 16, - "DescribeImageSharePermission": 10, - "DescribeImages": 38, - "DescribeImageSupportInstanceTypes": 16, - "DescribeInstanceAttribute": 36, - "DescribeInstanceAutoRenewAttribute": 17, - "DescribeInstanceHistoryEvents": 19, - "DescribeInstanceMonitorData": 19, - "DescribeInstancePhysicalAttribute": 10, - "DescribeInstanceRamRole": 11, - "DescribeInstancesFullStatus": 14, - "DescribeInstances": 10, - "DescribeInstanceStatus": 26, - "DescribeInstanceTopology": 12, - "DescribeInstanceTypeFamilies": 17, - "DescribeInstanceTypes": 17, - "DescribeInstanceVncPasswd": 10, - "DescribeInstanceVncUrl": 36, - "DescribeInvocationResults": 16, - "DescribeInvocations": 16, - "DescribeKeyPairs": 12, - "DescribeLaunchTemplates": 16, - "DescribeLaunchTemplateVersions": 16, - "DescribeLimitation": 36, - "DescribeNatGateways": 10, - "DescribeNetworkInterfacePermissions": 13, - "DescribeNetworkInterfaces": 16, - "DescribeNewProjectEipMonitorData": 16, - "DescribePhysicalConnections": 10, - "DescribePrice": 16, - "DescribeRecommendInstanceType": 10, - "DescribeRegions": 19, - "DescribeRenewalPrice": 16, - "DescribeResourceByTags": 10, - "DescribeResourcesModification": 17, - "DescribeRouterInterfaces": 10, - "DescribeRouteTables": 17, - "DescribeSecurityGroupAttribute": 133, - "DescribeSecurityGroupReferences": 16, - "DescribeSecurityGroups": 25, - "DescribeSnapshotLinks": 17, - "DescribeSnapshotMonitorData": 12, - "DescribeSnapshotPackage": 10, - "DescribeSnapshots": 26, - "DescribeSnapshotsUsage": 26, - "DescribeSpotPriceHistory": 22, - "DescribeTags": 17, - "DescribeTaskAttribute": 10, - "DescribeTasks": 11, - "DescribeUserBusinessBehavior": 13, - "DescribeUserData": 10, - "DescribeVirtualBorderRoutersForPhysicalConnection": 10, - "DescribeVirtualBorderRouters": 10, - "DescribeVpcs": 41, - "DescribeVRouters": 17, - "DescribeVSwitches": 17, - "DescribeZones": 103, - "DetachClassicLinkVpc": 14, - "DetachDisk": 17, - "DetachInstanceRamRole": 10, - "DetachKeyPair": 10, - "DetachNetworkInterface": 16, - "EipFillParams": 19, - "EipFillProduct": 13, - "EipNotifyPaid": 10, - "EnablePhysicalConnection": 10, - "ExportImage": 10, - "GetInstanceConsoleOutput": 14, - "GetInstanceScreenshot": 14, - "ImportImage": 29, - "ImportKeyPair": 10, - "InstallCloudAssistant": 10, - "InvokeCommand": 16, - "JoinResourceGroup": 10, - "JoinSecurityGroup": 66, - "LeaveSecurityGroup": 66, - "ModifyAutoSnapshotPolicyEx": 10, - "ModifyBandwidthPackageSpec": 11, - "ModifyCommand": 10, - "ModifyDeploymentSetAttribute": 10, - "ModifyDiskAttribute": 16, - "ModifyDiskChargeType": 13, - "ModifyEipAddressAttribute": 14, - "ModifyImageAttribute": 10, - "ModifyImageSharePermission": 16, - "ModifyInstanceAttribute": 22, - "ModifyInstanceAutoReleaseTime": 15, - "ModifyInstanceAutoRenewAttribute": 16, - "ModifyInstanceChargeType": 22, - "ModifyInstanceDeployment": 10, - "ModifyInstanceNetworkSpec": 36, - "ModifyInstanceSpec": 62, - "ModifyInstanceVncPasswd": 35, - "ModifyInstanceVpcAttribute": 15, - "ModifyLaunchTemplateDefaultVersion": 10, - "ModifyNetworkInterfaceAttribute": 10, - "ModifyPhysicalConnectionAttribute": 10, - "ModifyPrepayInstanceSpec": 13, - "ModifyRouterInterfaceAttribute": 10, - "ModifySecurityGroupAttribute": 10, - "ModifySecurityGroupEgressRule": 10, - "ModifySecurityGroupPolicy": 10, - "ModifySecurityGroupRule": 16, - "ModifySnapshotAttribute": 10, - "ModifyUserBusinessBehavior": 10, - "ModifyVirtualBorderRouterAttribute": 10, - "ModifyVpcAttribute": 10, - "ModifyVRouterAttribute": 10, - "ModifyVSwitchAttribute": 10, - "ReActivateInstances": 10, - "RebootInstance": 27, - "RedeployInstance": 14, - "ReInitDisk": 16, - "ReleaseDedicatedHost": 10, - "ReleaseEipAddress": 16, - "ReleasePublicIpAddress": 10, - "RemoveTags": 10, - "RenewInstance": 19, - "ReplaceSystemDisk": 36, - "ResetDisk": 36, - "ResizeDisk": 11, - "RevokeSecurityGroupEgress": 13, - "RevokeSecurityGroup": 16, - "RunInstances": 86, - "StartInstance": 46, - "StopInstance": 27, - "StopInvocation": 10, - "TerminatePhysicalConnection": 10, - "TerminateVirtualBorderRouter": 10, - "UnassignIpv6Addresses": 10, - "UnassignPrivateIpAddresses": 10, - "UnassociateEipAddress": 16 - } -} -` - -func getAPIMaxTimeout(product, actionName string) (time.Duration, bool) { - timeout := make(map[string]map[string]int) - err := json.Unmarshal([]byte(apiTimeouts), &timeout) - if err != nil { - return 0 * time.Millisecond, false - } - - obj := timeout[strings.ToLower(product)] - if obj != nil && obj[actionName] != 0 { - return time.Duration(obj[actionName]) * time.Second, true - } - - return 0 * time.Millisecond, false -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go deleted file mode 100644 index 7f20b7a4..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -type Credential interface { -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go deleted file mode 100644 index 68f82263..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go +++ /dev/null @@ -1,34 +0,0 @@ -package credentials - -// Deprecated: Use AccessKeyCredential in this package instead. -type BaseCredential struct { - AccessKeyId string - AccessKeySecret string -} - -type AccessKeyCredential struct { - AccessKeyId string - AccessKeySecret string -} - -// Deprecated: Use NewAccessKeyCredential in this package instead. -func NewBaseCredential(accessKeyId, accessKeySecret string) *BaseCredential { - return &BaseCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } -} - -func (baseCred *BaseCredential) ToAccessKeyCredential() *AccessKeyCredential { - return &AccessKeyCredential{ - AccessKeyId: baseCred.AccessKeyId, - AccessKeySecret: baseCred.AccessKeySecret, - } -} - -func NewAccessKeyCredential(accessKeyId, accessKeySecret string) *AccessKeyCredential { - return &AccessKeyCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/bearer_token_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/bearer_token_credential.go deleted file mode 100644 index 6d4763e6..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/bearer_token_credential.go +++ /dev/null @@ -1,12 +0,0 @@ -package credentials - -type BearerTokenCredential struct { - BearerToken string -} - -// NewBearerTokenCredential return a BearerTokenCredential object -func NewBearerTokenCredential(token string) *BearerTokenCredential { - return &BearerTokenCredential{ - BearerToken: token, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go deleted file mode 100644 index 55a5c2da..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go +++ /dev/null @@ -1,29 +0,0 @@ -package credentials - -func (oldCred *StsRoleNameOnEcsCredential) ToEcsRamRoleCredential() *EcsRamRoleCredential { - return &EcsRamRoleCredential{ - RoleName: oldCred.RoleName, - } -} - -type EcsRamRoleCredential struct { - RoleName string -} - -func NewEcsRamRoleCredential(roleName string) *EcsRamRoleCredential { - return &EcsRamRoleCredential{ - RoleName: roleName, - } -} - -// Deprecated: Use EcsRamRoleCredential in this package instead. -type StsRoleNameOnEcsCredential struct { - RoleName string -} - -// Deprecated: Use NewEcsRamRoleCredential in this package instead. -func NewStsRoleNameOnEcsCredential(roleName string) *StsRoleNameOnEcsCredential { - return &StsRoleNameOnEcsCredential{ - RoleName: roleName, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/env.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/env.go deleted file mode 100644 index 3cd0d020..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/env.go +++ /dev/null @@ -1,30 +0,0 @@ -package provider - -import ( - "errors" - "os" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" -) - -type EnvProvider struct{} - -var ProviderEnv = new(EnvProvider) - -func NewEnvProvider() Provider { - return &EnvProvider{} -} - -func (p *EnvProvider) Resolve() (auth.Credential, error) { - accessKeyID, ok1 := os.LookupEnv(ENVAccessKeyID) - accessKeySecret, ok2 := os.LookupEnv(ENVAccessKeySecret) - if !ok1 || !ok2 { - return nil, nil - } - if accessKeyID == "" || accessKeySecret == "" { - return nil, errors.New("Environmental variable (ALIBABACLOUD_ACCESS_KEY_ID or ALIBABACLOUD_ACCESS_KEY_SECRET) is empty") - } - return credentials.NewAccessKeyCredential(accessKeyID, accessKeySecret), nil -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/instance_credentials.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/instance_credentials.go deleted file mode 100644 index 074f6350..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/instance_credentials.go +++ /dev/null @@ -1,92 +0,0 @@ -package provider - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "os" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/" - -type InstanceCredentialsProvider struct{} - -var ProviderInstance = new(InstanceCredentialsProvider) - -var HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) { - return fn -} - -func NewInstanceCredentialsProvider() Provider { - return &InstanceCredentialsProvider{} -} - -func (p *InstanceCredentialsProvider) Resolve() (auth.Credential, error) { - roleName, ok := os.LookupEnv(ENVEcsMetadata) - if !ok { - return nil, nil - } - if roleName == "" { - return nil, errors.New("Environmental variable 'ALIBABA_CLOUD_ECS_METADATA' are empty") - } - status, content, err := HookGet(get)(securityCredURL + roleName) - if err != nil { - return nil, err - } - if status != 200 { - if status == 404 { - return nil, fmt.Errorf("The role was not found in the instance") - } - return nil, fmt.Errorf("Received %d when getting security credentials for %s", status, roleName) - } - body := make(map[string]interface{}) - - if err := json.Unmarshal(content, &body); err != nil { - return nil, err - } - - accessKeyID, err := extractString(body, "AccessKeyId") - if err != nil { - return nil, err - } - accessKeySecret, err := extractString(body, "AccessKeySecret") - if err != nil { - return nil, err - } - securityToken, err := extractString(body, "SecurityToken") - if err != nil { - return nil, err - } - - return credentials.NewStsTokenCredential(accessKeyID, accessKeySecret, securityToken), nil -} - -func get(url string) (status int, content []byte, err error) { - httpClient := http.DefaultClient - httpClient.Timeout = 1 * time.Second - resp, err := httpClient.Get(url) - if err != nil { - return - } - defer resp.Body.Close() - content, err = ioutil.ReadAll(resp.Body) - return resp.StatusCode, content, err -} - -func extractString(m map[string]interface{}, key string) (string, error) { - raw, ok := m[key] - if !ok { - return "", fmt.Errorf("%s not in map", key) - } - str, ok := raw.(string) - if !ok { - return "", fmt.Errorf("%s is not a string in map", key) - } - return str, nil -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/profile_credentials.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/profile_credentials.go deleted file mode 100644 index 146b9794..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/profile_credentials.go +++ /dev/null @@ -1,159 +0,0 @@ -package provider - -import ( - "bufio" - "errors" - "os" - "runtime" - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - - ini "gopkg.in/ini.v1" -) - -type ProfileProvider struct { - Profile string -} - -var ProviderProfile = NewProfileProvider() - -// NewProfileProvider receive zero or more parameters, -// when length of name is 0, the value of field Profile will be "default", -// and when there are multiple inputs, the function will take the -// first one and discard the other values. -func NewProfileProvider(name ...string) Provider { - p := new(ProfileProvider) - if len(name) == 0 { - p.Profile = "default" - } else { - p.Profile = name[0] - } - return p -} - -// Resolve implements the Provider interface -// when credential type is rsa_key_pair, the content of private_key file -// must be able to be parsed directly into the required string -// that NewRsaKeyPairCredential function needed -func (p *ProfileProvider) Resolve() (auth.Credential, error) { - path, ok := os.LookupEnv(ENVCredentialFile) - if !ok { - var err error - path, err = checkDefaultPath() - if err != nil { - return nil, err - } - if path == "" { - return nil, nil - } - } else if path == "" { - return nil, errors.New("Environment variable '" + ENVCredentialFile + "' cannot be empty") - } - - ini, err := ini.Load(path) - if err != nil { - return nil, errors.New("ERROR: Can not open file" + err.Error()) - } - - section, err := ini.GetSection(p.Profile) - if err != nil { - return nil, errors.New("ERROR: Can not load section" + err.Error()) - } - - value, err := section.GetKey("type") - if err != nil { - return nil, errors.New("ERROR: Can not find credential type" + err.Error()) - } - - switch value.String() { - case "access_key": - value1, err1 := section.GetKey("access_key_id") - value2, err2 := section.GetKey("access_key_secret") - if err1 != nil || err2 != nil { - return nil, errors.New("ERROR: Failed to get value") - } - if value1.String() == "" || value2.String() == "" { - return nil, errors.New("ERROR: Value can't be empty") - } - return credentials.NewAccessKeyCredential(value1.String(), value2.String()), nil - case "ecs_ram_role": - value1, err1 := section.GetKey("role_name") - if err1 != nil { - return nil, errors.New("ERROR: Failed to get value") - } - if value1.String() == "" { - return nil, errors.New("ERROR: Value can't be empty") - } - return credentials.NewEcsRamRoleCredential(value1.String()), nil - case "ram_role_arn": - value1, err1 := section.GetKey("access_key_id") - value2, err2 := section.GetKey("access_key_secret") - value3, err3 := section.GetKey("role_arn") - value4, err4 := section.GetKey("role_session_name") - if err1 != nil || err2 != nil || err3 != nil || err4 != nil { - return nil, errors.New("ERROR: Failed to get value") - } - if value1.String() == "" || value2.String() == "" || value3.String() == "" || value4.String() == "" { - return nil, errors.New("ERROR: Value can't be empty") - } - return credentials.NewRamRoleArnCredential(value1.String(), value2.String(), value3.String(), value4.String(), 3600), nil - case "rsa_key_pair": - value1, err1 := section.GetKey("public_key_id") - value2, err2 := section.GetKey("private_key_file") - if err1 != nil || err2 != nil { - return nil, errors.New("ERROR: Failed to get value") - } - if value1.String() == "" || value2.String() == "" { - return nil, errors.New("ERROR: Value can't be empty") - } - file, err := os.Open(value2.String()) - if err != nil { - return nil, errors.New("ERROR: Can not get private_key") - } - defer file.Close() - var privateKey string - scan := bufio.NewScanner(file) - var data string - for scan.Scan() { - if strings.HasPrefix(scan.Text(), "----") { - continue - } - data += scan.Text() + "\n" - } - return credentials.NewRsaKeyPairCredential(privateKey, value1.String(), 3600), nil - default: - return nil, errors.New("ERROR: Failed to get credential") - } -} - -// GetHomePath return home directory according to the system. -// if the environmental virables does not exist, will return empty -func GetHomePath() string { - if runtime.GOOS == "windows" { - path, ok := os.LookupEnv("USERPROFILE") - if !ok { - return "" - } - return path - } - path, ok := os.LookupEnv("HOME") - if !ok { - return "" - } - return path -} - -func checkDefaultPath() (path string, err error) { - path = GetHomePath() - if path == "" { - return "", errors.New("The default credential file path is invalid") - } - path = strings.Replace("~/.alibabacloud/credentials", "~", path, 1) - _, err = os.Stat(path) - if err != nil { - return "", nil - } - return path, nil -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider.go deleted file mode 100644 index ae4e168e..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider.go +++ /dev/null @@ -1,19 +0,0 @@ -package provider - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" -) - -//Environmental virables that may be used by the provider -const ( - ENVAccessKeyID = "ALIBABA_CLOUD_ACCESS_KEY_ID" - ENVAccessKeySecret = "ALIBABA_CLOUD_ACCESS_KEY_SECRET" - ENVCredentialFile = "ALIBABA_CLOUD_CREDENTIALS_FILE" - ENVEcsMetadata = "ALIBABA_CLOUD_ECS_METADATA" - PATHCredentialFile = "~/.alibabacloud/credentials" -) - -// When you want to customize the provider, you only need to implement the method of the interface. -type Provider interface { - Resolve() (auth.Credential, error) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider_chain.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider_chain.go deleted file mode 100644 index 3f9315d1..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider/provider_chain.go +++ /dev/null @@ -1,34 +0,0 @@ -package provider - -import ( - "errors" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" -) - -type ProviderChain struct { - Providers []Provider -} - -var defaultproviders = []Provider{ProviderEnv, ProviderProfile, ProviderInstance} -var DefaultChain = NewProviderChain(defaultproviders) - -func NewProviderChain(providers []Provider) Provider { - return &ProviderChain{ - Providers: providers, - } -} - -func (p *ProviderChain) Resolve() (auth.Credential, error) { - for _, provider := range p.Providers { - creds, err := provider.Resolve() - if err != nil { - return nil, err - } else if err == nil && creds == nil { - continue - } - return creds, err - } - return nil, errors.New("No credential found") - -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go deleted file mode 100644 index 00d688eb..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go +++ /dev/null @@ -1,15 +0,0 @@ -package credentials - -type RsaKeyPairCredential struct { - PrivateKey string - PublicKeyId string - SessionExpiration int -} - -func NewRsaKeyPairCredential(privateKey, publicKeyId string, sessionExpiration int) *RsaKeyPairCredential { - return &RsaKeyPairCredential{ - PrivateKey: privateKey, - PublicKeyId: publicKeyId, - SessionExpiration: sessionExpiration, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go deleted file mode 100644 index 554431ff..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go +++ /dev/null @@ -1,15 +0,0 @@ -package credentials - -type StsTokenCredential struct { - AccessKeyId string - AccessKeySecret string - AccessKeyStsToken string -} - -func NewStsTokenCredential(accessKeyId, accessKeySecret, accessKeyStsToken string) *StsTokenCredential { - return &StsTokenCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - AccessKeyStsToken: accessKeyStsToken, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go deleted file mode 100644 index 3507bdf9..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go +++ /dev/null @@ -1,62 +0,0 @@ -package credentials - -// Deprecated: Use RamRoleArnCredential in this package instead. -type StsRoleArnCredential struct { - AccessKeyId string - AccessKeySecret string - RoleArn string - RoleSessionName string - RoleSessionExpiration int -} - -type RamRoleArnCredential struct { - AccessKeyId string - AccessKeySecret string - RoleArn string - RoleSessionName string - RoleSessionExpiration int - Policy string - StsRegion string -} - -// Deprecated: Use RamRoleArnCredential in this package instead. -func NewStsRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *StsRoleArnCredential { - return &StsRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - RoleSessionExpiration: roleSessionExpiration, - } -} - -func (oldCred *StsRoleArnCredential) ToRamRoleArnCredential() *RamRoleArnCredential { - return &RamRoleArnCredential{ - AccessKeyId: oldCred.AccessKeyId, - AccessKeySecret: oldCred.AccessKeySecret, - RoleArn: oldCred.RoleArn, - RoleSessionName: oldCred.RoleSessionName, - RoleSessionExpiration: oldCred.RoleSessionExpiration, - } -} - -func NewRamRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *RamRoleArnCredential { - return &RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - RoleSessionExpiration: roleSessionExpiration, - } -} - -func NewRamRoleArnWithPolicyCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string, roleSessionExpiration int) *RamRoleArnCredential { - return &RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - RoleSessionExpiration: roleSessionExpiration, - Policy: policy, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go deleted file mode 100644 index 9c55811d..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -import ( - "bytes" - "sort" - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -var debug utils.Debug - -var hookGetDate = func(fn func() string) string { - return fn() -} - -func init() { - debug = utils.Init("sdk") -} - -func signRoaRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) { - // 先获取 accesskey,确保刷新 credential - accessKeyId, err := signer.GetAccessKeyId() - if err != nil { - return err - } - - completeROASignParams(request, signer, regionId) - stringToSign := buildRoaStringToSign(request) - request.SetStringToSign(stringToSign) - - signature := signer.Sign(stringToSign, "") - request.GetHeaders()["Authorization"] = "acs " + accessKeyId + ":" + signature - - return -} - -func completeROASignParams(request requests.AcsRequest, signer Signer, regionId string) { - headerParams := request.GetHeaders() - - // complete query params - queryParams := request.GetQueryParams() - //if _, ok := queryParams["RegionId"]; !ok { - // queryParams["RegionId"] = regionId - //} - if extraParam := signer.GetExtraParam(); extraParam != nil { - for key, value := range extraParam { - if key == "SecurityToken" { - headerParams["x-acs-security-token"] = value - continue - } - if key == "BearerToken" { - headerParams["x-acs-bearer-token"] = value - continue - } - queryParams[key] = value - } - } - - // complete header params - headerParams["Date"] = hookGetDate(utils.GetTimeInFormatRFC2616) - headerParams["x-acs-signature-method"] = signer.GetName() - headerParams["x-acs-signature-version"] = signer.GetVersion() - if request.GetFormParams() != nil && len(request.GetFormParams()) > 0 { - formString := utils.GetUrlFormedMap(request.GetFormParams()) - request.SetContent([]byte(formString)) - if headerParams["Content-Type"] == "" { - headerParams["Content-Type"] = requests.Form - } - } - contentMD5 := utils.GetMD5Base64(request.GetContent()) - headerParams["Content-MD5"] = contentMD5 - if _, contains := headerParams["Content-Type"]; !contains { - headerParams["Content-Type"] = requests.Raw - } - switch format := request.GetAcceptFormat(); format { - case "JSON": - headerParams["Accept"] = requests.Json - case "XML": - headerParams["Accept"] = requests.Xml - default: - headerParams["Accept"] = requests.Raw - } -} - -func buildRoaStringToSign(request requests.AcsRequest) (stringToSign string) { - - headers := request.GetHeaders() - - stringToSignBuilder := bytes.Buffer{} - stringToSignBuilder.WriteString(request.GetMethod()) - stringToSignBuilder.WriteString(requests.HeaderSeparator) - - // append header keys for sign - appendIfContain(headers, &stringToSignBuilder, "Accept", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Content-MD5", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Content-Type", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Date", requests.HeaderSeparator) - - // sort and append headers witch starts with 'x-acs-' - var acsHeaders []string - for key := range headers { - if strings.HasPrefix(key, "x-acs-") { - acsHeaders = append(acsHeaders, key) - } - } - sort.Strings(acsHeaders) - for _, key := range acsHeaders { - stringToSignBuilder.WriteString(key + ":" + headers[key]) - stringToSignBuilder.WriteString(requests.HeaderSeparator) - } - - // append query params - stringToSignBuilder.WriteString(request.BuildQueries()) - stringToSign = stringToSignBuilder.String() - debug("stringToSign: %s", stringToSign) - return -} - -func appendIfContain(sourceMap map[string]string, target *bytes.Buffer, key, separator string) { - if value, contain := sourceMap[key]; contain && len(value) > 0 { - target.WriteString(sourceMap[key]) - target.WriteString(separator) - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go deleted file mode 100644 index 33967b9e..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -import ( - "net/url" - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -var hookGetNonce = func(fn func() string) string { - return fn() -} - -func signRpcRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) { - err = completeRpcSignParams(request, signer, regionId) - if err != nil { - return - } - // remove while retry - if _, containsSign := request.GetQueryParams()["Signature"]; containsSign { - delete(request.GetQueryParams(), "Signature") - } - stringToSign := buildRpcStringToSign(request) - request.SetStringToSign(stringToSign) - signature := signer.Sign(stringToSign, "&") - request.GetQueryParams()["Signature"] = signature - - return -} - -func completeRpcSignParams(request requests.AcsRequest, signer Signer, regionId string) (err error) { - queryParams := request.GetQueryParams() - queryParams["Version"] = request.GetVersion() - queryParams["Action"] = request.GetActionName() - queryParams["Format"] = request.GetAcceptFormat() - queryParams["Timestamp"] = hookGetDate(utils.GetTimeInFormatISO8601) - queryParams["SignatureMethod"] = signer.GetName() - queryParams["SignatureType"] = signer.GetType() - queryParams["SignatureVersion"] = signer.GetVersion() - queryParams["SignatureNonce"] = hookGetNonce(utils.GetUUID) - queryParams["AccessKeyId"], err = signer.GetAccessKeyId() - - if err != nil { - return - } - - if _, contains := queryParams["RegionId"]; !contains { - queryParams["RegionId"] = regionId - } - if extraParam := signer.GetExtraParam(); extraParam != nil { - for key, value := range extraParam { - queryParams[key] = value - } - } - - request.GetHeaders()["Content-Type"] = requests.Form - formString := utils.GetUrlFormedMap(request.GetFormParams()) - request.SetContent([]byte(formString)) - - return -} - -func buildRpcStringToSign(request requests.AcsRequest) (stringToSign string) { - signParams := make(map[string]string) - for key, value := range request.GetQueryParams() { - signParams[key] = value - } - for key, value := range request.GetFormParams() { - signParams[key] = value - } - - stringToSign = utils.GetUrlFormedMap(signParams) - stringToSign = strings.Replace(stringToSign, "+", "%20", -1) - stringToSign = strings.Replace(stringToSign, "*", "%2A", -1) - stringToSign = strings.Replace(stringToSign, "%7E", "~", -1) - stringToSign = url.QueryEscape(stringToSign) - stringToSign = request.GetMethod() + "&%2F&" + stringToSign - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go deleted file mode 100644 index cbbc3cef..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -import ( - "fmt" - "reflect" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -type Signer interface { - GetName() string - GetType() string - GetVersion() string - GetAccessKeyId() (string, error) - GetExtraParam() map[string]string - Sign(stringToSign, secretSuffix string) string -} - -func NewSignerWithCredential(credential Credential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer Signer, err error) { - switch instance := credential.(type) { - case *credentials.AccessKeyCredential: - { - signer = signers.NewAccessKeySigner(instance) - } - case *credentials.StsTokenCredential: - { - signer = signers.NewStsTokenSigner(instance) - } - case *credentials.BearerTokenCredential: - { - signer = signers.NewBearerTokenSigner(instance) - } - case *credentials.RamRoleArnCredential: - { - signer, err = signers.NewRamRoleArnSigner(instance, commonApi) - } - case *credentials.RsaKeyPairCredential: - { - signer, err = signers.NewSignerKeyPair(instance, commonApi) - } - case *credentials.EcsRamRoleCredential: - { - signer = signers.NewEcsRamRoleSigner(instance, commonApi) - } - case *credentials.BaseCredential: // deprecated user interface - { - signer = signers.NewAccessKeySigner(instance.ToAccessKeyCredential()) - } - case *credentials.StsRoleArnCredential: // deprecated user interface - { - signer, err = signers.NewRamRoleArnSigner(instance.ToRamRoleArnCredential(), commonApi) - } - case *credentials.StsRoleNameOnEcsCredential: // deprecated user interface - { - signer = signers.NewEcsRamRoleSigner(instance.ToEcsRamRoleCredential(), commonApi) - } - default: - message := fmt.Sprintf(errors.UnsupportedCredentialErrorMessage, reflect.TypeOf(credential)) - err = errors.NewClientError(errors.UnsupportedCredentialErrorCode, message, nil) - } - return -} - -func Sign(request requests.AcsRequest, signer Signer, regionId string) (err error) { - switch request.GetStyle() { - case requests.ROA: - { - err = signRoaRequest(request, signer, regionId) - } - case requests.RPC: - { - err = signRpcRequest(request, signer, regionId) - } - default: - message := fmt.Sprintf(errors.UnknownRequestTypeErrorMessage, reflect.TypeOf(request)) - err = errors.NewClientError(errors.UnknownRequestTypeErrorCode, message, nil) - } - - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go deleted file mode 100644 index 887f5020..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "crypto" - "crypto/hmac" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/base64" -) - -func ShaHmac1(source, secret string) string { - key := []byte(secret) - hmac := hmac.New(sha1.New, key) - hmac.Write([]byte(source)) - signedBytes := hmac.Sum(nil) - signedString := base64.StdEncoding.EncodeToString(signedBytes) - return signedString -} - -func Sha256WithRsa(source, secret string) string { - // block, _ := pem.Decode([]byte(secret)) - decodeString, err := base64.StdEncoding.DecodeString(secret) - if err != nil { - panic(err) - } - private, err := x509.ParsePKCS8PrivateKey(decodeString) - if err != nil { - panic(err) - } - - h := crypto.Hash.New(crypto.SHA256) - h.Write([]byte(source)) - hashed := h.Sum(nil) - signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey), - crypto.SHA256, hashed) - if err != nil { - panic(err) - } - - return base64.StdEncoding.EncodeToString(signature) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go deleted file mode 100644 index ba291a41..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -const defaultInAdvanceScale = 0.95 - -type credentialUpdater struct { - credentialExpiration int - lastUpdateTimestamp int64 - inAdvanceScale float64 - buildRequestMethod func() (*requests.CommonRequest, error) - responseCallBack func(response *responses.CommonResponse) error - refreshApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) -} - -func (updater *credentialUpdater) needUpdateCredential() (result bool) { - if updater.inAdvanceScale == 0 { - updater.inAdvanceScale = defaultInAdvanceScale - } - return time.Now().Unix()-updater.lastUpdateTimestamp >= int64(float64(updater.credentialExpiration)*updater.inAdvanceScale) -} - -func (updater *credentialUpdater) updateCredential() (err error) { - request, err := updater.buildRequestMethod() - if err != nil { - return - } - response, err := updater.refreshApi(request) - if err != nil { - return - } - updater.lastUpdateTimestamp = time.Now().Unix() - err = updater.responseCallBack(response) - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go deleted file mode 100644 index 99c624c8..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go +++ /dev/null @@ -1,7 +0,0 @@ -package signers - -type SessionCredential struct { - AccessKeyId string - AccessKeySecret string - StsToken string -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go deleted file mode 100644 index bc4f35b8..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type AccessKeySigner struct { - credential *credentials.AccessKeyCredential -} - -func (signer *AccessKeySigner) GetExtraParam() map[string]string { - return nil -} - -func NewAccessKeySigner(credential *credentials.AccessKeyCredential) *AccessKeySigner { - return &AccessKeySigner{ - credential: credential, - } -} - -func (*AccessKeySigner) GetName() string { - return "HMAC-SHA1" -} - -func (*AccessKeySigner) GetType() string { - return "" -} - -func (*AccessKeySigner) GetVersion() string { - return "1.0" -} - -func (signer *AccessKeySigner) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.AccessKeyId, nil -} - -func (signer *AccessKeySigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_bearer_token.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_bearer_token.go deleted file mode 100644 index 75b78433..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_bearer_token.go +++ /dev/null @@ -1,35 +0,0 @@ -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type BearerTokenSigner struct { - credential *credentials.BearerTokenCredential -} - -func NewBearerTokenSigner(credential *credentials.BearerTokenCredential) *BearerTokenSigner { - return &BearerTokenSigner{ - credential: credential, - } -} - -func (signer *BearerTokenSigner) GetExtraParam() map[string]string { - return map[string]string{"BearerToken": signer.credential.BearerToken} -} - -func (*BearerTokenSigner) GetName() string { - return "" -} -func (*BearerTokenSigner) GetType() string { - return "BEARERTOKEN" -} -func (*BearerTokenSigner) GetVersion() string { - return "1.0" -} -func (signer *BearerTokenSigner) GetAccessKeyId() (accessKeyId string, err error) { - return "", nil -} -func (signer *BearerTokenSigner) Sign(stringToSign, secretSuffix string) string { - return "" -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go deleted file mode 100644 index 73788429..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - jmespath "github.com/jmespath/go-jmespath" -) - -var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/" - -type EcsRamRoleSigner struct { - *credentialUpdater - sessionCredential *SessionCredential - credential *credentials.EcsRamRoleCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewEcsRamRoleSigner(credential *credentials.EcsRamRoleCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *EcsRamRoleSigner) { - signer = &EcsRamRoleSigner{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: defaultDurationSeconds / 60, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - return signer -} - -func (*EcsRamRoleSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*EcsRamRoleSigner) GetType() string { - return "" -} - -func (*EcsRamRoleSigner) GetVersion() string { - return "1.0" -} - -func (signer *EcsRamRoleSigner) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - if err != nil { - return - } - } - if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 { - return "", nil - } - return signer.sessionCredential.AccessKeyId, nil -} - -func (signer *EcsRamRoleSigner) GetExtraParam() map[string]string { - if signer.sessionCredential == nil { - return make(map[string]string) - } - if len(signer.sessionCredential.StsToken) <= 0 { - return make(map[string]string) - } - return map[string]string{"SecurityToken": signer.sessionCredential.StsToken} -} - -func (signer *EcsRamRoleSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *EcsRamRoleSigner) buildCommonRequest() (request *requests.CommonRequest, err error) { - return -} - -func (signer *EcsRamRoleSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - requestUrl := securityCredURL + signer.credential.RoleName - httpRequest, err := http.NewRequest(requests.GET, requestUrl, strings.NewReader("")) - if err != nil { - err = fmt.Errorf("refresh Ecs sts token err: %s", err.Error()) - return - } - httpClient := &http.Client{} - httpResponse, err := httpClient.Do(httpRequest) - if err != nil { - err = fmt.Errorf("refresh Ecs sts token err: %s", err.Error()) - return - } - - response = responses.NewCommonResponse() - err = responses.Unmarshal(response, httpResponse, "") - return -} - -func (signer *EcsRamRoleSigner) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - return fmt.Errorf("refresh Ecs sts token err, httpStatus: %d, message = %s", response.GetHttpStatus(), response.GetHttpContentString()) - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - return fmt.Errorf("refresh Ecs sts token err, json.Unmarshal fail: %s", err.Error()) - } - code, err := jmespath.Search("Code", data) - if err != nil { - return fmt.Errorf("refresh Ecs sts token err, fail to get Code: %s", err.Error()) - } - if code.(string) != "Success" { - return fmt.Errorf("refresh Ecs sts token err, Code is not Success") - } - accessKeyId, err := jmespath.Search("AccessKeyId", data) - if err != nil { - return fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeyId: %s", err.Error()) - } - accessKeySecret, err := jmespath.Search("AccessKeySecret", data) - if err != nil { - return fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeySecret: %s", err.Error()) - } - securityToken, err := jmespath.Search("SecurityToken", data) - if err != nil { - return fmt.Errorf("refresh Ecs sts token err, fail to get SecurityToken: %s", err.Error()) - } - expiration, err := jmespath.Search("Expiration", data) - if err != nil { - return fmt.Errorf("refresh Ecs sts token err, fail to get Expiration: %s", err.Error()) - } - if accessKeyId == nil || accessKeySecret == nil || securityToken == nil || expiration == nil { - return - } - - expirationTime, err := time.Parse("2006-01-02T15:04:05Z", expiration.(string)) - signer.credentialExpiration = int(expirationTime.Unix() - time.Now().Unix()) - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - StsToken: securityToken.(string), - } - - return -} - -func (signer *EcsRamRoleSigner) GetSessionCredential() *SessionCredential { - return signer.sessionCredential -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go deleted file mode 100644 index 19273d5a..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "encoding/json" - "fmt" - "net/http" - "strconv" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - jmespath "github.com/jmespath/go-jmespath" -) - -type SignerKeyPair struct { - *credentialUpdater - sessionCredential *SessionCredential - credential *credentials.RsaKeyPairCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewSignerKeyPair(credential *credentials.RsaKeyPairCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *SignerKeyPair, err error) { - signer = &SignerKeyPair{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: credential.SessionExpiration, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - if credential.SessionExpiration > 0 { - if credential.SessionExpiration >= 900 && credential.SessionExpiration <= 3600 { - signer.credentialExpiration = credential.SessionExpiration - } else { - err = errors.NewClientError(errors.InvalidParamErrorCode, "Key Pair session duration should be in the range of 15min - 1Hr", nil) - } - } else { - signer.credentialExpiration = defaultDurationSeconds - } - return -} - -func (*SignerKeyPair) GetName() string { - return "HMAC-SHA1" -} - -func (*SignerKeyPair) GetType() string { - return "" -} - -func (*SignerKeyPair) GetVersion() string { - return "1.0" -} - -func (signer *SignerKeyPair) ensureCredential() error { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - return signer.updateCredential() - } - return nil -} - -func (signer *SignerKeyPair) GetAccessKeyId() (accessKeyId string, err error) { - err = signer.ensureCredential() - if err != nil { - return - } - if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 { - accessKeyId = "" - return - } - - accessKeyId = signer.sessionCredential.AccessKeyId - return -} - -func (signer *SignerKeyPair) GetExtraParam() map[string]string { - return make(map[string]string) -} - -func (signer *SignerKeyPair) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *SignerKeyPair) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - request.Product = "Sts" - request.Version = "2015-04-01" - request.ApiName = "GenerateSessionAccessKey" - request.Scheme = requests.HTTPS - request.SetDomain("sts.ap-northeast-1.aliyuncs.com") - request.QueryParams["PublicKeyId"] = signer.credential.PublicKeyId - request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration) - return -} - -func (signer *SignerKeyPair) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - signerV2 := NewSignerV2(signer.credential) - return signer.commonApi(request, signerV2) -} - -func (signer *SignerKeyPair) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - message := "refresh session AccessKey failed" - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - return fmt.Errorf("refresh KeyPair err, json.Unmarshal fail: %s", err.Error()) - } - accessKeyId, err := jmespath.Search("SessionAccessKey.SessionAccessKeyId", data) - if err != nil { - return fmt.Errorf("refresh KeyPair err, fail to get SessionAccessKeyId: %s", err.Error()) - } - accessKeySecret, err := jmespath.Search("SessionAccessKey.SessionAccessKeySecret", data) - if err != nil { - return fmt.Errorf("refresh KeyPair err, fail to get SessionAccessKeySecret: %s", err.Error()) - } - if accessKeyId == nil || accessKeySecret == nil { - return - } - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go deleted file mode 100644 index a01001bc..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "encoding/json" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - jmespath "github.com/jmespath/go-jmespath" -) - -const ( - defaultDurationSeconds = 3600 -) - -type RamRoleArnSigner struct { - *credentialUpdater - roleSessionName string - sessionCredential *SessionCredential - credential *credentials.RamRoleArnCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewRamRoleArnSigner(credential *credentials.RamRoleArnCredential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer *RamRoleArnSigner, err error) { - signer = &RamRoleArnSigner{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: credential.RoleSessionExpiration, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - if len(credential.RoleSessionName) > 0 { - signer.roleSessionName = credential.RoleSessionName - } else { - signer.roleSessionName = "aliyun-go-sdk-" + strconv.FormatInt(time.Now().UnixNano()/1000, 10) - } - if credential.RoleSessionExpiration > 0 { - if credential.RoleSessionExpiration >= 900 && credential.RoleSessionExpiration <= 3600 { - signer.credentialExpiration = credential.RoleSessionExpiration - } else { - err = errors.NewClientError(errors.InvalidParamErrorCode, "Assume Role session duration should be in the range of 15min - 1Hr", nil) - } - } else { - signer.credentialExpiration = defaultDurationSeconds - } - return -} - -func (*RamRoleArnSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*RamRoleArnSigner) GetType() string { - return "" -} - -func (*RamRoleArnSigner) GetVersion() string { - return "1.0" -} - -func (signer *RamRoleArnSigner) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - if err != nil { - return - } - } - - if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 { - return "", err - } - - return signer.sessionCredential.AccessKeyId, nil -} - -func (signer *RamRoleArnSigner) GetExtraParam() map[string]string { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - signer.updateCredential() - } - if signer.sessionCredential == nil || len(signer.sessionCredential.StsToken) <= 0 { - return make(map[string]string) - } - return map[string]string{"SecurityToken": signer.sessionCredential.StsToken} -} - -func (signer *RamRoleArnSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *RamRoleArnSigner) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - if signer.credential.StsRegion != "" { - request.Domain = fmt.Sprintf("sts.%s.aliyuncs.com", signer.credential.StsRegion) - } else { - request.Domain = "sts.aliyuncs.com" - } - request.Product = "Sts" - request.Version = "2015-04-01" - request.ApiName = "AssumeRole" - request.Scheme = requests.HTTPS - request.QueryParams["RoleArn"] = signer.credential.RoleArn - if signer.credential.Policy != "" { - request.QueryParams["Policy"] = signer.credential.Policy - } - request.QueryParams["RoleSessionName"] = signer.credential.RoleSessionName - request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration) - return -} - -func (signer *RamRoleArnSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - credential := &credentials.AccessKeyCredential{ - AccessKeyId: signer.credential.AccessKeyId, - AccessKeySecret: signer.credential.AccessKeySecret, - } - signerV1 := NewAccessKeySigner(credential) - return signer.commonApi(request, signerV1) -} - -func (signer *RamRoleArnSigner) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - message := "refresh session token failed" - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - return fmt.Errorf("refresh RoleArn sts token err, json.Unmarshal fail: %s", err.Error()) - } - accessKeyId, err := jmespath.Search("Credentials.AccessKeyId", data) - if err != nil { - return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeyId: %s", err.Error()) - } - accessKeySecret, err := jmespath.Search("Credentials.AccessKeySecret", data) - if err != nil { - return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeySecret: %s", err.Error()) - } - securityToken, err := jmespath.Search("Credentials.SecurityToken", data) - if err != nil { - return fmt.Errorf("refresh RoleArn sts token err, fail to get SecurityToken: %s", err.Error()) - } - if accessKeyId == nil || accessKeySecret == nil || securityToken == nil { - return - } - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - StsToken: securityToken.(string), - } - return -} - -func (signer *RamRoleArnSigner) GetSessionCredential() *SessionCredential { - return signer.sessionCredential -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go deleted file mode 100644 index d0ce36c3..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type StsTokenSigner struct { - credential *credentials.StsTokenCredential -} - -func NewStsTokenSigner(credential *credentials.StsTokenCredential) *StsTokenSigner { - return &StsTokenSigner{ - credential: credential, - } -} - -func (*StsTokenSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*StsTokenSigner) GetType() string { - return "" -} - -func (*StsTokenSigner) GetVersion() string { - return "1.0" -} - -func (signer *StsTokenSigner) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.AccessKeyId, nil -} - -func (signer *StsTokenSigner) GetExtraParam() map[string]string { - return map[string]string{"SecurityToken": signer.credential.AccessKeyStsToken} -} - -func (signer *StsTokenSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go deleted file mode 100644 index 97348529..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type SignerV2 struct { - credential *credentials.RsaKeyPairCredential -} - -func (signer *SignerV2) GetExtraParam() map[string]string { - return nil -} - -func NewSignerV2(credential *credentials.RsaKeyPairCredential) *SignerV2 { - return &SignerV2{ - credential: credential, - } -} - -func (*SignerV2) GetName() string { - return "SHA256withRSA" -} - -func (*SignerV2) GetType() string { - return "PRIVATEKEY" -} - -func (*SignerV2) GetVersion() string { - return "1.0" -} - -func (signer *SignerV2) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.PublicKeyId, err -} - -func (signer *SignerV2) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.PrivateKey - return Sha256WithRsa(stringToSign, secret) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go deleted file mode 100644 index 1cafecfc..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go +++ /dev/null @@ -1,853 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sdk - -import ( - "context" - "crypto/tls" - "fmt" - "net" - "net/http" - "net/url" - "os" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -var debug utils.Debug - -func init() { - debug = utils.Init("sdk") -} - -// Version this value will be replaced while build: -ldflags="-X sdk.version=x.x.x" -var Version = "0.0.1" -var defaultConnectTimeout = 5 * time.Second -var defaultReadTimeout = 10 * time.Second - -var DefaultUserAgent = fmt.Sprintf("AlibabaCloud (%s; %s) Golang/%s Core/%s", runtime.GOOS, runtime.GOARCH, strings.Trim(runtime.Version(), "go"), Version) - -var hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) { - return fn -} - -// Client the type Client -type Client struct { - SourceIp string - SecureTransport string - isInsecure bool - regionId string - config *Config - httpProxy string - httpsProxy string - noProxy string - logger *Logger - userAgent map[string]string - signer auth.Signer - httpClient *http.Client - asyncTaskQueue chan func() - readTimeout time.Duration - connectTimeout time.Duration - EndpointMap map[string]string - EndpointType string - Network string - Domain string - isOpenAsync bool -} - -func (client *Client) Init() (err error) { - panic("not support yet") -} - -func (client *Client) SetEndpointRules(endpointMap map[string]string, endpointType string, netWork string) { - client.EndpointMap = endpointMap - client.Network = netWork - client.EndpointType = endpointType -} - -func (client *Client) SetHTTPSInsecure(isInsecure bool) { - client.isInsecure = isInsecure -} - -func (client *Client) GetHTTPSInsecure() bool { - return client.isInsecure -} - -func (client *Client) SetHttpsProxy(httpsProxy string) { - client.httpsProxy = httpsProxy -} - -func (client *Client) GetHttpsProxy() string { - return client.httpsProxy -} - -func (client *Client) SetHttpProxy(httpProxy string) { - client.httpProxy = httpProxy -} - -func (client *Client) GetHttpProxy() string { - return client.httpProxy -} - -func (client *Client) SetNoProxy(noProxy string) { - client.noProxy = noProxy -} - -func (client *Client) GetNoProxy() string { - return client.noProxy -} - -func (client *Client) SetTransport(transport http.RoundTripper) { - if client.httpClient == nil { - client.httpClient = &http.Client{} - } - client.httpClient.Transport = transport -} - -// InitWithProviderChain will get credential from the providerChain, -// the RsaKeyPairCredential Only applicable to regionID `ap-northeast-1`, -// if your providerChain may return a credential type with RsaKeyPairCredential, -// please ensure your regionID is `ap-northeast-1`. -func (client *Client) InitWithProviderChain(regionId string, provider provider.Provider) (err error) { - config := client.InitClientConfig() - credential, err := provider.Resolve() - if err != nil { - return - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) { - if regionId != "" { - match, _ := regexp.MatchString("^[a-zA-Z0-9_-]+$", regionId) - if !match { - return fmt.Errorf("regionId contains invalid characters") - } - } - - client.regionId = regionId - client.config = config - client.httpClient = &http.Client{} - - if config.Transport != nil { - client.httpClient.Transport = config.Transport - } else if config.HttpTransport != nil { - client.httpClient.Transport = config.HttpTransport - } - - if config.Timeout > 0 { - client.httpClient.Timeout = config.Timeout - } - - if config.EnableAsync { - client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize) - } - - client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner) - - return -} - -func (client *Client) SetReadTimeout(readTimeout time.Duration) { - client.readTimeout = readTimeout -} - -func (client *Client) SetConnectTimeout(connectTimeout time.Duration) { - client.connectTimeout = connectTimeout -} - -func (client *Client) GetReadTimeout() time.Duration { - return client.readTimeout -} - -func (client *Client) GetConnectTimeout() time.Duration { - return client.connectTimeout -} - -func (client *Client) getHttpProxy(scheme string) (proxy *url.URL, err error) { - if scheme == "https" { - if client.GetHttpsProxy() != "" { - proxy, err = url.Parse(client.httpsProxy) - } else if rawurl := os.Getenv("HTTPS_PROXY"); rawurl != "" { - proxy, err = url.Parse(rawurl) - } else if rawurl := os.Getenv("https_proxy"); rawurl != "" { - proxy, err = url.Parse(rawurl) - } - } else { - if client.GetHttpProxy() != "" { - proxy, err = url.Parse(client.httpProxy) - } else if rawurl := os.Getenv("HTTP_PROXY"); rawurl != "" { - proxy, err = url.Parse(rawurl) - } else if rawurl := os.Getenv("http_proxy"); rawurl != "" { - proxy, err = url.Parse(rawurl) - } - } - - return proxy, err -} - -func (client *Client) getNoProxy(scheme string) []string { - var urls []string - if client.GetNoProxy() != "" { - urls = strings.Split(client.noProxy, ",") - } else if rawurl := os.Getenv("NO_PROXY"); rawurl != "" { - urls = strings.Split(rawurl, ",") - } else if rawurl := os.Getenv("no_proxy"); rawurl != "" { - urls = strings.Split(rawurl, ",") - } - - return urls -} - -// EnableAsync enable the async task queue -func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) { - if client.isOpenAsync { - fmt.Println("warning: Please not call EnableAsync repeatedly") - return - } - client.isOpenAsync = true - client.asyncTaskQueue = make(chan func(), maxTaskQueueSize) - for i := 0; i < routinePoolSize; i++ { - go func() { - for { - task, notClosed := <-client.asyncTaskQueue - if !notClosed { - return - } else { - task() - } - } - }() - } -} - -func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) { - config := client.InitClientConfig() - credential := &credentials.AccessKeyCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithStsToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) { - config := client.InitClientConfig() - credential := &credentials.StsTokenCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - AccessKeyStsToken: securityToken, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) { - config := client.InitClientConfig() - credential := &credentials.RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (err error) { - config := client.InitClientConfig() - credential := &credentials.RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - Policy: policy, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) { - config := client.InitClientConfig() - credential := &credentials.RsaKeyPairCredential{ - PrivateKey: privateKey, - PublicKeyId: publicKeyId, - SessionExpiration: sessionExpiration, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) { - config := client.InitClientConfig() - credential := &credentials.EcsRamRoleCredential{ - RoleName: roleName, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithBearerToken(regionId, bearerToken string) (err error) { - config := client.InitClientConfig() - credential := &credentials.BearerTokenCredential{ - BearerToken: bearerToken, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitClientConfig() (config *Config) { - if client.config != nil { - return client.config - } else { - return NewConfig() - } -} - -func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) { - if (client.SecureTransport == "false" || client.SecureTransport == "true") && client.SourceIp != "" { - t := reflect.TypeOf(request).Elem() - v := reflect.ValueOf(request).Elem() - for i := 0; i < t.NumField(); i++ { - value := v.FieldByName(t.Field(i).Name) - if t.Field(i).Name == "requests.RoaRequest" { - request.GetHeaders()["x-acs-proxy-source-ip"] = client.SourceIp - request.GetHeaders()["x-acs-proxy-secure-transport"] = client.SecureTransport - return client.DoActionWithSigner(request, response, nil) - } else if t.Field(i).Name == "PathPattern" && !value.IsZero() { - request.GetHeaders()["x-acs-proxy-source-ip"] = client.SourceIp - request.GetHeaders()["x-acs-proxy-secure-transport"] = client.SecureTransport - return client.DoActionWithSigner(request, response, nil) - } else if i == t.NumField()-1 { - request.GetQueryParams()["SourceIp"] = client.SourceIp - request.GetQueryParams()["SecureTransport"] = client.SecureTransport - return client.DoActionWithSigner(request, response, nil) - } - } - } - return client.DoActionWithSigner(request, response, nil) -} -func (client *Client) GetEndpointRules(regionId string, product string) (endpointRaw string, err error) { - if client.EndpointType == "regional" { - if regionId == "" { - err = fmt.Errorf("RegionId is empty, please set a valid RegionId.") - return "", err - } - endpointRaw = strings.Replace("..aliyuncs.com", "", regionId, 1) - } else { - endpointRaw = ".aliyuncs.com" - } - endpointRaw = strings.Replace(endpointRaw, "", strings.ToLower(product), 1) - if client.Network == "" || client.Network == "public" { - endpointRaw = strings.Replace(endpointRaw, "", "", 1) - } else { - endpointRaw = strings.Replace(endpointRaw, "", "-"+client.Network, 1) - } - return endpointRaw, nil -} - -func (client *Client) buildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (httpRequest *http.Request, err error) { - // add clientVersion - request.GetHeaders()["x-sdk-core-version"] = Version - - regionId := client.regionId - if len(request.GetRegionId()) > 0 { - regionId = request.GetRegionId() - } - - // resolve endpoint - endpoint := request.GetDomain() - - if endpoint == "" && client.Domain != "" { - endpoint = client.Domain - } - - if endpoint == "" { - endpoint = endpoints.GetEndpointFromMap(regionId, request.GetProduct()) - } - - if endpoint == "" && client.EndpointType != "" && - (request.GetProduct() != "Sts" || len(request.GetQueryParams()) == 0) { - if client.EndpointMap != nil && client.Network == "" || client.Network == "public" { - endpoint = client.EndpointMap[regionId] - } - - if endpoint == "" { - endpoint, err = client.GetEndpointRules(regionId, request.GetProduct()) - if err != nil { - return - } - } - } - - if endpoint == "" { - resolveParam := &endpoints.ResolveParam{ - Domain: request.GetDomain(), - Product: request.GetProduct(), - RegionId: regionId, - LocationProduct: request.GetLocationServiceCode(), - LocationEndpointType: request.GetLocationEndpointType(), - CommonApi: client.ProcessCommonRequest, - } - endpoint, err = endpoints.Resolve(resolveParam) - if err != nil { - return - } - } - - request.SetDomain(endpoint) - if request.GetScheme() == "" { - request.SetScheme(client.config.Scheme) - } - // init request params - err = requests.InitParams(request) - if err != nil { - return - } - - // signature - var finalSigner auth.Signer - if signer != nil { - finalSigner = signer - } else { - finalSigner = client.signer - } - httpRequest, err = buildHttpRequest(request, finalSigner, regionId) - if err == nil { - userAgent := DefaultUserAgent + getSendUserAgent(client.config.UserAgent, client.userAgent, request.GetUserAgent()) - httpRequest.Header.Set("User-Agent", userAgent) - } - - return -} - -func getSendUserAgent(configUserAgent string, clientUserAgent, requestUserAgent map[string]string) string { - realUserAgent := "" - for key1, value1 := range clientUserAgent { - for key2 := range requestUserAgent { - if key1 == key2 { - key1 = "" - } - } - if key1 != "" { - realUserAgent += fmt.Sprintf(" %s/%s", key1, value1) - - } - } - for key, value := range requestUserAgent { - realUserAgent += fmt.Sprintf(" %s/%s", key, value) - } - if configUserAgent != "" { - return realUserAgent + fmt.Sprintf(" Extra/%s", configUserAgent) - } - return realUserAgent -} - -func (client *Client) AppendUserAgent(key, value string) { - newkey := true - - if client.userAgent == nil { - client.userAgent = make(map[string]string) - } - if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" { - for tag := range client.userAgent { - if tag == key { - client.userAgent[tag] = value - newkey = false - } - } - if newkey { - client.userAgent[key] = value - } - } -} - -func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) { - _, err = client.buildRequestWithSigner(request, signer) - return -} - -func (client *Client) getTimeout(request requests.AcsRequest) (time.Duration, time.Duration) { - readTimeout := defaultReadTimeout - connectTimeout := defaultConnectTimeout - - reqReadTimeout := request.GetReadTimeout() - reqConnectTimeout := request.GetConnectTimeout() - if reqReadTimeout != 0*time.Millisecond { - readTimeout = reqReadTimeout - } else if client.readTimeout != 0*time.Millisecond { - readTimeout = client.readTimeout - } else if client.httpClient.Timeout != 0 { - readTimeout = client.httpClient.Timeout - } else if timeout, ok := getAPIMaxTimeout(request.GetProduct(), request.GetActionName()); ok { - readTimeout = timeout - } - - if reqConnectTimeout != 0*time.Millisecond { - connectTimeout = reqConnectTimeout - } else if client.connectTimeout != 0*time.Millisecond { - connectTimeout = client.connectTimeout - } - return readTimeout, connectTimeout -} - -func Timeout(connectTimeout time.Duration) func(cxt context.Context, net, addr string) (c net.Conn, err error) { - return func(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{ - Timeout: connectTimeout, - DualStack: true, - }).DialContext(ctx, network, address) - } -} - -func (client *Client) setTimeout(request requests.AcsRequest) { - readTimeout, connectTimeout := client.getTimeout(request) - client.httpClient.Timeout = readTimeout - if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil { - trans.DialContext = Timeout(connectTimeout) - client.httpClient.Transport = trans - } else if client.httpClient.Transport == nil { - client.httpClient.Transport = &http.Transport{ - DialContext: Timeout(connectTimeout), - } - } -} - -func (client *Client) getHTTPSInsecure(request requests.AcsRequest) (insecure bool) { - if request.GetHTTPSInsecure() != nil { - insecure = *request.GetHTTPSInsecure() - } else { - insecure = client.GetHTTPSInsecure() - } - return insecure -} - -func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) { - if client.Network != "" { - match, _ := regexp.MatchString("^[a-zA-Z0-9_-]+$", client.Network) - if !match { - return fmt.Errorf("netWork contains invalid characters") - } - } - fieldMap := make(map[string]string) - initLogMsg(fieldMap) - defer func() { - client.printLog(fieldMap, err) - }() - httpRequest, err := client.buildRequestWithSigner(request, signer) - if err != nil { - return - } - - client.setTimeout(request) - proxy, err := client.getHttpProxy(httpRequest.URL.Scheme) - if err != nil { - return err - } - - noProxy := client.getNoProxy(httpRequest.URL.Scheme) - - var flag bool - for _, value := range noProxy { - if strings.HasPrefix(value, "*") { - value = fmt.Sprintf(".%s", value) - } - noProxyReg, err := regexp.Compile(value) - if err != nil { - return err - } - if noProxyReg.MatchString(httpRequest.Host) { - flag = true - break - } - } - - // Set whether to ignore certificate validation. - // Default InsecureSkipVerify is false. - if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil { - if trans.TLSClientConfig != nil { - trans.TLSClientConfig.InsecureSkipVerify = client.getHTTPSInsecure(request) - } else { - trans.TLSClientConfig = &tls.Config{ - InsecureSkipVerify: client.getHTTPSInsecure(request), - } - } - if proxy != nil && !flag { - trans.Proxy = http.ProxyURL(proxy) - } - client.httpClient.Transport = trans - } - - var httpResponse *http.Response - for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ { - if proxy != nil && proxy.User != nil { - if password, passwordSet := proxy.User.Password(); passwordSet { - httpRequest.SetBasicAuth(proxy.User.Username(), password) - } - } - if retryTimes > 0 { - client.printLog(fieldMap, err) - initLogMsg(fieldMap) - } - putMsgToMap(fieldMap, httpRequest) - debug("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto) - debug("> Host: %s", httpRequest.Host) - for key, value := range httpRequest.Header { - debug("> %s: %v", key, strings.Join(value, "")) - } - debug(">") - debug(" Retry Times: %d.", retryTimes) - - startTime := time.Now() - fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05") - httpResponse, err = hookDo(client.httpClient.Do)(httpRequest) - fieldMap["{cost}"] = time.Since(startTime).String() - if err == nil { - fieldMap["{code}"] = strconv.Itoa(httpResponse.StatusCode) - fieldMap["{res_headers}"] = TransToString(httpResponse.Header) - debug("< %s %s", httpResponse.Proto, httpResponse.Status) - for key, value := range httpResponse.Header { - debug("< %s: %v", key, strings.Join(value, "")) - } - } - debug("<") - // receive error - if err != nil { - debug(" Error: %s.", err.Error()) - if !client.config.AutoRetry { - return - } else if retryTimes >= client.config.MaxRetryTime { - // timeout but reached the max retry times, return - times := strconv.Itoa(retryTimes + 1) - timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, times, times) - if strings.Contains(err.Error(), "Client.Timeout") { - timeoutErrorMsg += " Read timeout. Please set a valid ReadTimeout." - } else { - timeoutErrorMsg += " Connect timeout. Please set a valid ConnectTimeout." - } - err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err) - return - } - } - if isCertificateError(err) { - return - } - - // if status code >= 500 or timeout, will trigger retry - if client.config.AutoRetry && (err != nil || isServerError(httpResponse)) { - client.setTimeout(request) - // rewrite signatureNonce and signature - httpRequest, err = client.buildRequestWithSigner(request, signer) - // buildHttpRequest(request, finalSigner, regionId) - if err != nil { - return - } - continue - } - break - } - - err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat()) - fieldMap["{res_body}"] = response.GetHttpContentString() - debug("%s", response.GetHttpContentString()) - // wrap server errors - if serverErr, ok := err.(*errors.ServerError); ok { - var wrapInfo = map[string]string{} - serverErr.RespHeaders = response.GetHttpHeaders() - wrapInfo["StringToSign"] = request.GetStringToSign() - err = errors.WrapServerError(serverErr, wrapInfo) - } - return -} - -func isCertificateError(err error) bool { - if err != nil && strings.Contains(err.Error(), "x509: certificate signed by unknown authority") { - return true - } - return false -} - -func putMsgToMap(fieldMap map[string]string, request *http.Request) { - fieldMap["{host}"] = request.Host - fieldMap["{method}"] = request.Method - fieldMap["{uri}"] = request.URL.RequestURI() - fieldMap["{pid}"] = strconv.Itoa(os.Getpid()) - fieldMap["{version}"] = strings.Split(request.Proto, "/")[1] - hostname, _ := os.Hostname() - fieldMap["{hostname}"] = hostname - fieldMap["{req_headers}"] = TransToString(request.Header) - fieldMap["{target}"] = request.URL.Path + request.URL.RawQuery -} - -func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) { - err = auth.Sign(request, singer, regionId) - if err != nil { - return - } - requestMethod := request.GetMethod() - requestUrl := request.BuildUrl() - body := request.GetBodyReader() - httpRequest, err = http.NewRequest(requestMethod, requestUrl, body) - if err != nil { - return - } - for key, value := range request.GetHeaders() { - httpRequest.Header[key] = []string{value} - } - // host is a special case - if host, containsHost := request.GetHeaders()["Host"]; containsHost { - httpRequest.Host = host - } - return -} - -func isServerError(httpResponse *http.Response) bool { - return httpResponse.StatusCode >= http.StatusInternalServerError -} - -/** -only block when any one of the following occurs: -1. the asyncTaskQueue is full, increase the queue size to avoid this -2. Shutdown() in progressing, the client is being closed -**/ -func (client *Client) AddAsyncTask(task func()) (err error) { - if client.asyncTaskQueue != nil { - if client.isOpenAsync { - client.asyncTaskQueue <- task - } - } else { - err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil) - } - return -} - -func (client *Client) GetConfig() *Config { - return client.config -} - -func (client *Client) GetSigner() auth.Signer { - return client.signer -} - -func (client *Client) SetSigner(signer auth.Signer) { - client.signer = signer -} - -func NewClient() (client *Client, err error) { - client = &Client{} - err = client.Init() - return -} - -func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) { - client = &Client{} - var pc provider.Provider - if len(providers) == 0 { - pc = provider.DefaultChain - } else { - pc = provider.NewProviderChain(providers) - } - err = client.InitWithProviderChain(regionId, pc) - return -} - -func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) { - client = &Client{} - err = client.InitWithOptions(regionId, config, credential) - return -} - -func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) { - client = &Client{} - err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret) - return -} - -func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken) - return -} - -func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) - return -} - -func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy) - return -} - -func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithEcsRamRole(regionId, roleName) - return -} - -func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) { - client = &Client{} - err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration) - return -} - -func NewClientWithBearerToken(regionId, bearerToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithBearerToken(regionId, bearerToken) - return -} - -func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - request.TransToAcsRequest() - response = responses.NewCommonResponse() - err = client.DoAction(request, response) - return -} - -func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) { - if signer, isSigner := signerInterface.(auth.Signer); isSigner { - request.TransToAcsRequest() - response = responses.NewCommonResponse() - err = client.DoActionWithSigner(request, response, signer) - return - } - panic("should not be here") -} - -func (client *Client) Shutdown() { - if client.asyncTaskQueue != nil { - close(client.asyncTaskQueue) - } - - client.isOpenAsync = false -} - -// Deprecated: Use NewClientWithRamRoleArn in this package instead. -func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) -} - -// Deprecated: Use NewClientWithEcsRamRole in this package instead. -func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) { - return NewClientWithEcsRamRole(regionId, roleName) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go deleted file mode 100644 index 29b7cc35..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sdk - -import ( - "net/http" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -type Config struct { - AutoRetry bool `default:"false"` - MaxRetryTime int `default:"3"` - UserAgent string `default:""` - Debug bool `default:"false"` - HttpTransport *http.Transport `default:""` - Transport http.RoundTripper `default:""` - EnableAsync bool `default:"false"` - MaxTaskQueueSize int `default:"1000"` - GoRoutinePoolSize int `default:"5"` - Scheme string `default:"HTTP"` - Timeout time.Duration -} - -func NewConfig() (config *Config) { - config = &Config{} - utils.InitStructWithDefaultTag(config) - return -} - -func (c *Config) WithAutoRetry(isAutoRetry bool) *Config { - c.AutoRetry = isAutoRetry - return c -} - -func (c *Config) WithMaxRetryTime(maxRetryTime int) *Config { - c.MaxRetryTime = maxRetryTime - return c -} - -func (c *Config) WithUserAgent(userAgent string) *Config { - c.UserAgent = userAgent - return c -} - -func (c *Config) WithDebug(isDebug bool) *Config { - c.Debug = isDebug - return c -} - -func (c *Config) WithTimeout(timeout time.Duration) *Config { - c.Timeout = timeout - return c -} - -func (c *Config) WithHttpTransport(httpTransport *http.Transport) *Config { - c.HttpTransport = httpTransport - return c -} - -func (c *Config) WithEnableAsync(isEnableAsync bool) *Config { - c.EnableAsync = isEnableAsync - return c -} - -func (c *Config) WithMaxTaskQueueSize(maxTaskQueueSize int) *Config { - c.MaxTaskQueueSize = maxTaskQueueSize - return c -} - -func (c *Config) WithGoRoutinePoolSize(goRoutinePoolSize int) *Config { - c.GoRoutinePoolSize = goRoutinePoolSize - return c -} - -func (c *Config) WithScheme(scheme string) *Config { - c.Scheme = scheme - return c -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go deleted file mode 100644 index 8ee0ec53..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go +++ /dev/null @@ -1,4078 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "sync" -) - -const endpointsJson = `{ - "products": [ - { - "code": "emr", - "document_id": "28140", - "location_service_code": "emr", - "regional_endpoints": [ - { - "region": "cn-qingdao", - "endpoint": "emr.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "emr.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "emr.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "emr.eu-west-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "emr.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "emr.me-east-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "emr.ap-northeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "emr.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "emr.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "emr.ap-south-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "emr.us-east-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "emr.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "emr.cn-hongkong.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "emr.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "emr.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "emr.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "emr.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "emr.ap-southeast-5.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "emr.aliyuncs.com" - } - ], - "global_endpoint": "emr.aliyuncs.com", - "regional_endpoint_pattern": "emr.[RegionId].aliyuncs.com" - }, - { - "code": "petadata", - "document_id": "", - "location_service_code": "petadata", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "petadata.me-east-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "petadata.ap-southeast-2.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "petadata.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "petadata.ap-southeast-5.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "petadata.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "petadata.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "petadata.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "petadata.aliyuncs.com" - } - ], - "global_endpoint": "petadata.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "dbs", - "document_id": "", - "location_service_code": "dbs", - "regional_endpoints": [ - { - "region": "cn-shenzhen", - "endpoint": "dbs-api.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "dbs-api.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "dbs-api.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "dbs-api.ap-northeast-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "dbs-api.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "dbs-api.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "dbs-api.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "dbs-api.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "alidnsgtm", - "document_id": "", - "location_service_code": "alidnsgtm", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "alidns.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "alidns.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "elasticsearch", - "document_id": "", - "location_service_code": "elasticsearch", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "elasticsearch.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "elasticsearch.cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "elasticsearch.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "elasticsearch.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "elasticsearch.cn-hongkong.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "elasticsearch.ap-southeast-3.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "elasticsearch.us-west-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "elasticsearch.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "elasticsearch.ap-southeast-5.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "elasticsearch.eu-central-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "elasticsearch.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "elasticsearch.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "elasticsearch.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "elasticsearch.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "elasticsearch.ap-northeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "baas", - "document_id": "", - "location_service_code": "baas", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "baas.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "baas.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "baas.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "baas.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "baas.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "baas.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cr", - "document_id": "60716", - "location_service_code": "cr", - "regional_endpoints": null, - "global_endpoint": "cr.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "cloudap", - "document_id": "", - "location_service_code": "cloudap", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "cloudwf.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "imagesearch", - "document_id": "", - "location_service_code": "imagesearch", - "regional_endpoints": [ - { - "region": "ap-southeast-2", - "endpoint": "imagesearch.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "imagesearch.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "imagesearch.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "imagesearch.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "pts", - "document_id": "", - "location_service_code": "pts", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "pts.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ehs", - "document_id": "", - "location_service_code": "ehs", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "ehpc.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "ehpc.cn-hongkong.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "ehpc.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "ehpc.cn-qingdao.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "ehpc.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "ehpc.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "ehpc.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "ehpc.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ehpc.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "ehpc.cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "ehpc.ap-southeast-2.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "polardb", - "document_id": "58764", - "location_service_code": "polardb", - "regional_endpoints": [ - { - "region": "ap-south-1", - "endpoint": "polardb.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "polardb.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "polardb.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "polardb.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "polardb.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "polardb.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "polardb.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "polardb.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "polardb.ap-southeast-5.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "polardb.aliyuncs.com" - }, - { - "code": "r-kvstore", - "document_id": "60831", - "location_service_code": "redisa", - "regional_endpoints": [ - { - "region": "cn-shenzhen", - "endpoint": "r-kvstore.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "r-kvstore.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "r-kvstore.ap-southeast-3.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "r-kvstore.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "r-kvstore.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "r-kvstore.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "r-kvstore.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "r-kvstore.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "r-kvstore.cn-hongkong.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "r-kvstore.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "r-kvstore.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "r-kvstore.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "r-kvstore.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "r-kvstore.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "r-kvstore.eu-west-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "r-kvstore.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "r-kvstore.me-east-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "r-kvstore.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "r-kvstore.ap-southeast-5.aliyuncs.com" - } - ], - "global_endpoint": "r-kvstore.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "xianzhi", - "document_id": "", - "location_service_code": "xianzhi", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "xianzhi.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "pcdn", - "document_id": "", - "location_service_code": "pcdn", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "pcdn.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cdn", - "document_id": "27148", - "location_service_code": "cdn", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "cdn.aliyuncs.com" - } - ], - "global_endpoint": "cdn.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "cloudauth", - "document_id": "60687", - "location_service_code": "cloudauth", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "cloudauth.aliyuncs.com" - } - ], - "global_endpoint": "cloudauth.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "nas", - "document_id": "62598", - "location_service_code": "nas", - "regional_endpoints": [ - { - "region": "ap-southeast-2", - "endpoint": "nas.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "nas.ap-south-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "nas.eu-central-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "nas.us-west-1.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "nas.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "nas.cn-qingdao.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "nas.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "nas.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "nas.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "nas.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "nas.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "nas.ap-northeast-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "nas.us-east-1.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "nas.cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "nas.ap-southeast-5.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "nas.cn-hongkong.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "nas.ap-southeast-3.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "alidns", - "document_id": "29739", - "location_service_code": "alidns", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "alidns.aliyuncs.com" - } - ], - "global_endpoint": "alidns.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "dts", - "document_id": "", - "location_service_code": "dts", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "dts.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "dts.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "emas", - "document_id": "", - "location_service_code": "emas", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "mhub.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "mhub.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "dysmsapi", - "document_id": "", - "location_service_code": "dysmsapi", - "regional_endpoints": [ - { - "region": "ap-southeast-3", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "dysmsapi.aliyuncs.com" - }, - { - "region": "cn-chengdu", - "endpoint": "dysmsapi.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "dysmsapi.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "dysmsapi.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "dysmsapi.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "dysmsapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "dysmsapi.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "dysmsapi.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "dysmsapi.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cloudwf", - "document_id": "58111", - "location_service_code": "cloudwf", - "regional_endpoints": null, - "global_endpoint": "cloudwf.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "fc", - "document_id": "", - "location_service_code": "fc", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "cn-beijing.fc.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "ap-southeast-2.fc.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "cn-huhehaote.fc.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "cn-shanghai.fc.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "cn-hangzhou.fc.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "cn-shenzhen.fc.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "saf", - "document_id": "", - "location_service_code": "saf", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "saf.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "saf.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "saf.cn-shenzhen.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "rds", - "document_id": "26223", - "location_service_code": "rds", - "regional_endpoints": [ - { - "region": "ap-northeast-1", - "endpoint": "rds.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "rds.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "rds.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "rds.eu-west-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "rds.ap-southeast-3.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "rds.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "rds.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "rds.ap-southeast-5.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "rds.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "rds.me-east-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "rds.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "rds.aliyuncs.com" - } - ], - "global_endpoint": "rds.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "vpc", - "document_id": "34962", - "location_service_code": "vpc", - "regional_endpoints": [ - { - "region": "ap-south-1", - "endpoint": "vpc.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "vpc.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "vpc.ap-northeast-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "vpc.cn-huhehaote.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "vpc.me-east-1.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "vpc.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "vpc.ap-southeast-3.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "vpc.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "vpc.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "vpc.eu-west-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "vpc.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "vpc.aliyuncs.com" - } - ], - "global_endpoint": "vpc.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "gpdb", - "document_id": "", - "location_service_code": "gpdb", - "regional_endpoints": [ - { - "region": "ap-southeast-3", - "endpoint": "gpdb.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "gpdb.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "gpdb.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "gpdb.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "gpdb.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "gpdb.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "gpdb.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "gpdb.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "gpdb.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "gpdb.ap-southeast-2.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "gpdb.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "gpdb.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "gpdb.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "gpdb.ap-northeast-1.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "gpdb.eu-west-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "gpdb.ap-south-1.aliyuncs.com" - } - ], - "global_endpoint": "gpdb.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "yunmarket", - "document_id": "", - "location_service_code": "yunmarket", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "market.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "pvtz", - "document_id": "", - "location_service_code": "pvtz", - "regional_endpoints": [ - { - "region": "ap-southeast-1", - "endpoint": "pvtz.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "pvtz.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "oss", - "document_id": "", - "location_service_code": "oss", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "oss-cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "oss-cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "oss-cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "oss-cn-hongkong.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "oss-cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "oss-ap-southeast-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "oss-us-west-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "oss-cn-qingdao.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "foas", - "document_id": "", - "location_service_code": "foas", - "regional_endpoints": [ - { - "region": "cn-qingdao", - "endpoint": "foas.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "foas.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "foas.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "foas.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "foas.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "foas.cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "foas.ap-northeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ddos", - "document_id": "", - "location_service_code": "ddos", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ddospro.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "ddospro.cn-hongkong.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cbn", - "document_id": "", - "location_service_code": "cbn", - "regional_endpoints": [ - { - "region": "ap-southeast-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "cbn.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "cbn.aliyuncs.com" - } - ], - "global_endpoint": "cbn.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "nlp", - "document_id": "", - "location_service_code": "nlp", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "nlp.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "hsm", - "document_id": "", - "location_service_code": "hsm", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "hsm.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "hsm.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "hsm.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "hsm.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "hsm.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "hsm.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ons", - "document_id": "44416", - "location_service_code": "ons", - "regional_endpoints": [ - { - "region": "ap-southeast-1", - "endpoint": "ons.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "ons.cn-huhehaote.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "ons.us-east-1.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "ons.cn-hongkong.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "ons.cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "ons.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "ons.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "ons.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "ons.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "ons.me-east-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "ons.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "ons.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "ons.cn-hangzhou.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "ons.eu-central-1.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "ons.eu-west-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "ons.us-west-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "ons.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ons.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "kms", - "document_id": "", - "location_service_code": "kms", - "regional_endpoints": [ - { - "region": "cn-hongkong", - "endpoint": "kms.cn-hongkong.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "kms.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "kms.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "kms.cn-qingdao.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "kms.eu-west-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "kms.us-east-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "kms.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "kms.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "kms.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "kms.ap-southeast-5.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "kms.cn-huhehaote.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "kms.me-east-1.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "kms.cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "kms.ap-southeast-3.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "kms.us-west-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "kms.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "kms.ap-southeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "kms.eu-central-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "kms.ap-northeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cps", - "document_id": "", - "location_service_code": "cps", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "cloudpush.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ensdisk", - "document_id": "", - "location_service_code": "ensdisk", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ens.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cloudapi", - "document_id": "43590", - "location_service_code": "apigateway", - "regional_endpoints": [ - { - "region": "ap-southeast-2", - "endpoint": "apigateway.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "apigateway.ap-south-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "apigateway.us-east-1.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "apigateway.me-east-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "apigateway.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "apigateway.cn-beijing.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "apigateway.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "apigateway.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "apigateway.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "apigateway.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "apigateway.ap-southeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "apigateway.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "apigateway.cn-hangzhou.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "apigateway.us-west-1.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "apigateway.cn-shenzhen.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "apigateway.eu-west-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "apigateway.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "apigateway.ap-northeast-1.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "apigateway.cn-hongkong.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "apigateway.[RegionId].aliyuncs.com" - }, - { - "code": "eci", - "document_id": "", - "location_service_code": "eci", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "eci.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "eci.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "eci.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "eci.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "eci.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "eci.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "onsvip", - "document_id": "", - "location_service_code": "onsvip", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "ons.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "ons.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ons.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "ons.cn-shenzhen.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "ons.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "ons.cn-qingdao.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "linkwan", - "document_id": "", - "location_service_code": "linkwan", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "linkwan.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "linkwan.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ddosdip", - "document_id": "", - "location_service_code": "ddosdip", - "regional_endpoints": [ - { - "region": "ap-southeast-1", - "endpoint": "ddosdip.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "batchcompute", - "document_id": "44717", - "location_service_code": "batchcompute", - "regional_endpoints": [ - { - "region": "us-west-1", - "endpoint": "batchcompute.us-west-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "batchcompute.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "batchcompute.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "batchcompute.cn-shenzhen.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "batchcompute.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "batchcompute.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "batchcompute.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "batchcompute.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "batchcompute.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "batchcompute.[RegionId].aliyuncs.com" - }, - { - "code": "aegis", - "document_id": "28449", - "location_service_code": "vipaegis", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "aegis.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "aegis.ap-southeast-3.aliyuncs.com" - } - ], - "global_endpoint": "aegis.cn-hangzhou.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "arms", - "document_id": "42924", - "location_service_code": "arms", - "regional_endpoints": [ - { - "region": "cn-hongkong", - "endpoint": "arms.cn-hongkong.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "arms.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "arms.cn-shenzhen.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "arms.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "arms.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "arms.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "arms.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "arms.[RegionId].aliyuncs.com" - }, - { - "code": "live", - "document_id": "48207", - "location_service_code": "live", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "live.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "live.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "live.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "live.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "live.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "live.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "live.aliyuncs.com" - } - ], - "global_endpoint": "live.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "alimt", - "document_id": "", - "location_service_code": "alimt", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "mt.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "actiontrail", - "document_id": "", - "location_service_code": "actiontrail", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "actiontrail.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "actiontrail.cn-qingdao.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "actiontrail.us-east-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "actiontrail.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "actiontrail.ap-southeast-3.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "actiontrail.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "actiontrail.ap-south-1.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "actiontrail.me-east-1.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "actiontrail.cn-hongkong.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "actiontrail.cn-shenzhen.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "actiontrail.cn-hangzhou.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "actiontrail.eu-west-1.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "actiontrail.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "actiontrail.ap-northeast-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "actiontrail.us-west-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "actiontrail.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "actiontrail.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "actiontrail.cn-beijing.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "actiontrail.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "smartag", - "document_id": "", - "location_service_code": "smartag", - "regional_endpoints": [ - { - "region": "ap-southeast-3", - "endpoint": "smartag.ap-southeast-3.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "smartag.ap-southeast-5.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "smartag.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "smartag.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "smartag.cn-hongkong.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "smartag.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "smartag.ap-southeast-2.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "vod", - "document_id": "60574", - "location_service_code": "vod", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "vod.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "vod.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "vod.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "vod.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "vod.ap-southeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "vod.eu-central-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "domain", - "document_id": "42875", - "location_service_code": "domain", - "regional_endpoints": [ - { - "region": "ap-southeast-1", - "endpoint": "domain-intl.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "domain.aliyuncs.com" - } - ], - "global_endpoint": "domain.aliyuncs.com", - "regional_endpoint_pattern": "domain.aliyuncs.com" - }, - { - "code": "ros", - "document_id": "28899", - "location_service_code": "ros", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ros.aliyuncs.com" - } - ], - "global_endpoint": "ros.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "cloudphoto", - "document_id": "59902", - "location_service_code": "cloudphoto", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "cloudphoto.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "cloudphoto.[RegionId].aliyuncs.com" - }, - { - "code": "rtc", - "document_id": "", - "location_service_code": "rtc", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "rtc.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "odpsmayi", - "document_id": "", - "location_service_code": "odpsmayi", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "bsb.cloud.alipay.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "bsb.cloud.alipay.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ims", - "document_id": "", - "location_service_code": "ims", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ims.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "csb", - "document_id": "64837", - "location_service_code": "csb", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "csb.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "csb.cn-beijing.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "csb.[RegionId].aliyuncs.com" - }, - { - "code": "cds", - "document_id": "62887", - "location_service_code": "codepipeline", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "cds.cn-beijing.aliyuncs.com" - } - ], - "global_endpoint": "cds.cn-beijing.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "ddosbgp", - "document_id": "", - "location_service_code": "ddosbgp", - "regional_endpoints": [ - { - "region": "cn-huhehaote", - "endpoint": "ddosbgp.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "ddosbgp.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "ddosbgp.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "ddosbgp.cn-hongkong.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "ddosbgp.cn-hangzhou.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "ddosbgp.us-west-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "ddosbgp.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "ddosbgp.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ddosbgp.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "dybaseapi", - "document_id": "", - "location_service_code": "dybaseapi", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "cn-chengdu", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "dybaseapi.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "dybaseapi.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ecs", - "document_id": "25484", - "location_service_code": "ecs", - "regional_endpoints": [ - { - "region": "cn-huhehaote", - "endpoint": "ecs.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "ecs.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "ecs.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "ecs.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "ecs.ap-southeast-3.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "ecs.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "ecs.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "ecs.eu-west-1.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "ecs.me-east-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "ecs.ap-southeast-5.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "ecs-cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "ecs-cn-hangzhou.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "ccc", - "document_id": "63027", - "location_service_code": "ccc", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ccc.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ccc.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "ccc.[RegionId].aliyuncs.com" - }, - { - "code": "cs", - "document_id": "26043", - "location_service_code": "cs", - "regional_endpoints": null, - "global_endpoint": "cs.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "drdspre", - "document_id": "", - "location_service_code": "drdspre", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "drds.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "drds.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "drds.cn-shenzhen.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "drds.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "drds.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "drds.cn-qingdao.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "drds.cn-beijing.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "dcdn", - "document_id": "", - "location_service_code": "dcdn", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "dcdn.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "dcdn.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "linkedmall", - "document_id": "", - "location_service_code": "linkedmall", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "linkedmall.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "linkedmall.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "trademark", - "document_id": "", - "location_service_code": "trademark", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "trademark.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "openanalytics", - "document_id": "", - "location_service_code": "openanalytics", - "regional_endpoints": [ - { - "region": "cn-shenzhen", - "endpoint": "openanalytics.cn-shenzhen.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "openanalytics.eu-west-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "openanalytics.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "openanalytics.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "openanalytics.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "openanalytics.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "openanalytics.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "openanalytics.cn-zhangjiakou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "sts", - "document_id": "28756", - "location_service_code": "sts", - "regional_endpoints": null, - "global_endpoint": "sts.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "waf", - "document_id": "62847", - "location_service_code": "waf", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "wafopenapi.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ots", - "document_id": "", - "location_service_code": "ots", - "regional_endpoints": [ - { - "region": "me-east-1", - "endpoint": "ots.me-east-1.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "ots.ap-southeast-5.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "ots.eu-west-1.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "ots.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "ots.cn-beijing.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "ots.ap-southeast-2.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "ots.us-west-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "ots.us-east-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "ots.ap-south-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "ots.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "ots.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "ots.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "ots.ap-northeast-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ots.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "ots.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "ots.ap-southeast-3.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cloudfirewall", - "document_id": "", - "location_service_code": "cloudfirewall", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "cloudfw.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "dm", - "document_id": "29434", - "location_service_code": "dm", - "regional_endpoints": [ - { - "region": "ap-southeast-2", - "endpoint": "dm.ap-southeast-2.aliyuncs.com" - } - ], - "global_endpoint": "dm.aliyuncs.com", - "regional_endpoint_pattern": "dm.[RegionId].aliyuncs.com" - }, - { - "code": "oas", - "document_id": "", - "location_service_code": "oas", - "regional_endpoints": [ - { - "region": "cn-shenzhen", - "endpoint": "cn-shenzhen.oas.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "cn-beijing.oas.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "cn-hangzhou.oas.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ddoscoo", - "document_id": "", - "location_service_code": "ddoscoo", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ddoscoo.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "jaq", - "document_id": "35037", - "location_service_code": "jaq", - "regional_endpoints": null, - "global_endpoint": "jaq.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "iovcc", - "document_id": "", - "location_service_code": "iovcc", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "iovcc.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "sas-api", - "document_id": "28498", - "location_service_code": "sas", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "sas.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "chatbot", - "document_id": "60760", - "location_service_code": "beebot", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "chatbot.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "chatbot.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "chatbot.[RegionId].aliyuncs.com" - }, - { - "code": "airec", - "document_id": "", - "location_service_code": "airec", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "airec.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "airec.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "airec.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "dmsenterprise", - "document_id": "", - "location_service_code": "dmsenterprise", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "dms-enterprise.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "dms-enterprise.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "dms-enterprise.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "dms-enterprise.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "dms-enterprise.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "dms-enterprise.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ivision", - "document_id": "", - "location_service_code": "ivision", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ivision.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "ivision.cn-beijing.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "odpsplusmayi", - "document_id": "", - "location_service_code": "odpsplusmayi", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "bsb.cloud.alipay.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "bsb.cloud.alipay.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "bsb.cloud.alipay.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "gameshield", - "document_id": "", - "location_service_code": "gameshield", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "gameshield.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "gameshield.cn-zhangjiakou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "scdn", - "document_id": "", - "location_service_code": "scdn", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "scdn.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "hitsdb", - "document_id": "", - "location_service_code": "hitsdb", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "hitsdb.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "hdm", - "document_id": "", - "location_service_code": "hdm", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "hdm-api.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "slb", - "document_id": "27565", - "location_service_code": "slb", - "regional_endpoints": [ - { - "region": "cn-shenzhen", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "slb.eu-west-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "slb.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "slb.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "slb.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "slb.ap-south-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "slb.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "slb.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "slb.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "slb.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "slb.me-east-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "slb.cn-zhangjiakou.aliyuncs.com" - } - ], - "global_endpoint": "slb.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "green", - "document_id": "28427", - "location_service_code": "green", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "green.cn-beijing.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "green.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "green.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "green.cn-hangzhou.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "green.us-west-1.aliyuncs.com" - } - ], - "global_endpoint": "green.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "cccvn", - "document_id": "", - "location_service_code": "cccvn", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "voicenavigator.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ddosrewards", - "document_id": "", - "location_service_code": "ddosrewards", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ddosright.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "iot", - "document_id": "30557", - "location_service_code": "iot", - "regional_endpoints": [ - { - "region": "us-east-1", - "endpoint": "iot.us-east-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "iot.ap-northeast-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "iot.us-west-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "iot.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "iot.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "iot.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "iot.[RegionId].aliyuncs.com" - }, - { - "code": "bssopenapi", - "document_id": "", - "location_service_code": "bssopenapi", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "business.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "business.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "sca", - "document_id": "", - "location_service_code": "sca", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "qualitycheck.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "luban", - "document_id": "", - "location_service_code": "luban", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "luban.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "luban.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "drdspost", - "document_id": "", - "location_service_code": "drdspost", - "regional_endpoints": [ - { - "region": "cn-shanghai", - "endpoint": "drds.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "drds.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "drds.ap-southeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "drds", - "document_id": "51111", - "location_service_code": "drds", - "regional_endpoints": [ - { - "region": "ap-southeast-1", - "endpoint": "drds.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "drds.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "drds.aliyuncs.com", - "regional_endpoint_pattern": "drds.aliyuncs.com" - }, - { - "code": "httpdns", - "document_id": "52679", - "location_service_code": "httpdns", - "regional_endpoints": null, - "global_endpoint": "httpdns-api.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "cas", - "document_id": "", - "location_service_code": "cas", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "cas.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "cas.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "cas.ap-northeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "cas.eu-central-1.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "cas.me-east-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "hpc", - "document_id": "35201", - "location_service_code": "hpc", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "hpc.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "hpc.aliyuncs.com" - } - ], - "global_endpoint": "hpc.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "ddosbasic", - "document_id": "", - "location_service_code": "ddosbasic", - "regional_endpoints": [ - { - "region": "ap-south-1", - "endpoint": "antiddos-openapi.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "antiddos-openapi.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "antiddos-openapi.ap-southeast-3.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "antiddos-openapi.me-east-1.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "antiddos-openapi.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "antiddos-openapi.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "antiddos-openapi.eu-west-1.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "antiddos-openapi.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "antiddos-openapi.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "antiddos.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "antiddos-openapi.ap-northeast-1.aliyuncs.com" - } - ], - "global_endpoint": "antiddos.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "clouddesktop", - "document_id": "", - "location_service_code": "clouddesktop", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "clouddesktop.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "clouddesktop.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "clouddesktop.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "clouddesktop.cn-shenzhen.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "uis", - "document_id": "", - "location_service_code": "uis", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "uis.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "imm", - "document_id": "", - "location_service_code": "imm", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "imm.cn-beijing.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "imm.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "imm.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "imm.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "imm.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "imm.cn-shenzhen.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ens", - "document_id": "", - "location_service_code": "ens", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ens.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ram", - "document_id": "28672", - "location_service_code": "ram", - "regional_endpoints": null, - "global_endpoint": "ram.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "hcs_mgw", - "document_id": "", - "location_service_code": "hcs_mgw", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "mgw.cn-hangzhou.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "mgw.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "mgw.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "itaas", - "document_id": "55759", - "location_service_code": "itaas", - "regional_endpoints": null, - "global_endpoint": "itaas.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "qualitycheck", - "document_id": "50807", - "location_service_code": "qualitycheck", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "qualitycheck.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "alikafka", - "document_id": "", - "location_service_code": "alikafka", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "alikafka.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "alikafka.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "alikafka.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "alikafka.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "alikafka.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "alikafka.cn-shenzhen.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "alikafka.cn-hongkong.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "alikafka.cn-qingdao.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "faas", - "document_id": "", - "location_service_code": "faas", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "faas.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "faas.cn-shenzhen.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "faas.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "faas.cn-beijing.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "alidfs", - "document_id": "", - "location_service_code": "alidfs", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "dfs.cn-beijing.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "dfs.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "cms", - "document_id": "28615", - "location_service_code": "cms", - "regional_endpoints": [ - { - "region": "ap-southeast-3", - "endpoint": "metrics.ap-southeast-3.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "metrics.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "metrics.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "metrics.cn-hangzhou.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "metrics.eu-west-1.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "metrics.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "metrics.ap-northeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "domain-intl", - "document_id": "", - "location_service_code": "domain-intl", - "regional_endpoints": null, - "global_endpoint": "domain-intl.aliyuncs.com", - "regional_endpoint_pattern": "domain-intl.aliyuncs.com" - }, - { - "code": "kvstore", - "document_id": "", - "location_service_code": "kvstore", - "regional_endpoints": [ - { - "region": "ap-northeast-1", - "endpoint": "r-kvstore.ap-northeast-1.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ccs", - "document_id": "", - "location_service_code": "ccs", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "ccs.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "ess", - "document_id": "25925", - "location_service_code": "ess", - "regional_endpoints": [ - { - "region": "cn-huhehaote", - "endpoint": "ess.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "ess.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "ess.eu-west-1.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "ess.ap-southeast-5.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "ess.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "ess.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "ess.me-east-1.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "ess.ap-northeast-1.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "ess.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "ess.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "ess.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "ess.aliyuncs.com" - } - ], - "global_endpoint": "ess.aliyuncs.com", - "regional_endpoint_pattern": "ess.[RegionId].aliyuncs.com" - }, - { - "code": "dds", - "document_id": "61715", - "location_service_code": "dds", - "regional_endpoints": [ - { - "region": "me-east-1", - "endpoint": "mongodb.me-east-1.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "mongodb.ap-southeast-3.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "mongodb.ap-southeast-5.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "mongodb.ap-northeast-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "mongodb.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "mongodb.eu-west-1.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "cn-huhehaote", - "endpoint": "mongodb.cn-huhehaote.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "mongodb.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "mongodb.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "mongodb.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "mongodb.ap-south-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "mongodb.aliyuncs.com" - } - ], - "global_endpoint": "mongodb.aliyuncs.com", - "regional_endpoint_pattern": "mongodb.[RegionId].aliyuncs.com" - }, - { - "code": "mts", - "document_id": "29212", - "location_service_code": "mts", - "regional_endpoints": [ - { - "region": "cn-beijing", - "endpoint": "mts.cn-beijing.aliyuncs.com" - }, - { - "region": "ap-northeast-1", - "endpoint": "mts.ap-northeast-1.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "mts.cn-hongkong.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "mts.cn-shenzhen.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "mts.cn-zhangjiakou.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "mts.ap-south-1.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "mts.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "mts.ap-southeast-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "mts.us-west-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "mts.eu-central-1.aliyuncs.com" - }, - { - "region": "eu-west-1", - "endpoint": "mts.eu-west-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "mts.cn-hangzhou.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "push", - "document_id": "30074", - "location_service_code": "push", - "regional_endpoints": null, - "global_endpoint": "cloudpush.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "hcs_sgw", - "document_id": "", - "location_service_code": "hcs_sgw", - "regional_endpoints": [ - { - "region": "eu-central-1", - "endpoint": "sgw.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "sgw.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-zhangjiakou", - "endpoint": "sgw.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "sgw.ap-southeast-1.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "sgw.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-hongkong", - "endpoint": "sgw.cn-shanghai.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "sgw.ap-southeast-2.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "sgw.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "sgw.cn-shanghai.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "sgw.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "hbase", - "document_id": "", - "location_service_code": "hbase", - "regional_endpoints": [ - { - "region": "cn-huhehaote", - "endpoint": "hbase.cn-huhehaote.aliyuncs.com" - }, - { - "region": "ap-south-1", - "endpoint": "hbase.ap-south-1.aliyuncs.com" - }, - { - "region": "us-west-1", - "endpoint": "hbase.aliyuncs.com" - }, - { - "region": "me-east-1", - "endpoint": "hbase.me-east-1.aliyuncs.com" - }, - { - "region": "eu-central-1", - "endpoint": "hbase.eu-central-1.aliyuncs.com" - }, - { - "region": "cn-qingdao", - "endpoint": "hbase.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "hbase.aliyuncs.com" - }, - { - "region": "cn-shenzhen", - "endpoint": "hbase.aliyuncs.com" - }, - { - "region": "ap-southeast-2", - "endpoint": "hbase.ap-southeast-2.aliyuncs.com" - }, - { - "region": "ap-southeast-3", - "endpoint": "hbase.ap-southeast-3.aliyuncs.com" - }, - { - "region": "cn-hangzhou", - "endpoint": "hbase.aliyuncs.com" - }, - { - "region": "us-east-1", - "endpoint": "hbase.aliyuncs.com" - }, - { - "region": "ap-southeast-5", - "endpoint": "hbase.ap-southeast-5.aliyuncs.com" - }, - { - "region": "cn-beijing", - "endpoint": "hbase.aliyuncs.com" - }, - { - "region": "ap-southeast-1", - "endpoint": "hbase.aliyuncs.com" - } - ], - "global_endpoint": "hbase.aliyuncs.com", - "regional_endpoint_pattern": "" - }, - { - "code": "bastionhost", - "document_id": "", - "location_service_code": "bastionhost", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "yundun-bastionhost.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - }, - { - "code": "vs", - "document_id": "", - "location_service_code": "vs", - "regional_endpoints": [ - { - "region": "cn-hangzhou", - "endpoint": "vs.cn-hangzhou.aliyuncs.com" - }, - { - "region": "cn-shanghai", - "endpoint": "vs.cn-shanghai.aliyuncs.com" - } - ], - "global_endpoint": "", - "regional_endpoint_pattern": "" - } - ] -}` - -var initOnce sync.Once -var data interface{} - -func getEndpointConfigData() interface{} { - initOnce.Do(func() { - err := json.Unmarshal([]byte(endpointsJson), &data) - if err != nil { - panic(fmt.Sprintf("init endpoint config data failed. %s", err)) - } - }) - return data -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go deleted file mode 100644 index 160e62cb..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "fmt" - "strings" - - "github.com/jmespath/go-jmespath" -) - -type LocalGlobalResolver struct { -} - -func (resolver *LocalGlobalResolver) GetName() (name string) { - name = "local global resolver" - return -} - -func (resolver *LocalGlobalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - // get the global endpoints configs - endpointExpression := fmt.Sprintf("products[?code=='%s'].global_endpoint", strings.ToLower(param.Product)) - endpointData, err := jmespath.Search(endpointExpression, getEndpointConfigData()) - if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 { - endpoint = endpointData.([]interface{})[0].(string) - support = len(endpoint) > 0 - return - } - support = false - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go deleted file mode 100644 index 7fee64d4..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "fmt" - "strings" - - "github.com/jmespath/go-jmespath" -) - -type LocalRegionalResolver struct { -} - -func (resolver *LocalRegionalResolver) GetName() (name string) { - name = "local regional resolver" - return -} - -func (resolver *LocalRegionalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - // get the regional endpoints configs - regionalExpression := fmt.Sprintf("products[?code=='%s'].regional_endpoints", strings.ToLower(param.Product)) - regionalData, err := jmespath.Search(regionalExpression, getEndpointConfigData()) - if err == nil && regionalData != nil && len(regionalData.([]interface{})) > 0 { - endpointExpression := fmt.Sprintf("[0][?region=='%s'].endpoint", strings.ToLower(param.RegionId)) - var endpointData interface{} - endpointData, err = jmespath.Search(endpointExpression, regionalData) - if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 { - endpoint = endpointData.([]interface{})[0].(string) - support = len(endpoint) > 0 - return - } - } - support = false - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go deleted file mode 100644 index cc354cc4..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package endpoints - -import ( - "encoding/json" - "sync" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" -) - -const ( - // EndpointCacheExpireTime ... - EndpointCacheExpireTime = 3600 //Seconds -) - -// Cache caches endpoint for specific product and region -type Cache struct { - sync.RWMutex - cache map[string]interface{} -} - -// Get ... -func (c *Cache) Get(k string) (v interface{}) { - c.RLock() - v = c.cache[k] - c.RUnlock() - return -} - -// Set ... -func (c *Cache) Set(k string, v interface{}) { - c.Lock() - c.cache[k] = v - c.Unlock() -} - -var lastClearTimePerProduct = &Cache{cache: make(map[string]interface{})} -var endpointCache = &Cache{cache: make(map[string]interface{})} - -// LocationResolver ... -type LocationResolver struct { -} - -func (resolver *LocationResolver) GetName() (name string) { - name = "location resolver" - return -} - -// TryResolve resolves endpoint giving product and region -func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - if len(param.LocationProduct) <= 0 { - support = false - return - } - - //get from cache - cacheKey := param.Product + "#" + param.RegionId - var ok bool - endpoint, ok = endpointCache.Get(cacheKey).(string) - - if ok && len(endpoint) > 0 && !CheckCacheIsExpire(cacheKey) { - support = true - return - } - - //get from remote - getEndpointRequest := requests.NewCommonRequest() - - getEndpointRequest.Product = "Location" - getEndpointRequest.Version = "2015-06-12" - getEndpointRequest.ApiName = "DescribeEndpoints" - getEndpointRequest.Domain = "location-readonly.aliyuncs.com" - getEndpointRequest.Method = "GET" - getEndpointRequest.Scheme = requests.HTTPS - - getEndpointRequest.QueryParams["Id"] = param.RegionId - getEndpointRequest.QueryParams["ServiceCode"] = param.LocationProduct - if len(param.LocationEndpointType) > 0 { - getEndpointRequest.QueryParams["Type"] = param.LocationEndpointType - } else { - getEndpointRequest.QueryParams["Type"] = "openAPI" - } - - response, err := param.CommonApi(getEndpointRequest) - if err != nil { - support = false - return - } - - if !response.IsSuccess() { - support = false - return - } - - var getEndpointResponse GetEndpointResponse - err = json.Unmarshal([]byte(response.GetHttpContentString()), &getEndpointResponse) - if err != nil { - support = false - return - } - - if !getEndpointResponse.Success || getEndpointResponse.Endpoints == nil { - support = false - return - } - if len(getEndpointResponse.Endpoints.Endpoint) <= 0 { - support = false - return - } - if len(getEndpointResponse.Endpoints.Endpoint[0].Endpoint) > 0 { - endpoint = getEndpointResponse.Endpoints.Endpoint[0].Endpoint - endpointCache.Set(cacheKey, endpoint) - lastClearTimePerProduct.Set(cacheKey, time.Now().Unix()) - support = true - return - } - - support = false - return -} - -// CheckCacheIsExpire ... -func CheckCacheIsExpire(cacheKey string) bool { - lastClearTime, ok := lastClearTimePerProduct.Get(cacheKey).(int64) - if !ok { - return true - } - - if lastClearTime <= 0 { - lastClearTime = time.Now().Unix() - lastClearTimePerProduct.Set(cacheKey, lastClearTime) - } - - now := time.Now().Unix() - elapsedTime := now - lastClearTime - if elapsedTime > EndpointCacheExpireTime { - return true - } - - return false -} - -// GetEndpointResponse ... -type GetEndpointResponse struct { - Endpoints *EndpointsObj - RequestId string - Success bool -} - -// EndpointsObj ... -type EndpointsObj struct { - Endpoint []EndpointObj -} - -// EndpointObj ... -type EndpointObj struct { - // Protocols map[string]string - Type string - Namespace string - Id string - SerivceCode string - Endpoint string -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go deleted file mode 100644 index a415a169..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "fmt" - "strings" - "sync" -) - -const keyFormatter = "%s::%s" - -type EndpointMapping struct { - sync.RWMutex - endpoint map[string]string -} - -var endpointMapping = EndpointMapping{endpoint: make(map[string]string)} - -// AddEndpointMapping use productId and regionId as key to store the endpoint into inner map -// when using the same productId and regionId as key, the endpoint will be covered. -func AddEndpointMapping(regionId, productId, endpoint string) (err error) { - key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId)) - endpointMapping.Lock() - endpointMapping.endpoint[key] = endpoint - endpointMapping.Unlock() - return nil -} - -// GetEndpointFromMap use Product and RegionId as key to find endpoint from inner map -func GetEndpointFromMap(regionId, productId string) string { - key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId)) - endpointMapping.RLock() - endpoint := endpointMapping.endpoint[key] - endpointMapping.RUnlock() - return endpoint -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go deleted file mode 100644 index a73b8b13..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "encoding/json" - "fmt" - "sync" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -var debug utils.Debug - -func init() { - debug = utils.Init("sdk") -} - -const ( - ResolveEndpointUserGuideLink = "" -) - -var once sync.Once -var resolvers []Resolver - -type Resolver interface { - TryResolve(param *ResolveParam) (endpoint string, support bool, err error) - GetName() (name string) -} - -// Resolve resolve endpoint with params -// It will resolve with each supported resolver until anyone resolved -func Resolve(param *ResolveParam) (endpoint string, err error) { - supportedResolvers := getAllResolvers() - var lastErr error - for _, resolver := range supportedResolvers { - endpoint, supported, resolveErr := resolver.TryResolve(param) - if resolveErr != nil { - lastErr = resolveErr - } - - if supported { - debug("resolve endpoint with %s\n", param) - debug("\t%s by resolver(%s)\n", endpoint, resolver.GetName()) - return endpoint, nil - } - } - - // not support - errorMsg := fmt.Sprintf(errors.CanNotResolveEndpointErrorMessage, param, ResolveEndpointUserGuideLink) - err = errors.NewClientError(errors.CanNotResolveEndpointErrorCode, errorMsg, lastErr) - return -} - -func getAllResolvers() []Resolver { - once.Do(func() { - resolvers = []Resolver{ - &LocationResolver{}, - &LocalRegionalResolver{}, - &LocalGlobalResolver{}, - } - }) - return resolvers -} - -type ResolveParam struct { - Domain string - Product string - RegionId string - LocationProduct string - LocationEndpointType string - CommonApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) `json:"-"` -} - -func (param *ResolveParam) String() string { - jsonBytes, err := json.Marshal(param) - if err != nil { - return fmt.Sprint("ResolveParam.String() process error:", err) - } - return string(jsonBytes) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go deleted file mode 100644 index 1e2d9c00..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package errors - -import "fmt" - -const ( - DefaultClientErrorStatus = 400 - DefaultClientErrorCode = "SDK.ClientError" - - UnsupportedCredentialErrorCode = "SDK.UnsupportedCredential" - UnsupportedCredentialErrorMessage = "Specified credential (type = %s) is not supported, please check" - - CanNotResolveEndpointErrorCode = "SDK.CanNotResolveEndpoint" - CanNotResolveEndpointErrorMessage = "Can not resolve endpoint(param = %s), please check your accessKey with secret, and read the user guide\n %s" - - UnsupportedParamPositionErrorCode = "SDK.UnsupportedParamPosition" - UnsupportedParamPositionErrorMessage = "Specified param position (%s) is not supported, please upgrade sdk and retry" - - AsyncFunctionNotEnabledCode = "SDK.AsyncFunctionNotEnabled" - AsyncFunctionNotEnabledMessage = "Async function is not enabled in client, please invoke 'client.EnableAsync' function" - - UnknownRequestTypeErrorCode = "SDK.UnknownRequestType" - UnknownRequestTypeErrorMessage = "Unknown Request Type: %s" - - MissingParamErrorCode = "SDK.MissingParam" - InvalidParamErrorCode = "SDK.InvalidParam" - - JsonUnmarshalErrorCode = "SDK.JsonUnmarshalError" - JsonUnmarshalErrorMessage = "Failed to unmarshal response, but you can get the data via response.GetHttpStatusCode() and response.GetHttpContentString()" - - TimeoutErrorCode = "SDK.TimeoutError" - TimeoutErrorMessage = "The request timed out %s times(%s for retry), perhaps we should have the threshold raised a little?" -) - -type ClientError struct { - errorCode string - message string - originError error -} - -func NewClientError(errorCode, message string, originErr error) Error { - return &ClientError{ - errorCode: errorCode, - message: message, - originError: originErr, - } -} - -func (err *ClientError) Error() string { - clientErrMsg := fmt.Sprintf("[%s] %s", err.ErrorCode(), err.message) - if err.originError != nil { - return clientErrMsg + "\ncaused by:\n" + err.originError.Error() - } - return clientErrMsg -} - -func (err *ClientError) OriginError() error { - return err.originError -} - -func (*ClientError) HttpStatus() int { - return DefaultClientErrorStatus -} - -func (err *ClientError) ErrorCode() string { - if err.errorCode == "" { - return DefaultClientErrorCode - } else { - return err.errorCode - } -} - -func (err *ClientError) Message() string { - return err.message -} - -func (err *ClientError) String() string { - return err.Error() -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go deleted file mode 100644 index 49962f3b..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package errors - -type Error interface { - error - HttpStatus() int - ErrorCode() string - Message() string - OriginError() error -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go deleted file mode 100644 index f9102a04..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package errors - -import ( - "encoding/json" - "fmt" - - "github.com/jmespath/go-jmespath" -) - -var wrapperList = []ServerErrorWrapper{ - &SignatureDostNotMatchWrapper{}, -} - -type ServerError struct { - RespHeaders map[string][]string - httpStatus int - requestId string - hostId string - errorCode string - recommend string - message string - comment string -} - -type ServerErrorWrapper interface { - tryWrap(error *ServerError, wrapInfo map[string]string) bool -} - -func (err *ServerError) Error() string { - return fmt.Sprintf("SDK.ServerError\nErrorCode: %s\nRecommend: %s\nRequestId: %s\nMessage: %s\nRespHeaders: %s", - err.errorCode, err.comment+err.recommend, err.requestId, err.message, err.RespHeaders) -} - -func NewServerError(httpStatus int, responseContent, comment string) Error { - result := &ServerError{ - httpStatus: httpStatus, - message: responseContent, - comment: comment, - } - - var data interface{} - err := json.Unmarshal([]byte(responseContent), &data) - if err == nil { - requestId, _ := jmespath.Search("RequestId", data) - hostId, _ := jmespath.Search("HostId", data) - errorCode, _ := jmespath.Search("Code", data) - recommend, _ := jmespath.Search("Recommend", data) - message, _ := jmespath.Search("Message", data) - - if requestId != nil { - result.requestId = requestId.(string) - } - if hostId != nil { - result.hostId = hostId.(string) - } - if errorCode != nil { - result.errorCode = errorCode.(string) - } - if recommend != nil { - result.recommend = recommend.(string) - } - if message != nil { - result.message = message.(string) - } - } - - return result -} - -func WrapServerError(originError *ServerError, wrapInfo map[string]string) *ServerError { - for _, wrapper := range wrapperList { - ok := wrapper.tryWrap(originError, wrapInfo) - if ok { - return originError - } - } - return originError -} - -func (err *ServerError) HttpStatus() int { - return err.httpStatus -} - -func (err *ServerError) ErrorCode() string { - return err.errorCode -} - -func (err *ServerError) Message() string { - return err.message -} - -func (err *ServerError) OriginError() error { - return nil -} - -func (err *ServerError) HostId() string { - return err.hostId -} - -func (err *ServerError) RequestId() string { - return err.requestId -} - -func (err *ServerError) Recommend() string { - return err.recommend -} - -func (err *ServerError) Comment() string { - return err.comment -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go deleted file mode 100644 index 4b09d7d7..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go +++ /dev/null @@ -1,45 +0,0 @@ -package errors - -import ( - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -const SignatureDostNotMatchErrorCode = "SignatureDoesNotMatch" -const IncompleteSignatureErrorCode = "IncompleteSignature" -const MessageContain = "server string to sign is:" - -var debug utils.Debug - -func init() { - debug = utils.Init("sdk") -} - -type SignatureDostNotMatchWrapper struct { -} - -func (*SignatureDostNotMatchWrapper) tryWrap(error *ServerError, wrapInfo map[string]string) (ok bool) { - clientStringToSign := wrapInfo["StringToSign"] - if (error.errorCode == SignatureDostNotMatchErrorCode || error.errorCode == IncompleteSignatureErrorCode) && clientStringToSign != "" { - message := error.message - if strings.Contains(message, MessageContain) { - str := strings.Split(message, MessageContain) - serverStringToSign := str[1] - - if clientStringToSign == serverStringToSign { - // user secret is error - error.recommend = "InvalidAccessKeySecret: Please check you AccessKeySecret" - } else { - debug("Client StringToSign: %s", clientStringToSign) - debug("Server StringToSign: %s", serverStringToSign) - error.recommend = "This may be a bug with the SDK and we hope you can submit this question in the " + - "github issue(https://github.com/aliyun/alibaba-cloud-sdk-go/issues), thanks very much" - } - } - ok = true - return - } - ok = false - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/logger.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/logger.go deleted file mode 100644 index 49e49833..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/logger.go +++ /dev/null @@ -1,117 +0,0 @@ -package sdk - -import ( - "encoding/json" - "io" - "log" - "os" - "strings" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -var logChannel string -var defaultChannel = "AlibabaCloud" - -type Logger struct { - *log.Logger - formatTemplate string - isOpen bool - lastLogMsg string -} - -var defaultLoggerTemplate = `{time} {channel}: "{method} {uri} HTTP/{version}" {code} {cost} {hostname}` -var loggerParam = []string{"{time}", "{start_time}", "{ts}", "{channel}", "{pid}", "{host}", "{method}", "{uri}", "{version}", "{target}", "{hostname}", "{code}", "{error}", "{req_headers}", "{res_body}", "{res_headers}", "{cost}"} - -func initLogMsg(fieldMap map[string]string) { - for _, value := range loggerParam { - fieldMap[value] = "" - } -} - -func (client *Client) GetLogger() *Logger { - return client.logger -} - -func (client *Client) GetLoggerMsg() string { - if client.logger == nil { - client.SetLogger("", "", os.Stdout, "") - } - return client.logger.lastLogMsg -} - -func (client *Client) SetLogger(level string, channel string, out io.Writer, template string) { - if level == "" { - level = "info" - } - - logChannel = "AlibabaCloud" - if channel != "" { - logChannel = channel - } - log := log.New(out, "["+strings.ToUpper(level)+"]", log.Lshortfile) - if template == "" { - template = defaultLoggerTemplate - } - - client.logger = &Logger{ - Logger: log, - formatTemplate: template, - isOpen: true, - } -} - -func (client *Client) OpenLogger() { - if client.logger == nil { - client.SetLogger("", "", os.Stdout, "") - } - client.logger.isOpen = true -} - -func (client *Client) CloseLogger() { - if client.logger != nil { - client.logger.isOpen = false - } -} - -func (client *Client) SetTemplate(template string) { - if client.logger == nil { - client.SetLogger("", "", os.Stdout, "") - } - client.logger.formatTemplate = template -} - -func (client *Client) GetTemplate() string { - if client.logger == nil { - client.SetLogger("", "", os.Stdout, "") - } - return client.logger.formatTemplate -} - -func TransToString(object interface{}) string { - byt, err := json.Marshal(object) - if err != nil { - return "" - } - return string(byt) -} - -func (client *Client) printLog(fieldMap map[string]string, err error) { - if err != nil { - fieldMap["{error}"] = err.Error() - } - fieldMap["{time}"] = time.Now().Format("2006-01-02 15:04:05") - fieldMap["{ts}"] = utils.GetTimeInFormatISO8601() - fieldMap["{channel}"] = logChannel - if client.logger != nil { - logMsg := client.logger.formatTemplate - for key, value := range fieldMap { - logMsg = strings.Replace(logMsg, key, value, -1) - } - client.logger.lastLogMsg = logMsg - if client.logger.isOpen == true { - client.logger.Output(2, logMsg) - } - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_request.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_request.go deleted file mode 100644 index d055c754..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_request.go +++ /dev/null @@ -1,525 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package requests - -import ( - "encoding/json" - "fmt" - "io" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" -) - -const ( - RPC = "RPC" - ROA = "ROA" - - HTTP = "HTTP" - HTTPS = "HTTPS" - - DefaultHttpPort = "80" - - GET = "GET" - PUT = "PUT" - POST = "POST" - DELETE = "DELETE" - PATCH = "PATCH" - HEAD = "HEAD" - OPTIONS = "OPTIONS" - - Json = "application/json" - Xml = "application/xml" - Raw = "application/octet-stream" - Form = "application/x-www-form-urlencoded" - - Header = "Header" - Query = "Query" - Body = "Body" - Path = "Path" - - HeaderSeparator = "\n" -) - -// interface -type AcsRequest interface { - GetScheme() string - GetMethod() string - GetDomain() string - GetPort() string - GetRegionId() string - GetHeaders() map[string]string - GetQueryParams() map[string]string - GetFormParams() map[string]string - GetContent() []byte - GetBodyReader() io.Reader - GetStyle() string - GetProduct() string - GetVersion() string - SetVersion(version string) - GetActionName() string - GetAcceptFormat() string - GetLocationServiceCode() string - GetLocationEndpointType() string - GetReadTimeout() time.Duration - GetConnectTimeout() time.Duration - SetReadTimeout(readTimeout time.Duration) - SetConnectTimeout(connectTimeout time.Duration) - SetHTTPSInsecure(isInsecure bool) - GetHTTPSInsecure() *bool - - GetUserAgent() map[string]string - - SetStringToSign(stringToSign string) - GetStringToSign() string - - SetDomain(domain string) - SetContent(content []byte) - SetScheme(scheme string) - BuildUrl() string - BuildQueries() string - - addHeaderParam(key, value string) - addQueryParam(key, value string) - addFormParam(key, value string) - addPathParam(key, value string) -} - -// base class -type baseRequest struct { - Scheme string - Method string - Domain string - Port string - RegionId string - ReadTimeout time.Duration - ConnectTimeout time.Duration - isInsecure *bool - - userAgent map[string]string - product string - version string - - actionName string - - AcceptFormat string - - QueryParams map[string]string - Headers map[string]string - FormParams map[string]string - Content []byte - - locationServiceCode string - locationEndpointType string - - queries string - - stringToSign string -} - -func (request *baseRequest) GetQueryParams() map[string]string { - return request.QueryParams -} - -func (request *baseRequest) GetFormParams() map[string]string { - return request.FormParams -} - -func (request *baseRequest) GetReadTimeout() time.Duration { - return request.ReadTimeout -} - -func (request *baseRequest) GetConnectTimeout() time.Duration { - return request.ConnectTimeout -} - -func (request *baseRequest) SetReadTimeout(readTimeout time.Duration) { - request.ReadTimeout = readTimeout -} - -func (request *baseRequest) SetConnectTimeout(connectTimeout time.Duration) { - request.ConnectTimeout = connectTimeout -} - -func (request *baseRequest) GetHTTPSInsecure() *bool { - return request.isInsecure -} - -func (request *baseRequest) SetHTTPSInsecure(isInsecure bool) { - request.isInsecure = &isInsecure -} - -func (request *baseRequest) GetContent() []byte { - return request.Content -} - -func (request *baseRequest) SetVersion(version string) { - request.version = version -} - -func (request *baseRequest) GetVersion() string { - return request.version -} - -func (request *baseRequest) GetActionName() string { - return request.actionName -} - -func (request *baseRequest) SetContent(content []byte) { - request.Content = content -} - -func (request *baseRequest) GetUserAgent() map[string]string { - return request.userAgent -} - -func (request *baseRequest) AppendUserAgent(key, value string) { - newkey := true - if request.userAgent == nil { - request.userAgent = make(map[string]string) - } - if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" { - for tag, _ := range request.userAgent { - if tag == key { - request.userAgent[tag] = value - newkey = false - } - } - if newkey { - request.userAgent[key] = value - } - } -} - -func (request *baseRequest) addHeaderParam(key, value string) { - request.Headers[key] = value -} - -func (request *baseRequest) addQueryParam(key, value string) { - request.QueryParams[key] = value -} - -func (request *baseRequest) addFormParam(key, value string) { - request.FormParams[key] = value -} - -func (request *baseRequest) GetAcceptFormat() string { - return request.AcceptFormat -} - -func (request *baseRequest) GetLocationServiceCode() string { - return request.locationServiceCode -} - -func (request *baseRequest) GetLocationEndpointType() string { - return request.locationEndpointType -} - -func (request *baseRequest) GetProduct() string { - return request.product -} - -func (request *baseRequest) GetScheme() string { - return request.Scheme -} - -func (request *baseRequest) SetScheme(scheme string) { - request.Scheme = scheme -} - -func (request *baseRequest) GetMethod() string { - return request.Method -} - -func (request *baseRequest) GetDomain() string { - return request.Domain -} - -func (request *baseRequest) SetDomain(host string) { - request.Domain = host -} - -func (request *baseRequest) GetPort() string { - return request.Port -} - -func (request *baseRequest) GetRegionId() string { - return request.RegionId -} - -func (request *baseRequest) GetHeaders() map[string]string { - return request.Headers -} - -func (request *baseRequest) SetContentType(contentType string) { - request.addHeaderParam("Content-Type", contentType) -} - -func (request *baseRequest) GetContentType() (contentType string, contains bool) { - contentType, contains = request.Headers["Content-Type"] - return -} - -func (request *baseRequest) SetStringToSign(stringToSign string) { - request.stringToSign = stringToSign -} - -func (request *baseRequest) GetStringToSign() string { - return request.stringToSign -} - -func defaultBaseRequest() (request *baseRequest) { - request = &baseRequest{ - Scheme: "", - AcceptFormat: "JSON", - Method: GET, - QueryParams: make(map[string]string), - Headers: map[string]string{ - "x-sdk-client": "golang/1.0.0", - "x-sdk-invoke-type": "normal", - "Accept-Encoding": "identity", - }, - FormParams: make(map[string]string), - } - return -} - -func InitParams(request AcsRequest) (err error) { - requestValue := reflect.ValueOf(request).Elem() - err = flatRepeatedList(requestValue, request, "", "") - return -} - -func flatRepeatedList(dataValue reflect.Value, request AcsRequest, position, prefix string) (err error) { - dataType := dataValue.Type() - for i := 0; i < dataType.NumField(); i++ { - field := dataType.Field(i) - name, containsNameTag := field.Tag.Lookup("name") - fieldPosition := position - if fieldPosition == "" { - fieldPosition, _ = field.Tag.Lookup("position") - } - typeTag, containsTypeTag := field.Tag.Lookup("type") - if containsNameTag { - if !containsTypeTag { - // simple param - key := prefix + name - value := dataValue.Field(i).String() - if dataValue.Field(i).Kind().String() == "map" { - byt, _ := json.Marshal(dataValue.Field(i).Interface()) - value = string(byt) - if value == "null" { - value = "" - } - } - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else if typeTag == "Repeated" { - // repeated param - err = handleRepeatedParams(request, dataValue, prefix, name, fieldPosition, i) - if err != nil { - return - } - } else if typeTag == "Struct" { - err = handleStruct(request, dataValue, prefix, name, fieldPosition, i) - if err != nil { - return - } - } else if typeTag == "Map" { - err = handleMap(request, dataValue, prefix, name, fieldPosition, i) - if err != nil { - return err - } - } else if typeTag == "Json" { - byt, err := json.Marshal(dataValue.Field(i).Interface()) - if err != nil { - return err - } - key := prefix + name - err = addParam(request, fieldPosition, key, string(byt)) - if err != nil { - return err - } - } - } - } - return -} - -func handleRepeatedParams(request AcsRequest, dataValue reflect.Value, prefix, name, fieldPosition string, index int) (err error) { - repeatedFieldValue := dataValue.Field(index) - if repeatedFieldValue.Kind() != reflect.Slice { - // possible value: {"[]string", "*[]struct"}, we must call Elem() in the last condition - repeatedFieldValue = repeatedFieldValue.Elem() - } - if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() { - for m := 0; m < repeatedFieldValue.Len(); m++ { - elementValue := repeatedFieldValue.Index(m) - key := prefix + name + "." + strconv.Itoa(m+1) - if elementValue.Type().Kind().String() == "string" { - value := elementValue.String() - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else { - err = flatRepeatedList(elementValue, request, fieldPosition, key+".") - if err != nil { - return - } - } - } - } - return nil -} - -func handleParam(request AcsRequest, dataValue reflect.Value, prefix, key, fieldPosition string) (err error) { - if dataValue.Type().String() == "[]string" { - if dataValue.IsNil() { - return - } - for j := 0; j < dataValue.Len(); j++ { - err = addParam(request, fieldPosition, key+"."+strconv.Itoa(j+1), dataValue.Index(j).String()) - if err != nil { - return - } - } - } else { - if dataValue.Type().Kind().String() == "string" { - value := dataValue.String() - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else if dataValue.Type().Kind().String() == "struct" { - err = flatRepeatedList(dataValue, request, fieldPosition, key+".") - if err != nil { - return - } - } else if dataValue.Type().Kind().String() == "int" { - value := dataValue.Int() - err = addParam(request, fieldPosition, key, strconv.Itoa(int(value))) - if err != nil { - return err - } - } - } - return nil -} - -func handleMap(request AcsRequest, dataValue reflect.Value, prefix, name, fieldPosition string, index int) (err error) { - valueField := dataValue.Field(index) - if valueField.IsValid() && !valueField.IsNil() { - iter := valueField.MapRange() - for iter.Next() { - k := iter.Key() - v := iter.Value() - key := prefix + name + ".#" + strconv.Itoa(k.Len()) + "#" + k.String() - if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { - elementValue := v.Elem() - err = handleParam(request, elementValue, prefix, key, fieldPosition) - if err != nil { - return err - } - } else if v.IsValid() && v.IsNil() { - err = handleParam(request, v, prefix, key, fieldPosition) - if err != nil { - return err - } - } - } - } - return nil -} - -func handleStruct(request AcsRequest, dataValue reflect.Value, prefix, name, fieldPosition string, index int) (err error) { - valueField := dataValue.Field(index) - if valueField.IsValid() && valueField.String() != "" { - valueFieldType := valueField.Type() - for m := 0; m < valueFieldType.NumField(); m++ { - fieldName := valueFieldType.Field(m).Name - elementValue := valueField.FieldByName(fieldName) - key := prefix + name + "." + fieldName - if elementValue.Type().String() == "[]string" { - if elementValue.IsNil() { - continue - } - for j := 0; j < elementValue.Len(); j++ { - err = addParam(request, fieldPosition, key+"."+strconv.Itoa(j+1), elementValue.Index(j).String()) - if err != nil { - return - } - } - } else { - if elementValue.Type().Kind().String() == "string" { - value := elementValue.String() - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else if elementValue.Type().Kind().String() == "struct" { - err = flatRepeatedList(elementValue, request, fieldPosition, key+".") - if err != nil { - return - } - } else if !elementValue.IsNil() { - repeatedFieldValue := elementValue.Elem() - if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() { - for m := 0; m < repeatedFieldValue.Len(); m++ { - elementValue := repeatedFieldValue.Index(m) - if elementValue.Type().Kind().String() == "string" { - value := elementValue.String() - err := addParam(request, fieldPosition, key+"."+strconv.Itoa(m+1), value) - if err != nil { - return err - } - } else { - err = flatRepeatedList(elementValue, request, fieldPosition, key+"."+strconv.Itoa(m+1)+".") - if err != nil { - return - } - } - } - } - } - } - } - } - return nil -} - -func addParam(request AcsRequest, position, name, value string) (err error) { - if len(value) > 0 { - switch position { - case Header: - request.addHeaderParam(name, value) - case Query: - request.addQueryParam(name, value) - case Path: - request.addPathParam(name, value) - case Body: - request.addFormParam(name, value) - default: - errMsg := fmt.Sprintf(errors.UnsupportedParamPositionErrorMessage, position) - err = errors.NewClientError(errors.UnsupportedParamPositionErrorCode, errMsg, nil) - } - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go deleted file mode 100644 index a27f82c0..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go +++ /dev/null @@ -1,112 +0,0 @@ -package requests - -import ( - "bytes" - "fmt" - "io" - "sort" - "strings" -) - -type CommonRequest struct { - *baseRequest - - Version string - ApiName string - Product string - ServiceCode string - EndpointType string - - // roa params - PathPattern string - PathParams map[string]string - - Ontology AcsRequest -} - -func NewCommonRequest() (request *CommonRequest) { - request = &CommonRequest{ - baseRequest: defaultBaseRequest(), - } - request.Headers["x-sdk-invoke-type"] = "common" - request.PathParams = make(map[string]string) - return -} - -func (request *CommonRequest) String() string { - request.TransToAcsRequest() - - resultBuilder := bytes.Buffer{} - - mapOutput := func(m map[string]string) { - if len(m) > 0 { - sortedKeys := make([]string, 0) - for k := range m { - sortedKeys = append(sortedKeys, k) - } - - // sort 'string' key in increasing order - sort.Strings(sortedKeys) - - for _, key := range sortedKeys { - resultBuilder.WriteString(key + ": " + m[key] + "\n") - } - } - } - - // Request Line - resultBuilder.WriteString(fmt.Sprintf("%s %s %s/1.1\n", request.Method, request.BuildQueries(), strings.ToUpper(request.Scheme))) - - // Headers - resultBuilder.WriteString("Host" + ": " + request.Domain + "\n") - mapOutput(request.Headers) - - resultBuilder.WriteString("\n") - // Body - if len(request.Content) > 0 { - resultBuilder.WriteString(string(request.Content) + "\n") - } else { - mapOutput(request.FormParams) - } - - return resultBuilder.String() -} - -func (request *CommonRequest) TransToAcsRequest() { - if len(request.PathPattern) > 0 { - roaRequest := &RoaRequest{} - roaRequest.initWithCommonRequest(request) - request.Ontology = roaRequest - } else { - rpcRequest := &RpcRequest{} - rpcRequest.baseRequest = request.baseRequest - rpcRequest.product = request.Product - rpcRequest.version = request.Version - rpcRequest.locationServiceCode = request.ServiceCode - rpcRequest.locationEndpointType = request.EndpointType - rpcRequest.actionName = request.ApiName - rpcRequest.Headers["x-acs-version"] = request.Version - rpcRequest.Headers["x-acs-action"] = request.ApiName - request.Ontology = rpcRequest - } -} - -func (request *CommonRequest) BuildUrl() string { - return request.Ontology.BuildUrl() -} - -func (request *CommonRequest) BuildQueries() string { - return request.Ontology.BuildQueries() -} - -func (request *CommonRequest) GetBodyReader() io.Reader { - return request.Ontology.GetBodyReader() -} - -func (request *CommonRequest) GetStyle() string { - return request.Ontology.GetStyle() -} - -func (request *CommonRequest) addPathParam(key, value string) { - request.PathParams[key] = value -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go deleted file mode 100644 index 4f52345b..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package requests - -import ( - "bytes" - "fmt" - "io" - "net/url" - "sort" - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -type RoaRequest struct { - *baseRequest - pathPattern string - PathParams map[string]string -} - -func (*RoaRequest) GetStyle() string { - return ROA -} - -func (request *RoaRequest) GetBodyReader() io.Reader { - if request.FormParams != nil && len(request.FormParams) > 0 { - formString := utils.GetUrlFormedMap(request.FormParams) - return strings.NewReader(formString) - } else if len(request.Content) > 0 { - return bytes.NewReader(request.Content) - } else { - return nil - } -} - -// for sign method, need not url encoded -func (request *RoaRequest) BuildQueries() string { - return request.buildQueries() -} - -func (request *RoaRequest) buildPath() string { - path := request.pathPattern - for key, value := range request.PathParams { - path = strings.Replace(path, "["+key+"]", value, 1) - } - return path -} - -func (request *RoaRequest) buildQueries() string { - // replace path params with value - path := request.buildPath() - queryParams := request.QueryParams - // sort QueryParams by key - var queryKeys []string - for key := range queryParams { - queryKeys = append(queryKeys, key) - } - sort.Strings(queryKeys) - - // append urlBuilder - urlBuilder := bytes.Buffer{} - urlBuilder.WriteString(path) - if len(queryKeys) > 0 { - urlBuilder.WriteString("?") - } - for i := 0; i < len(queryKeys); i++ { - queryKey := queryKeys[i] - urlBuilder.WriteString(queryKey) - if value := queryParams[queryKey]; len(value) > 0 { - urlBuilder.WriteString("=") - urlBuilder.WriteString(value) - } - if i < len(queryKeys)-1 { - urlBuilder.WriteString("&") - } - } - result := urlBuilder.String() - return result -} - -func (request *RoaRequest) buildQueryString() string { - queryParams := request.QueryParams - // sort QueryParams by key - q := url.Values{} - for key, value := range queryParams { - q.Add(key, value) - } - return q.Encode() -} - -func (request *RoaRequest) BuildUrl() string { - // for network trans, need url encoded - scheme := strings.ToLower(request.Scheme) - domain := request.Domain - port := request.Port - path := request.buildPath() - url := fmt.Sprintf("%s://%s:%s%s", scheme, domain, port, path) - querystring := request.buildQueryString() - if len(querystring) > 0 { - url = fmt.Sprintf("%s?%s", url, querystring) - } - return url -} - -func (request *RoaRequest) addPathParam(key, value string) { - request.PathParams[key] = value -} - -func (request *RoaRequest) InitWithApiInfo(product, version, action, uriPattern, serviceCode, endpointType string) { - request.baseRequest = defaultBaseRequest() - request.PathParams = make(map[string]string) - request.Headers["x-acs-version"] = version - request.Headers["x-acs-action"] = action - request.pathPattern = uriPattern - request.locationServiceCode = serviceCode - request.locationEndpointType = endpointType - request.product = product - //request.version = version - request.actionName = action -} - -func (request *RoaRequest) initWithCommonRequest(commonRequest *CommonRequest) { - request.baseRequest = commonRequest.baseRequest - request.PathParams = commonRequest.PathParams - request.product = commonRequest.Product - //request.version = commonRequest.Version - request.Headers["x-acs-version"] = commonRequest.Version - if commonRequest.ApiName != "" { - request.Headers["x-acs-action"] = commonRequest.ApiName - } - request.actionName = commonRequest.ApiName - request.pathPattern = commonRequest.PathPattern - request.locationServiceCode = commonRequest.ServiceCode - request.locationEndpointType = "" -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go deleted file mode 100644 index a04765e9..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package requests - -import ( - "fmt" - "io" - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" -) - -type RpcRequest struct { - *baseRequest -} - -func (request *RpcRequest) init() { - request.baseRequest = defaultBaseRequest() - request.Method = POST -} - -func (*RpcRequest) GetStyle() string { - return RPC -} - -func (request *RpcRequest) GetBodyReader() io.Reader { - if request.FormParams != nil && len(request.FormParams) > 0 { - formString := utils.GetUrlFormedMap(request.FormParams) - return strings.NewReader(formString) - } else { - return strings.NewReader("") - } -} - -func (request *RpcRequest) BuildQueries() string { - request.queries = "/?" + utils.GetUrlFormedMap(request.QueryParams) - return request.queries -} - -func (request *RpcRequest) BuildUrl() string { - url := fmt.Sprintf("%s://%s", strings.ToLower(request.Scheme), request.Domain) - if len(request.Port) > 0 { - url = fmt.Sprintf("%s:%s", url, request.Port) - } - return url + request.BuildQueries() -} - -func (request *RpcRequest) GetVersion() string { - return request.version -} - -func (request *RpcRequest) GetActionName() string { - return request.actionName -} - -func (request *RpcRequest) addPathParam(key, value string) { - panic("not support") -} - -func (request *RpcRequest) InitWithApiInfo(product, version, action, serviceCode, endpointType string) { - request.init() - request.product = product - request.version = version - request.actionName = action - request.locationServiceCode = serviceCode - request.locationEndpointType = endpointType - request.Headers["x-acs-version"] = version - request.Headers["x-acs-action"] = action -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go deleted file mode 100644 index 28af63ea..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go +++ /dev/null @@ -1,53 +0,0 @@ -package requests - -import "strconv" - -type Integer string - -func NewInteger(integer int) Integer { - return Integer(strconv.Itoa(integer)) -} - -func (integer Integer) HasValue() bool { - return integer != "" -} - -func (integer Integer) GetValue() (int, error) { - return strconv.Atoi(string(integer)) -} - -func NewInteger64(integer int64) Integer { - return Integer(strconv.FormatInt(integer, 10)) -} - -func (integer Integer) GetValue64() (int64, error) { - return strconv.ParseInt(string(integer), 10, 0) -} - -type Boolean string - -func NewBoolean(bool bool) Boolean { - return Boolean(strconv.FormatBool(bool)) -} - -func (boolean Boolean) HasValue() bool { - return boolean != "" -} - -func (boolean Boolean) GetValue() (bool, error) { - return strconv.ParseBool(string(boolean)) -} - -type Float string - -func NewFloat(f float64) Float { - return Float(strconv.FormatFloat(f, 'f', 6, 64)) -} - -func (float Float) HasValue() bool { - return float != "" -} - -func (float Float) GetValue() (float64, error) { - return strconv.ParseFloat(string(float), 64) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go deleted file mode 100644 index cd66316d..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go +++ /dev/null @@ -1,333 +0,0 @@ -package responses - -import ( - "encoding/json" - "io" - "math" - "reflect" - "strconv" - "strings" - "unsafe" - - jsoniter "github.com/json-iterator/go" - "github.com/modern-go/reflect2" -) - -const maxUint = ^uint(0) -const maxInt = int(maxUint >> 1) -const minInt = -maxInt - 1 - -var jsonParser jsoniter.API - -func init() { - jsonParser = jsoniter.Config{ - EscapeHTML: true, - SortMapKeys: true, - ValidateJsonRawMessage: true, - CaseSensitive: true, - }.Froze() - - jsonParser.RegisterExtension(newBetterFuzzyExtension()) -} - -func newBetterFuzzyExtension() jsoniter.DecoderExtension { - return jsoniter.DecoderExtension{ - reflect2.DefaultTypeOfKind(reflect.String): &nullableFuzzyStringDecoder{}, - reflect2.DefaultTypeOfKind(reflect.Bool): &fuzzyBoolDecoder{}, - reflect2.DefaultTypeOfKind(reflect.Float32): &nullableFuzzyFloat32Decoder{}, - reflect2.DefaultTypeOfKind(reflect.Float64): &nullableFuzzyFloat64Decoder{}, - reflect2.DefaultTypeOfKind(reflect.Int): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(maxInt) || val < float64(minInt) { - iter.ReportError("fuzzy decode int", "exceed range") - return - } - *((*int)(ptr)) = int(val) - } else { - *((*int)(ptr)) = iter.ReadInt() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Uint): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(maxUint) || val < 0 { - iter.ReportError("fuzzy decode uint", "exceed range") - return - } - *((*uint)(ptr)) = uint(val) - } else { - *((*uint)(ptr)) = iter.ReadUint() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Int8): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt8) || val < float64(math.MinInt8) { - iter.ReportError("fuzzy decode int8", "exceed range") - return - } - *((*int8)(ptr)) = int8(val) - } else { - *((*int8)(ptr)) = iter.ReadInt8() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Uint8): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint8) || val < 0 { - iter.ReportError("fuzzy decode uint8", "exceed range") - return - } - *((*uint8)(ptr)) = uint8(val) - } else { - *((*uint8)(ptr)) = iter.ReadUint8() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Int16): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt16) || val < float64(math.MinInt16) { - iter.ReportError("fuzzy decode int16", "exceed range") - return - } - *((*int16)(ptr)) = int16(val) - } else { - *((*int16)(ptr)) = iter.ReadInt16() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Uint16): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint16) || val < 0 { - iter.ReportError("fuzzy decode uint16", "exceed range") - return - } - *((*uint16)(ptr)) = uint16(val) - } else { - *((*uint16)(ptr)) = iter.ReadUint16() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Int32): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt32) || val < float64(math.MinInt32) { - iter.ReportError("fuzzy decode int32", "exceed range") - return - } - *((*int32)(ptr)) = int32(val) - } else { - *((*int32)(ptr)) = iter.ReadInt32() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Uint32): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint32) || val < 0 { - iter.ReportError("fuzzy decode uint32", "exceed range") - return - } - *((*uint32)(ptr)) = uint32(val) - } else { - *((*uint32)(ptr)) = iter.ReadUint32() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Int64): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt64) || val < float64(math.MinInt64) { - iter.ReportError("fuzzy decode int64", "exceed range") - return - } - *((*int64)(ptr)) = int64(val) - } else { - *((*int64)(ptr)) = iter.ReadInt64() - } - }}, - reflect2.DefaultTypeOfKind(reflect.Uint64): &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint64) || val < 0 { - iter.ReportError("fuzzy decode uint64", "exceed range") - return - } - *((*uint64)(ptr)) = uint64(val) - } else { - *((*uint64)(ptr)) = iter.ReadUint64() - } - }}, - } -} - -type nullableFuzzyStringDecoder struct { -} - -func (decoder *nullableFuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - switch valueType { - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - *((*string)(ptr)) = string(number) - case jsoniter.StringValue: - *((*string)(ptr)) = iter.ReadString() - case jsoniter.BoolValue: - *((*string)(ptr)) = strconv.FormatBool(iter.ReadBool()) - case jsoniter.NilValue: - iter.ReadNil() - *((*string)(ptr)) = "" - default: - iter.ReportError("fuzzyStringDecoder", "not number or string or bool") - } -} - -type fuzzyBoolDecoder struct { -} - -func (decoder *fuzzyBoolDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - switch valueType { - case jsoniter.BoolValue: - *((*bool)(ptr)) = iter.ReadBool() - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - num, err := number.Int64() - if err != nil { - iter.ReportError("fuzzyBoolDecoder", "get value from json.number failed") - } - if num == 0 { - *((*bool)(ptr)) = false - } else { - *((*bool)(ptr)) = true - } - case jsoniter.StringValue: - strValue := strings.ToLower(iter.ReadString()) - if strValue == "true" { - *((*bool)(ptr)) = true - } else if strValue == "false" || strValue == "" { - *((*bool)(ptr)) = false - } else { - iter.ReportError("fuzzyBoolDecoder", "unsupported bool value: "+strValue) - } - case jsoniter.NilValue: - iter.ReadNil() - *((*bool)(ptr)) = false - default: - iter.ReportError("fuzzyBoolDecoder", "not number or string or nil") - } -} - -type nullableFuzzyIntegerDecoder struct { - fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) -} - -func (decoder *nullableFuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - str = string(number) - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - str = "0" - } - case jsoniter.BoolValue: - if iter.ReadBool() { - str = "1" - } else { - str = "0" - } - case jsoniter.NilValue: - iter.ReadNil() - str = "0" - default: - iter.ReportError("fuzzyIntegerDecoder", "not number or string") - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - isFloat := strings.IndexByte(str, '.') != -1 - decoder.fun(isFloat, ptr, newIter) - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } -} - -type nullableFuzzyFloat32Decoder struct { -} - -func (decoder *nullableFuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - *((*float32)(ptr)) = iter.ReadFloat32() - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - *((*float32)(ptr)) = 0 - return - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - *((*float32)(ptr)) = newIter.ReadFloat32() - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } - case jsoniter.BoolValue: - // support bool to float32 - if iter.ReadBool() { - *((*float32)(ptr)) = 1 - } else { - *((*float32)(ptr)) = 0 - } - case jsoniter.NilValue: - iter.ReadNil() - *((*float32)(ptr)) = 0 - default: - iter.ReportError("nullableFuzzyFloat32Decoder", "not number or string") - } -} - -type nullableFuzzyFloat64Decoder struct { -} - -func (decoder *nullableFuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - *((*float64)(ptr)) = iter.ReadFloat64() - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - *((*float64)(ptr)) = 0 - return - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - *((*float64)(ptr)) = newIter.ReadFloat64() - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } - case jsoniter.BoolValue: - // support bool to float64 - if iter.ReadBool() { - *((*float64)(ptr)) = 1 - } else { - *((*float64)(ptr)) = 0 - } - case jsoniter.NilValue: - // support empty string - iter.ReadNil() - *((*float64)(ptr)) = 0 - default: - iter.ReportError("nullableFuzzyFloat64Decoder", "not number or string") - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go deleted file mode 100644 index 53a156b7..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package responses - -import ( - "bytes" - "encoding/xml" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" -) - -type AcsResponse interface { - IsSuccess() bool - GetHttpStatus() int - GetHttpHeaders() map[string][]string - GetHttpContentString() string - GetHttpContentBytes() []byte - GetOriginHttpResponse() *http.Response - parseFromHttpResponse(httpResponse *http.Response) error -} - -// Unmarshal object from http response body to target Response -func Unmarshal(response AcsResponse, httpResponse *http.Response, format string) (err error) { - err = response.parseFromHttpResponse(httpResponse) - if err != nil { - return - } - if !response.IsSuccess() { - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), "") - return - } - - if _, isCommonResponse := response.(*CommonResponse); isCommonResponse { - // common response need not unmarshal - return - } - - if len(response.GetHttpContentBytes()) == 0 { - return - } - - if strings.ToUpper(format) == "JSON" { - err = jsonParser.Unmarshal(response.GetHttpContentBytes(), response) - if err != nil { - err = errors.NewClientError(errors.JsonUnmarshalErrorCode, errors.JsonUnmarshalErrorMessage, err) - } - } else if strings.ToUpper(format) == "XML" { - err = xml.Unmarshal(response.GetHttpContentBytes(), response) - } - return -} - -type BaseResponse struct { - httpStatus int - httpHeaders map[string][]string - httpContentString string - httpContentBytes []byte - originHttpResponse *http.Response -} - -func (baseResponse *BaseResponse) GetHttpStatus() int { - return baseResponse.httpStatus -} - -func (baseResponse *BaseResponse) GetHttpHeaders() map[string][]string { - return baseResponse.httpHeaders -} - -func (baseResponse *BaseResponse) GetHttpContentString() string { - return baseResponse.httpContentString -} - -func (baseResponse *BaseResponse) GetHttpContentBytes() []byte { - return baseResponse.httpContentBytes -} - -func (baseResponse *BaseResponse) GetOriginHttpResponse() *http.Response { - return baseResponse.originHttpResponse -} - -func (baseResponse *BaseResponse) IsSuccess() bool { - if baseResponse.GetHttpStatus() >= 200 && baseResponse.GetHttpStatus() < 300 { - return true - } - - return false -} - -func (baseResponse *BaseResponse) parseFromHttpResponse(httpResponse *http.Response) (err error) { - defer httpResponse.Body.Close() - body, err := ioutil.ReadAll(httpResponse.Body) - if err != nil { - return - } - baseResponse.httpStatus = httpResponse.StatusCode - baseResponse.httpHeaders = httpResponse.Header - baseResponse.httpContentBytes = body - baseResponse.httpContentString = string(body) - baseResponse.originHttpResponse = httpResponse - return -} - -func (baseResponse *BaseResponse) String() string { - resultBuilder := bytes.Buffer{} - // statusCode - // resultBuilder.WriteString("\n") - resultBuilder.WriteString(fmt.Sprintf("%s %s\n", baseResponse.originHttpResponse.Proto, baseResponse.originHttpResponse.Status)) - // httpHeaders - //resultBuilder.WriteString("Headers:\n") - for key, value := range baseResponse.httpHeaders { - resultBuilder.WriteString(key + ": " + strings.Join(value, ";") + "\n") - } - resultBuilder.WriteString("\n") - // content - //resultBuilder.WriteString("Content:\n") - resultBuilder.WriteString(baseResponse.httpContentString + "\n") - return resultBuilder.String() -} - -type CommonResponse struct { - *BaseResponse -} - -func NewCommonResponse() (response *CommonResponse) { - return &CommonResponse{ - BaseResponse: &BaseResponse{}, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/debug.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/debug.go deleted file mode 100644 index 09440d27..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/debug.go +++ /dev/null @@ -1,36 +0,0 @@ -package utils - -import ( - "fmt" - "os" - "strings" -) - -type Debug func(format string, v ...interface{}) - -var hookGetEnv = func() string { - return os.Getenv("DEBUG") -} - -var hookPrint = func(input string) { - fmt.Println(input) -} - -func Init(flag string) Debug { - enable := false - - env := hookGetEnv() - parts := strings.Split(env, ",") - for _, part := range parts { - if part == flag { - enable = true - break - } - } - - return func(format string, v ...interface{}) { - if enable { - hookPrint(fmt.Sprintf(format, v...)) - } - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go deleted file mode 100644 index f8a3ad38..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package utils - -import ( - "crypto/md5" - "crypto/rand" - "encoding/base64" - "encoding/hex" - "hash" - rand2 "math/rand" - "net/url" - "reflect" - "strconv" - "time" -) - -type UUID [16]byte - -const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - -func GetUUID() (uuidHex string) { - uuid := NewUUID() - uuidHex = hex.EncodeToString(uuid[:]) - return -} - -func RandStringBytes(n int) string { - b := make([]byte, n) - for i := range b { - b[i] = letterBytes[rand2.Intn(len(letterBytes))] - } - return string(b) -} - -func GetMD5Base64(bytes []byte) (base64Value string) { - md5Ctx := md5.New() - md5Ctx.Write(bytes) - md5Value := md5Ctx.Sum(nil) - base64Value = base64.StdEncoding.EncodeToString(md5Value) - return -} - -func GetTimeInFormatISO8601() (timeStr string) { - gmt := time.FixedZone("GMT", 0) - - return time.Now().In(gmt).Format("2006-01-02T15:04:05Z") -} - -func GetTimeInFormatRFC2616() (timeStr string) { - gmt := time.FixedZone("GMT", 0) - - return time.Now().In(gmt).Format("Mon, 02 Jan 2006 15:04:05 GMT") -} - -func GetUrlFormedMap(source map[string]string) (urlEncoded string) { - urlEncoder := url.Values{} - for key, value := range source { - urlEncoder.Add(key, value) - } - urlEncoded = urlEncoder.Encode() - return -} - -func InitStructWithDefaultTag(bean interface{}) { - configType := reflect.TypeOf(bean) - for i := 0; i < configType.Elem().NumField(); i++ { - field := configType.Elem().Field(i) - defaultValue := field.Tag.Get("default") - if defaultValue == "" { - continue - } - setter := reflect.ValueOf(bean).Elem().Field(i) - switch field.Type.String() { - case "int": - intValue, _ := strconv.ParseInt(defaultValue, 10, 64) - setter.SetInt(intValue) - case "time.Duration": - intValue, _ := strconv.ParseInt(defaultValue, 10, 64) - setter.SetInt(intValue) - case "string": - setter.SetString(defaultValue) - case "bool": - boolValue, _ := strconv.ParseBool(defaultValue) - setter.SetBool(boolValue) - } - } -} - -func NewUUID() UUID { - ns := UUID{} - safeRandom(ns[:]) - u := newFromHash(md5.New(), ns, RandStringBytes(16)) - u[6] = (u[6] & 0x0f) | (byte(2) << 4) - u[8] = (u[8]&(0xff>>2) | (0x02 << 6)) - - return u -} - -func newFromHash(h hash.Hash, ns UUID, name string) UUID { - u := UUID{} - h.Write(ns[:]) - h.Write([]byte(name)) - copy(u[:], h.Sum(nil)) - - return u -} - -func safeRandom(dest []byte) { - if _, err := rand.Read(dest); err != nil { - panic(err) - } -} - -func (u UUID) String() string { - buf := make([]byte, 36) - - hex.Encode(buf[0:8], u[0:4]) - buf[8] = '-' - hex.Encode(buf[9:13], u[4:6]) - buf[13] = '-' - hex.Encode(buf[14:18], u[6:8]) - buf[18] = '-' - hex.Encode(buf[19:23], u[8:10]) - buf[23] = '-' - hex.Encode(buf[24:], u[10:]) - - return string(buf) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_sign.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_sign.go deleted file mode 100644 index 8e23ccab..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_sign.go +++ /dev/null @@ -1,114 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddSmsSign invokes the dysmsapi.AddSmsSign API synchronously -func (client *Client) AddSmsSign(request *AddSmsSignRequest) (response *AddSmsSignResponse, err error) { - response = CreateAddSmsSignResponse() - err = client.DoAction(request, response) - return -} - -// AddSmsSignWithChan invokes the dysmsapi.AddSmsSign API asynchronously -func (client *Client) AddSmsSignWithChan(request *AddSmsSignRequest) (<-chan *AddSmsSignResponse, <-chan error) { - responseChan := make(chan *AddSmsSignResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddSmsSign(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddSmsSignWithCallback invokes the dysmsapi.AddSmsSign API asynchronously -func (client *Client) AddSmsSignWithCallback(request *AddSmsSignRequest, callback func(response *AddSmsSignResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddSmsSignResponse - var err error - defer close(result) - response, err = client.AddSmsSign(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddSmsSignRequest is the request struct for api AddSmsSign -type AddSmsSignRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Remark string `position:"Query" name:"Remark"` - SignName string `position:"Query" name:"SignName"` - SignFileList *[]AddSmsSignSignFileList `position:"Body" name:"SignFileList" type:"Repeated"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - SignSource requests.Integer `position:"Query" name:"SignSource"` -} - -// AddSmsSignSignFileList is a repeated param struct in AddSmsSignRequest -type AddSmsSignSignFileList struct { - FileContents string `name:"FileContents"` - FileSuffix string `name:"FileSuffix"` -} - -// AddSmsSignResponse is the response struct for api AddSmsSign -type AddSmsSignResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - SignName string `json:"SignName" xml:"SignName"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateAddSmsSignRequest creates a request to invoke AddSmsSign API -func CreateAddSmsSignRequest() (request *AddSmsSignRequest) { - request = &AddSmsSignRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "AddSmsSign", "", "") - request.Method = requests.POST - return -} - -// CreateAddSmsSignResponse creates a response to parse from AddSmsSign response -func CreateAddSmsSignResponse() (response *AddSmsSignResponse) { - response = &AddSmsSignResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_template.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_template.go deleted file mode 100644 index 129ac1ec..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/add_sms_template.go +++ /dev/null @@ -1,108 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddSmsTemplate invokes the dysmsapi.AddSmsTemplate API synchronously -func (client *Client) AddSmsTemplate(request *AddSmsTemplateRequest) (response *AddSmsTemplateResponse, err error) { - response = CreateAddSmsTemplateResponse() - err = client.DoAction(request, response) - return -} - -// AddSmsTemplateWithChan invokes the dysmsapi.AddSmsTemplate API asynchronously -func (client *Client) AddSmsTemplateWithChan(request *AddSmsTemplateRequest) (<-chan *AddSmsTemplateResponse, <-chan error) { - responseChan := make(chan *AddSmsTemplateResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddSmsTemplate(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddSmsTemplateWithCallback invokes the dysmsapi.AddSmsTemplate API asynchronously -func (client *Client) AddSmsTemplateWithCallback(request *AddSmsTemplateRequest, callback func(response *AddSmsTemplateResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddSmsTemplateResponse - var err error - defer close(result) - response, err = client.AddSmsTemplate(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddSmsTemplateRequest is the request struct for api AddSmsTemplate -type AddSmsTemplateRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Remark string `position:"Query" name:"Remark"` - TemplateType requests.Integer `position:"Query" name:"TemplateType"` - TemplateName string `position:"Query" name:"TemplateName"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TemplateContent string `position:"Query" name:"TemplateContent"` -} - -// AddSmsTemplateResponse is the response struct for api AddSmsTemplate -type AddSmsTemplateResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TemplateCode string `json:"TemplateCode" xml:"TemplateCode"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateAddSmsTemplateRequest creates a request to invoke AddSmsTemplate API -func CreateAddSmsTemplateRequest() (request *AddSmsTemplateRequest) { - request = &AddSmsTemplateRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "AddSmsTemplate", "", "") - request.Method = requests.POST - return -} - -// CreateAddSmsTemplateResponse creates a response to parse from AddSmsTemplate response -func CreateAddSmsTemplateResponse() (response *AddSmsTemplateResponse) { - response = &AddSmsTemplateResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/client.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/client.go deleted file mode 100644 index c94d36c5..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/client.go +++ /dev/null @@ -1,129 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "reflect" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider" -) - -// Client is the sdk client struct, each func corresponds to an OpenAPI -type Client struct { - sdk.Client -} - -// SetClientProperty Set Property by Reflect -func SetClientProperty(client *Client, propertyName string, propertyValue interface{}) { - v := reflect.ValueOf(client).Elem() - if v.FieldByName(propertyName).IsValid() && v.FieldByName(propertyName).CanSet() { - v.FieldByName(propertyName).Set(reflect.ValueOf(propertyValue)) - } -} - -// SetEndpointDataToClient Set EndpointMap and ENdpointType -func SetEndpointDataToClient(client *Client) { - SetClientProperty(client, "EndpointMap", GetEndpointMap()) - SetClientProperty(client, "EndpointType", GetEndpointType()) -} - -// NewClient creates a sdk client with environment variables -func NewClient() (client *Client, err error) { - client = &Client{} - err = client.Init() - SetEndpointDataToClient(client) - return -} - -// NewClientWithProvider creates a sdk client with providers -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) { - client = &Client{} - var pc provider.Provider - if len(providers) == 0 { - pc = provider.DefaultChain - } else { - pc = provider.NewProviderChain(providers) - } - err = client.InitWithProviderChain(regionId, pc) - SetEndpointDataToClient(client) - return -} - -// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential -// this is the common api to create a sdk client -func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) { - client = &Client{} - err = client.InitWithOptions(regionId, config, credential) - SetEndpointDataToClient(client) - return -} - -// NewClientWithAccessKey is a shortcut to create sdk client with accesskey -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) { - client = &Client{} - err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret) - SetEndpointDataToClient(client) - return -} - -// NewClientWithStsToken is a shortcut to create sdk client with sts token -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken) - SetEndpointDataToClient(client) - return -} - -// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) - SetEndpointDataToClient(client) - return -} - -// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn and policy -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy) - SetEndpointDataToClient(client) - return -} - -// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithEcsRamRole(regionId, roleName) - SetEndpointDataToClient(client) - return -} - -// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) { - client = &Client{} - err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration) - SetEndpointDataToClient(client) - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_sign.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_sign.go deleted file mode 100644 index e5463864..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_sign.go +++ /dev/null @@ -1,105 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteSmsSign invokes the dysmsapi.DeleteSmsSign API synchronously -func (client *Client) DeleteSmsSign(request *DeleteSmsSignRequest) (response *DeleteSmsSignResponse, err error) { - response = CreateDeleteSmsSignResponse() - err = client.DoAction(request, response) - return -} - -// DeleteSmsSignWithChan invokes the dysmsapi.DeleteSmsSign API asynchronously -func (client *Client) DeleteSmsSignWithChan(request *DeleteSmsSignRequest) (<-chan *DeleteSmsSignResponse, <-chan error) { - responseChan := make(chan *DeleteSmsSignResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteSmsSign(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteSmsSignWithCallback invokes the dysmsapi.DeleteSmsSign API asynchronously -func (client *Client) DeleteSmsSignWithCallback(request *DeleteSmsSignRequest, callback func(response *DeleteSmsSignResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteSmsSignResponse - var err error - defer close(result) - response, err = client.DeleteSmsSign(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteSmsSignRequest is the request struct for api DeleteSmsSign -type DeleteSmsSignRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - SignName string `position:"Query" name:"SignName"` -} - -// DeleteSmsSignResponse is the response struct for api DeleteSmsSign -type DeleteSmsSignResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - SignName string `json:"SignName" xml:"SignName"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateDeleteSmsSignRequest creates a request to invoke DeleteSmsSign API -func CreateDeleteSmsSignRequest() (request *DeleteSmsSignRequest) { - request = &DeleteSmsSignRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "DeleteSmsSign", "", "") - request.Method = requests.POST - return -} - -// CreateDeleteSmsSignResponse creates a response to parse from DeleteSmsSign response -func CreateDeleteSmsSignResponse() (response *DeleteSmsSignResponse) { - response = &DeleteSmsSignResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_template.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_template.go deleted file mode 100644 index ef3d7170..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/delete_sms_template.go +++ /dev/null @@ -1,105 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteSmsTemplate invokes the dysmsapi.DeleteSmsTemplate API synchronously -func (client *Client) DeleteSmsTemplate(request *DeleteSmsTemplateRequest) (response *DeleteSmsTemplateResponse, err error) { - response = CreateDeleteSmsTemplateResponse() - err = client.DoAction(request, response) - return -} - -// DeleteSmsTemplateWithChan invokes the dysmsapi.DeleteSmsTemplate API asynchronously -func (client *Client) DeleteSmsTemplateWithChan(request *DeleteSmsTemplateRequest) (<-chan *DeleteSmsTemplateResponse, <-chan error) { - responseChan := make(chan *DeleteSmsTemplateResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteSmsTemplate(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteSmsTemplateWithCallback invokes the dysmsapi.DeleteSmsTemplate API asynchronously -func (client *Client) DeleteSmsTemplateWithCallback(request *DeleteSmsTemplateRequest, callback func(response *DeleteSmsTemplateResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteSmsTemplateResponse - var err error - defer close(result) - response, err = client.DeleteSmsTemplate(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteSmsTemplateRequest is the request struct for api DeleteSmsTemplate -type DeleteSmsTemplateRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TemplateCode string `position:"Query" name:"TemplateCode"` -} - -// DeleteSmsTemplateResponse is the response struct for api DeleteSmsTemplate -type DeleteSmsTemplateResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TemplateCode string `json:"TemplateCode" xml:"TemplateCode"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateDeleteSmsTemplateRequest creates a request to invoke DeleteSmsTemplate API -func CreateDeleteSmsTemplateRequest() (request *DeleteSmsTemplateRequest) { - request = &DeleteSmsTemplateRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "DeleteSmsTemplate", "", "") - request.Method = requests.POST - return -} - -// CreateDeleteSmsTemplateResponse creates a response to parse from DeleteSmsTemplate response -func CreateDeleteSmsTemplateResponse() (response *DeleteSmsTemplateResponse) { - response = &DeleteSmsTemplateResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/endpoint.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/endpoint.go deleted file mode 100644 index 03691f2f..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/endpoint.go +++ /dev/null @@ -1,25 +0,0 @@ -package dysmsapi - -// EndpointMap Endpoint Data -var EndpointMap map[string]string - -// EndpointType regional or central -var EndpointType = "central" - -// GetEndpointMap Get Endpoint Data Map -func GetEndpointMap() map[string]string { - if EndpointMap == nil { - EndpointMap = map[string]string{ - "cn-beijing": "dysmsapi-proxy.cn-beijing.aliyuncs.com", - "cn-hongkong": "dysmsapi-xman.cn-hongkong.aliyuncs.com", - "ap-southeast-1": "dysmsapi.ap-southeast-1.aliyuncs.com", - "ap-southeast-5": "dysmsapi-xman.ap-southeast-5.aliyuncs.com", - } - } - return EndpointMap -} - -// GetEndpointType Get Endpoint Type Value -func GetEndpointType() string { - return EndpointType -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_sign.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_sign.go deleted file mode 100644 index 4c7dcf0e..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_sign.go +++ /dev/null @@ -1,114 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ModifySmsSign invokes the dysmsapi.ModifySmsSign API synchronously -func (client *Client) ModifySmsSign(request *ModifySmsSignRequest) (response *ModifySmsSignResponse, err error) { - response = CreateModifySmsSignResponse() - err = client.DoAction(request, response) - return -} - -// ModifySmsSignWithChan invokes the dysmsapi.ModifySmsSign API asynchronously -func (client *Client) ModifySmsSignWithChan(request *ModifySmsSignRequest) (<-chan *ModifySmsSignResponse, <-chan error) { - responseChan := make(chan *ModifySmsSignResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ModifySmsSign(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ModifySmsSignWithCallback invokes the dysmsapi.ModifySmsSign API asynchronously -func (client *Client) ModifySmsSignWithCallback(request *ModifySmsSignRequest, callback func(response *ModifySmsSignResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ModifySmsSignResponse - var err error - defer close(result) - response, err = client.ModifySmsSign(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ModifySmsSignRequest is the request struct for api ModifySmsSign -type ModifySmsSignRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Remark string `position:"Query" name:"Remark"` - SignName string `position:"Query" name:"SignName"` - SignFileList *[]ModifySmsSignSignFileList `position:"Body" name:"SignFileList" type:"Repeated"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - SignSource requests.Integer `position:"Query" name:"SignSource"` -} - -// ModifySmsSignSignFileList is a repeated param struct in ModifySmsSignRequest -type ModifySmsSignSignFileList struct { - FileContents string `name:"FileContents"` - FileSuffix string `name:"FileSuffix"` -} - -// ModifySmsSignResponse is the response struct for api ModifySmsSign -type ModifySmsSignResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - SignName string `json:"SignName" xml:"SignName"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateModifySmsSignRequest creates a request to invoke ModifySmsSign API -func CreateModifySmsSignRequest() (request *ModifySmsSignRequest) { - request = &ModifySmsSignRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "ModifySmsSign", "", "") - request.Method = requests.POST - return -} - -// CreateModifySmsSignResponse creates a response to parse from ModifySmsSign response -func CreateModifySmsSignResponse() (response *ModifySmsSignResponse) { - response = &ModifySmsSignResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_template.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_template.go deleted file mode 100644 index c7c77c18..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/modify_sms_template.go +++ /dev/null @@ -1,109 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ModifySmsTemplate invokes the dysmsapi.ModifySmsTemplate API synchronously -func (client *Client) ModifySmsTemplate(request *ModifySmsTemplateRequest) (response *ModifySmsTemplateResponse, err error) { - response = CreateModifySmsTemplateResponse() - err = client.DoAction(request, response) - return -} - -// ModifySmsTemplateWithChan invokes the dysmsapi.ModifySmsTemplate API asynchronously -func (client *Client) ModifySmsTemplateWithChan(request *ModifySmsTemplateRequest) (<-chan *ModifySmsTemplateResponse, <-chan error) { - responseChan := make(chan *ModifySmsTemplateResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ModifySmsTemplate(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ModifySmsTemplateWithCallback invokes the dysmsapi.ModifySmsTemplate API asynchronously -func (client *Client) ModifySmsTemplateWithCallback(request *ModifySmsTemplateRequest, callback func(response *ModifySmsTemplateResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ModifySmsTemplateResponse - var err error - defer close(result) - response, err = client.ModifySmsTemplate(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ModifySmsTemplateRequest is the request struct for api ModifySmsTemplate -type ModifySmsTemplateRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Remark string `position:"Query" name:"Remark"` - TemplateType requests.Integer `position:"Query" name:"TemplateType"` - TemplateName string `position:"Query" name:"TemplateName"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TemplateContent string `position:"Query" name:"TemplateContent"` - TemplateCode string `position:"Query" name:"TemplateCode"` -} - -// ModifySmsTemplateResponse is the response struct for api ModifySmsTemplate -type ModifySmsTemplateResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TemplateCode string `json:"TemplateCode" xml:"TemplateCode"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateModifySmsTemplateRequest creates a request to invoke ModifySmsTemplate API -func CreateModifySmsTemplateRequest() (request *ModifySmsTemplateRequest) { - request = &ModifySmsTemplateRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "ModifySmsTemplate", "", "") - request.Method = requests.POST - return -} - -// CreateModifySmsTemplateResponse creates a response to parse from ModifySmsTemplate response -func CreateModifySmsTemplateResponse() (response *ModifySmsTemplateResponse) { - response = &ModifySmsTemplateResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_send_details.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_send_details.go deleted file mode 100644 index 1aa671f7..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_send_details.go +++ /dev/null @@ -1,110 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QuerySendDetails invokes the dysmsapi.QuerySendDetails API synchronously -func (client *Client) QuerySendDetails(request *QuerySendDetailsRequest) (response *QuerySendDetailsResponse, err error) { - response = CreateQuerySendDetailsResponse() - err = client.DoAction(request, response) - return -} - -// QuerySendDetailsWithChan invokes the dysmsapi.QuerySendDetails API asynchronously -func (client *Client) QuerySendDetailsWithChan(request *QuerySendDetailsRequest) (<-chan *QuerySendDetailsResponse, <-chan error) { - responseChan := make(chan *QuerySendDetailsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QuerySendDetails(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QuerySendDetailsWithCallback invokes the dysmsapi.QuerySendDetails API asynchronously -func (client *Client) QuerySendDetailsWithCallback(request *QuerySendDetailsRequest, callback func(response *QuerySendDetailsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QuerySendDetailsResponse - var err error - defer close(result) - response, err = client.QuerySendDetails(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QuerySendDetailsRequest is the request struct for api QuerySendDetails -type QuerySendDetailsRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - PhoneNumber string `position:"Query" name:"PhoneNumber"` - SendDate string `position:"Query" name:"SendDate"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - CurrentPage requests.Integer `position:"Query" name:"CurrentPage"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - BizId string `position:"Query" name:"BizId"` -} - -// QuerySendDetailsResponse is the response struct for api QuerySendDetails -type QuerySendDetailsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` - TotalCount string `json:"TotalCount" xml:"TotalCount"` - SmsSendDetailDTOs SmsSendDetailDTOs `json:"SmsSendDetailDTOs" xml:"SmsSendDetailDTOs"` -} - -// CreateQuerySendDetailsRequest creates a request to invoke QuerySendDetails API -func CreateQuerySendDetailsRequest() (request *QuerySendDetailsRequest) { - request = &QuerySendDetailsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "QuerySendDetails", "", "") - request.Method = requests.POST - return -} - -// CreateQuerySendDetailsResponse creates a response to parse from QuerySendDetails response -func CreateQuerySendDetailsResponse() (response *QuerySendDetailsResponse) { - response = &QuerySendDetailsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_sign.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_sign.go deleted file mode 100644 index 9177e4ee..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_sign.go +++ /dev/null @@ -1,108 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QuerySmsSign invokes the dysmsapi.QuerySmsSign API synchronously -func (client *Client) QuerySmsSign(request *QuerySmsSignRequest) (response *QuerySmsSignResponse, err error) { - response = CreateQuerySmsSignResponse() - err = client.DoAction(request, response) - return -} - -// QuerySmsSignWithChan invokes the dysmsapi.QuerySmsSign API asynchronously -func (client *Client) QuerySmsSignWithChan(request *QuerySmsSignRequest) (<-chan *QuerySmsSignResponse, <-chan error) { - responseChan := make(chan *QuerySmsSignResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QuerySmsSign(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QuerySmsSignWithCallback invokes the dysmsapi.QuerySmsSign API asynchronously -func (client *Client) QuerySmsSignWithCallback(request *QuerySmsSignRequest, callback func(response *QuerySmsSignResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QuerySmsSignResponse - var err error - defer close(result) - response, err = client.QuerySmsSign(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QuerySmsSignRequest is the request struct for api QuerySmsSign -type QuerySmsSignRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - SignName string `position:"Query" name:"SignName"` -} - -// QuerySmsSignResponse is the response struct for api QuerySmsSign -type QuerySmsSignResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` - SignStatus int `json:"SignStatus" xml:"SignStatus"` - Reason string `json:"Reason" xml:"Reason"` - SignName string `json:"SignName" xml:"SignName"` - CreateDate string `json:"CreateDate" xml:"CreateDate"` -} - -// CreateQuerySmsSignRequest creates a request to invoke QuerySmsSign API -func CreateQuerySmsSignRequest() (request *QuerySmsSignRequest) { - request = &QuerySmsSignRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "QuerySmsSign", "", "") - request.Method = requests.POST - return -} - -// CreateQuerySmsSignResponse creates a response to parse from QuerySmsSign response -func CreateQuerySmsSignResponse() (response *QuerySmsSignResponse) { - response = &QuerySmsSignResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_template.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_template.go deleted file mode 100644 index bd7e2155..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/query_sms_template.go +++ /dev/null @@ -1,111 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QuerySmsTemplate invokes the dysmsapi.QuerySmsTemplate API synchronously -func (client *Client) QuerySmsTemplate(request *QuerySmsTemplateRequest) (response *QuerySmsTemplateResponse, err error) { - response = CreateQuerySmsTemplateResponse() - err = client.DoAction(request, response) - return -} - -// QuerySmsTemplateWithChan invokes the dysmsapi.QuerySmsTemplate API asynchronously -func (client *Client) QuerySmsTemplateWithChan(request *QuerySmsTemplateRequest) (<-chan *QuerySmsTemplateResponse, <-chan error) { - responseChan := make(chan *QuerySmsTemplateResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QuerySmsTemplate(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QuerySmsTemplateWithCallback invokes the dysmsapi.QuerySmsTemplate API asynchronously -func (client *Client) QuerySmsTemplateWithCallback(request *QuerySmsTemplateRequest, callback func(response *QuerySmsTemplateResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QuerySmsTemplateResponse - var err error - defer close(result) - response, err = client.QuerySmsTemplate(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QuerySmsTemplateRequest is the request struct for api QuerySmsTemplate -type QuerySmsTemplateRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TemplateCode string `position:"Query" name:"TemplateCode"` -} - -// QuerySmsTemplateResponse is the response struct for api QuerySmsTemplate -type QuerySmsTemplateResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` - TemplateStatus int `json:"TemplateStatus" xml:"TemplateStatus"` - Reason string `json:"Reason" xml:"Reason"` - TemplateCode string `json:"TemplateCode" xml:"TemplateCode"` - TemplateType int `json:"TemplateType" xml:"TemplateType"` - TemplateName string `json:"TemplateName" xml:"TemplateName"` - TemplateContent string `json:"TemplateContent" xml:"TemplateContent"` - CreateDate string `json:"CreateDate" xml:"CreateDate"` -} - -// CreateQuerySmsTemplateRequest creates a request to invoke QuerySmsTemplate API -func CreateQuerySmsTemplateRequest() (request *QuerySmsTemplateRequest) { - request = &QuerySmsTemplateRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "QuerySmsTemplate", "", "") - request.Method = requests.POST - return -} - -// CreateQuerySmsTemplateResponse creates a response to parse from QuerySmsTemplate response -func CreateQuerySmsTemplateResponse() (response *QuerySmsTemplateResponse) { - response = &QuerySmsTemplateResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_batch_sms.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_batch_sms.go deleted file mode 100644 index fd14cbc0..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_batch_sms.go +++ /dev/null @@ -1,109 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SendBatchSms invokes the dysmsapi.SendBatchSms API synchronously -func (client *Client) SendBatchSms(request *SendBatchSmsRequest) (response *SendBatchSmsResponse, err error) { - response = CreateSendBatchSmsResponse() - err = client.DoAction(request, response) - return -} - -// SendBatchSmsWithChan invokes the dysmsapi.SendBatchSms API asynchronously -func (client *Client) SendBatchSmsWithChan(request *SendBatchSmsRequest) (<-chan *SendBatchSmsResponse, <-chan error) { - responseChan := make(chan *SendBatchSmsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SendBatchSms(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SendBatchSmsWithCallback invokes the dysmsapi.SendBatchSms API asynchronously -func (client *Client) SendBatchSmsWithCallback(request *SendBatchSmsRequest, callback func(response *SendBatchSmsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SendBatchSmsResponse - var err error - defer close(result) - response, err = client.SendBatchSms(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SendBatchSmsRequest is the request struct for api SendBatchSms -type SendBatchSmsRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - TemplateParamJson string `position:"Query" name:"TemplateParamJson"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - SmsUpExtendCodeJson string `position:"Query" name:"SmsUpExtendCodeJson"` - SignNameJson string `position:"Query" name:"SignNameJson"` - TemplateCode string `position:"Query" name:"TemplateCode"` - PhoneNumberJson string `position:"Query" name:"PhoneNumberJson"` -} - -// SendBatchSmsResponse is the response struct for api SendBatchSms -type SendBatchSmsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - BizId string `json:"BizId" xml:"BizId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateSendBatchSmsRequest creates a request to invoke SendBatchSms API -func CreateSendBatchSmsRequest() (request *SendBatchSmsRequest) { - request = &SendBatchSmsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "SendBatchSms", "", "") - request.Method = requests.POST - return -} - -// CreateSendBatchSmsResponse creates a response to parse from SendBatchSms response -func CreateSendBatchSmsResponse() (response *SendBatchSmsResponse) { - response = &SendBatchSmsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_sms.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_sms.go deleted file mode 100644 index 11409918..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/send_sms.go +++ /dev/null @@ -1,110 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SendSms invokes the dysmsapi.SendSms API synchronously -func (client *Client) SendSms(request *SendSmsRequest) (response *SendSmsResponse, err error) { - response = CreateSendSmsResponse() - err = client.DoAction(request, response) - return -} - -// SendSmsWithChan invokes the dysmsapi.SendSms API asynchronously -func (client *Client) SendSmsWithChan(request *SendSmsRequest) (<-chan *SendSmsResponse, <-chan error) { - responseChan := make(chan *SendSmsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SendSms(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SendSmsWithCallback invokes the dysmsapi.SendSms API asynchronously -func (client *Client) SendSmsWithCallback(request *SendSmsRequest, callback func(response *SendSmsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SendSmsResponse - var err error - defer close(result) - response, err = client.SendSms(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SendSmsRequest is the request struct for api SendSms -type SendSmsRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - SmsUpExtendCode string `position:"Query" name:"SmsUpExtendCode"` - SignName string `position:"Query" name:"SignName"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - PhoneNumbers string `position:"Query" name:"PhoneNumbers"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - OutId string `position:"Query" name:"OutId"` - TemplateCode string `position:"Query" name:"TemplateCode"` - TemplateParam string `position:"Query" name:"TemplateParam"` -} - -// SendSmsResponse is the response struct for api SendSms -type SendSmsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - BizId string `json:"BizId" xml:"BizId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateSendSmsRequest creates a request to invoke SendSms API -func CreateSendSmsRequest() (request *SendSmsRequest) { - request = &SendSmsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dysmsapi", "2017-05-25", "SendSms", "", "") - request.Method = requests.POST - return -} - -// CreateSendSmsResponse creates a response to parse from SendSms response -func CreateSendSmsResponse() (response *SendSmsResponse) { - response = &SendSmsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dt_os.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dt_os.go deleted file mode 100644 index aaa89966..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dt_os.go +++ /dev/null @@ -1,21 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// SmsSendDetailDTOs is a nested struct in dysmsapi response -type SmsSendDetailDTOs struct { - SmsSendDetailDTO []SmsSendDetailDTO `json:"SmsSendDetailDTO" xml:"SmsSendDetailDTO"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dto.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dto.go deleted file mode 100644 index 1dacb3e6..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi/struct_sms_send_detail_dto.go +++ /dev/null @@ -1,28 +0,0 @@ -package dysmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// SmsSendDetailDTO is a nested struct in dysmsapi response -type SmsSendDetailDTO struct { - PhoneNum string `json:"PhoneNum" xml:"PhoneNum"` - SendStatus int64 `json:"SendStatus" xml:"SendStatus"` - ErrCode string `json:"ErrCode" xml:"ErrCode"` - TemplateCode string `json:"TemplateCode" xml:"TemplateCode"` - Content string `json:"Content" xml:"Content"` - SendDate string `json:"SendDate" xml:"SendDate"` - ReceiveDate string `json:"ReceiveDate" xml:"ReceiveDate"` - OutId string `json:"OutId" xml:"OutId"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/add_rtc_account.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/add_rtc_account.go deleted file mode 100644 index 7e2c4a09..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/add_rtc_account.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddRtcAccount invokes the dyvmsapi.AddRtcAccount API synchronously -func (client *Client) AddRtcAccount(request *AddRtcAccountRequest) (response *AddRtcAccountResponse, err error) { - response = CreateAddRtcAccountResponse() - err = client.DoAction(request, response) - return -} - -// AddRtcAccountWithChan invokes the dyvmsapi.AddRtcAccount API asynchronously -func (client *Client) AddRtcAccountWithChan(request *AddRtcAccountRequest) (<-chan *AddRtcAccountResponse, <-chan error) { - responseChan := make(chan *AddRtcAccountResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddRtcAccount(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddRtcAccountWithCallback invokes the dyvmsapi.AddRtcAccount API asynchronously -func (client *Client) AddRtcAccountWithCallback(request *AddRtcAccountRequest, callback func(response *AddRtcAccountResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddRtcAccountResponse - var err error - defer close(result) - response, err = client.AddRtcAccount(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddRtcAccountRequest is the request struct for api AddRtcAccount -type AddRtcAccountRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - DeviceId string `position:"Query" name:"DeviceId"` -} - -// AddRtcAccountResponse is the response struct for api AddRtcAccount -type AddRtcAccountResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Module string `json:"Module" xml:"Module"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateAddRtcAccountRequest creates a request to invoke AddRtcAccount API -func CreateAddRtcAccountRequest() (request *AddRtcAccountRequest) { - request = &AddRtcAccountRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "AddRtcAccount", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateAddRtcAccountResponse creates a response to parse from AddRtcAccount response -func CreateAddRtcAccountResponse() (response *AddRtcAccountResponse) { - response = &AddRtcAccountResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/batch_robot_smart_call.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/batch_robot_smart_call.go deleted file mode 100644 index 1011ca0a..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/batch_robot_smart_call.go +++ /dev/null @@ -1,115 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// BatchRobotSmartCall invokes the dyvmsapi.BatchRobotSmartCall API synchronously -func (client *Client) BatchRobotSmartCall(request *BatchRobotSmartCallRequest) (response *BatchRobotSmartCallResponse, err error) { - response = CreateBatchRobotSmartCallResponse() - err = client.DoAction(request, response) - return -} - -// BatchRobotSmartCallWithChan invokes the dyvmsapi.BatchRobotSmartCall API asynchronously -func (client *Client) BatchRobotSmartCallWithChan(request *BatchRobotSmartCallRequest) (<-chan *BatchRobotSmartCallResponse, <-chan error) { - responseChan := make(chan *BatchRobotSmartCallResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.BatchRobotSmartCall(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// BatchRobotSmartCallWithCallback invokes the dyvmsapi.BatchRobotSmartCall API asynchronously -func (client *Client) BatchRobotSmartCallWithCallback(request *BatchRobotSmartCallRequest, callback func(response *BatchRobotSmartCallResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *BatchRobotSmartCallResponse - var err error - defer close(result) - response, err = client.BatchRobotSmartCall(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// BatchRobotSmartCallRequest is the request struct for api BatchRobotSmartCall -type BatchRobotSmartCallRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - EarlyMediaAsr requests.Boolean `position:"Query" name:"EarlyMediaAsr"` - TtsParamHead string `position:"Query" name:"TtsParamHead"` - TaskName string `position:"Query" name:"TaskName"` - TtsParam string `position:"Query" name:"TtsParam"` - CalledNumber string `position:"Query" name:"CalledNumber"` - CalledShowNumber string `position:"Query" name:"CalledShowNumber"` - IsSelfLine requests.Boolean `position:"Query" name:"IsSelfLine"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - DialogId string `position:"Query" name:"DialogId"` - ScheduleTime requests.Integer `position:"Query" name:"ScheduleTime"` - CorpName string `position:"Query" name:"CorpName"` - ScheduleCall requests.Boolean `position:"Query" name:"ScheduleCall"` -} - -// BatchRobotSmartCallResponse is the response struct for api BatchRobotSmartCall -type BatchRobotSmartCallResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TaskId string `json:"TaskId" xml:"TaskId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateBatchRobotSmartCallRequest creates a request to invoke BatchRobotSmartCall API -func CreateBatchRobotSmartCallRequest() (request *BatchRobotSmartCallRequest) { - request = &BatchRobotSmartCallRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "BatchRobotSmartCall", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateBatchRobotSmartCallResponse creates a response to parse from BatchRobotSmartCall response -func CreateBatchRobotSmartCallResponse() (response *BatchRobotSmartCallResponse) { - response = &BatchRobotSmartCallResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/bind_number_and_voip_id.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/bind_number_and_voip_id.go deleted file mode 100644 index 4f9f0724..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/bind_number_and_voip_id.go +++ /dev/null @@ -1,106 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// BindNumberAndVoipId invokes the dyvmsapi.BindNumberAndVoipId API synchronously -func (client *Client) BindNumberAndVoipId(request *BindNumberAndVoipIdRequest) (response *BindNumberAndVoipIdResponse, err error) { - response = CreateBindNumberAndVoipIdResponse() - err = client.DoAction(request, response) - return -} - -// BindNumberAndVoipIdWithChan invokes the dyvmsapi.BindNumberAndVoipId API asynchronously -func (client *Client) BindNumberAndVoipIdWithChan(request *BindNumberAndVoipIdRequest) (<-chan *BindNumberAndVoipIdResponse, <-chan error) { - responseChan := make(chan *BindNumberAndVoipIdResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.BindNumberAndVoipId(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// BindNumberAndVoipIdWithCallback invokes the dyvmsapi.BindNumberAndVoipId API asynchronously -func (client *Client) BindNumberAndVoipIdWithCallback(request *BindNumberAndVoipIdRequest, callback func(response *BindNumberAndVoipIdResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *BindNumberAndVoipIdResponse - var err error - defer close(result) - response, err = client.BindNumberAndVoipId(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// BindNumberAndVoipIdRequest is the request struct for api BindNumberAndVoipId -type BindNumberAndVoipIdRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - PhoneNumber string `position:"Query" name:"PhoneNumber"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - VoipId string `position:"Query" name:"VoipId"` -} - -// BindNumberAndVoipIdResponse is the response struct for api BindNumberAndVoipId -type BindNumberAndVoipIdResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Code string `json:"Code" xml:"Code"` - Module string `json:"Module" xml:"Module"` - Message string `json:"Message" xml:"Message"` -} - -// CreateBindNumberAndVoipIdRequest creates a request to invoke BindNumberAndVoipId API -func CreateBindNumberAndVoipIdRequest() (request *BindNumberAndVoipIdRequest) { - request = &BindNumberAndVoipIdRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "BindNumberAndVoipId", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateBindNumberAndVoipIdResponse creates a response to parse from BindNumberAndVoipId response -func CreateBindNumberAndVoipIdResponse() (response *BindNumberAndVoipIdResponse) { - response = &BindNumberAndVoipIdResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_call.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_call.go deleted file mode 100644 index 2b729a05..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_call.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// CancelCall invokes the dyvmsapi.CancelCall API synchronously -func (client *Client) CancelCall(request *CancelCallRequest) (response *CancelCallResponse, err error) { - response = CreateCancelCallResponse() - err = client.DoAction(request, response) - return -} - -// CancelCallWithChan invokes the dyvmsapi.CancelCall API asynchronously -func (client *Client) CancelCallWithChan(request *CancelCallRequest) (<-chan *CancelCallResponse, <-chan error) { - responseChan := make(chan *CancelCallResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.CancelCall(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// CancelCallWithCallback invokes the dyvmsapi.CancelCall API asynchronously -func (client *Client) CancelCallWithCallback(request *CancelCallRequest, callback func(response *CancelCallResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *CancelCallResponse - var err error - defer close(result) - response, err = client.CancelCall(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// CancelCallRequest is the request struct for api CancelCall -type CancelCallRequest struct { - *requests.RpcRequest - CallId string `position:"Query" name:"CallId"` - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` -} - -// CancelCallResponse is the response struct for api CancelCall -type CancelCallResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Status bool `json:"Status" xml:"Status"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateCancelCallRequest creates a request to invoke CancelCall API -func CreateCancelCallRequest() (request *CancelCallRequest) { - request = &CancelCallRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "CancelCall", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateCancelCallResponse creates a response to parse from CancelCall response -func CreateCancelCallResponse() (response *CancelCallResponse) { - response = &CancelCallResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_order_robot_task.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_order_robot_task.go deleted file mode 100644 index 873aea11..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_order_robot_task.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// CancelOrderRobotTask invokes the dyvmsapi.CancelOrderRobotTask API synchronously -func (client *Client) CancelOrderRobotTask(request *CancelOrderRobotTaskRequest) (response *CancelOrderRobotTaskResponse, err error) { - response = CreateCancelOrderRobotTaskResponse() - err = client.DoAction(request, response) - return -} - -// CancelOrderRobotTaskWithChan invokes the dyvmsapi.CancelOrderRobotTask API asynchronously -func (client *Client) CancelOrderRobotTaskWithChan(request *CancelOrderRobotTaskRequest) (<-chan *CancelOrderRobotTaskResponse, <-chan error) { - responseChan := make(chan *CancelOrderRobotTaskResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.CancelOrderRobotTask(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// CancelOrderRobotTaskWithCallback invokes the dyvmsapi.CancelOrderRobotTask API asynchronously -func (client *Client) CancelOrderRobotTaskWithCallback(request *CancelOrderRobotTaskRequest, callback func(response *CancelOrderRobotTaskResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *CancelOrderRobotTaskResponse - var err error - defer close(result) - response, err = client.CancelOrderRobotTask(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// CancelOrderRobotTaskRequest is the request struct for api CancelOrderRobotTask -type CancelOrderRobotTaskRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TaskId requests.Integer `position:"Query" name:"TaskId"` -} - -// CancelOrderRobotTaskResponse is the response struct for api CancelOrderRobotTask -type CancelOrderRobotTaskResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateCancelOrderRobotTaskRequest creates a request to invoke CancelOrderRobotTask API -func CreateCancelOrderRobotTaskRequest() (request *CancelOrderRobotTaskRequest) { - request = &CancelOrderRobotTaskRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "CancelOrderRobotTask", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateCancelOrderRobotTaskResponse creates a response to parse from CancelOrderRobotTask response -func CreateCancelOrderRobotTaskResponse() (response *CancelOrderRobotTaskResponse) { - response = &CancelOrderRobotTaskResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_robot_task.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_robot_task.go deleted file mode 100644 index 3ca6c8e9..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/cancel_robot_task.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// CancelRobotTask invokes the dyvmsapi.CancelRobotTask API synchronously -func (client *Client) CancelRobotTask(request *CancelRobotTaskRequest) (response *CancelRobotTaskResponse, err error) { - response = CreateCancelRobotTaskResponse() - err = client.DoAction(request, response) - return -} - -// CancelRobotTaskWithChan invokes the dyvmsapi.CancelRobotTask API asynchronously -func (client *Client) CancelRobotTaskWithChan(request *CancelRobotTaskRequest) (<-chan *CancelRobotTaskResponse, <-chan error) { - responseChan := make(chan *CancelRobotTaskResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.CancelRobotTask(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// CancelRobotTaskWithCallback invokes the dyvmsapi.CancelRobotTask API asynchronously -func (client *Client) CancelRobotTaskWithCallback(request *CancelRobotTaskRequest, callback func(response *CancelRobotTaskResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *CancelRobotTaskResponse - var err error - defer close(result) - response, err = client.CancelRobotTask(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// CancelRobotTaskRequest is the request struct for api CancelRobotTask -type CancelRobotTaskRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TaskId requests.Integer `position:"Query" name:"TaskId"` -} - -// CancelRobotTaskResponse is the response struct for api CancelRobotTask -type CancelRobotTaskResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateCancelRobotTaskRequest creates a request to invoke CancelRobotTask API -func CreateCancelRobotTaskRequest() (request *CancelRobotTaskRequest) { - request = &CancelRobotTaskRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "CancelRobotTask", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateCancelRobotTaskResponse creates a response to parse from CancelRobotTask response -func CreateCancelRobotTaskResponse() (response *CancelRobotTaskResponse) { - response = &CancelRobotTaskResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/click_to_dial.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/click_to_dial.go deleted file mode 100644 index 0e800fd2..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/click_to_dial.go +++ /dev/null @@ -1,113 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ClickToDial invokes the dyvmsapi.ClickToDial API synchronously -func (client *Client) ClickToDial(request *ClickToDialRequest) (response *ClickToDialResponse, err error) { - response = CreateClickToDialResponse() - err = client.DoAction(request, response) - return -} - -// ClickToDialWithChan invokes the dyvmsapi.ClickToDial API asynchronously -func (client *Client) ClickToDialWithChan(request *ClickToDialRequest) (<-chan *ClickToDialResponse, <-chan error) { - responseChan := make(chan *ClickToDialResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ClickToDial(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ClickToDialWithCallback invokes the dyvmsapi.ClickToDial API asynchronously -func (client *Client) ClickToDialWithCallback(request *ClickToDialRequest, callback func(response *ClickToDialResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ClickToDialResponse - var err error - defer close(result) - response, err = client.ClickToDial(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ClickToDialRequest is the request struct for api ClickToDial -type ClickToDialRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - CallerShowNumber string `position:"Query" name:"CallerShowNumber"` - SessionTimeout requests.Integer `position:"Query" name:"SessionTimeout"` - CalledNumber string `position:"Query" name:"CalledNumber"` - CalledShowNumber string `position:"Query" name:"CalledShowNumber"` - AsrFlag requests.Boolean `position:"Query" name:"AsrFlag"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - RecordFlag requests.Boolean `position:"Query" name:"RecordFlag"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - OutId string `position:"Query" name:"OutId"` - AsrModelId string `position:"Query" name:"AsrModelId"` - CallerNumber string `position:"Query" name:"CallerNumber"` -} - -// ClickToDialResponse is the response struct for api ClickToDial -type ClickToDialResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - CallId string `json:"CallId" xml:"CallId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateClickToDialRequest creates a request to invoke ClickToDial API -func CreateClickToDialRequest() (request *ClickToDialRequest) { - request = &ClickToDialRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "ClickToDial", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateClickToDialResponse creates a response to parse from ClickToDial response -func CreateClickToDialResponse() (response *ClickToDialResponse) { - response = &ClickToDialResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/client.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/client.go deleted file mode 100644 index a6a997ec..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/client.go +++ /dev/null @@ -1,129 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "reflect" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider" -) - -// Client is the sdk client struct, each func corresponds to an OpenAPI -type Client struct { - sdk.Client -} - -// SetClientProperty Set Property by Reflect -func SetClientProperty(client *Client, propertyName string, propertyValue interface{}) { - v := reflect.ValueOf(client).Elem() - if v.FieldByName(propertyName).IsValid() && v.FieldByName(propertyName).CanSet() { - v.FieldByName(propertyName).Set(reflect.ValueOf(propertyValue)) - } -} - -// SetEndpointDataToClient Set EndpointMap and ENdpointType -func SetEndpointDataToClient(client *Client) { - SetClientProperty(client, "EndpointMap", GetEndpointMap()) - SetClientProperty(client, "EndpointType", GetEndpointType()) -} - -// NewClient creates a sdk client with environment variables -func NewClient() (client *Client, err error) { - client = &Client{} - err = client.Init() - SetEndpointDataToClient(client) - return -} - -// NewClientWithProvider creates a sdk client with providers -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) { - client = &Client{} - var pc provider.Provider - if len(providers) == 0 { - pc = provider.DefaultChain - } else { - pc = provider.NewProviderChain(providers) - } - err = client.InitWithProviderChain(regionId, pc) - SetEndpointDataToClient(client) - return -} - -// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential -// this is the common api to create a sdk client -func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) { - client = &Client{} - err = client.InitWithOptions(regionId, config, credential) - SetEndpointDataToClient(client) - return -} - -// NewClientWithAccessKey is a shortcut to create sdk client with accesskey -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) { - client = &Client{} - err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret) - SetEndpointDataToClient(client) - return -} - -// NewClientWithStsToken is a shortcut to create sdk client with sts token -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken) - SetEndpointDataToClient(client) - return -} - -// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) - SetEndpointDataToClient(client) - return -} - -// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn and policy -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy) - SetEndpointDataToClient(client) - return -} - -// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithEcsRamRole(regionId, roleName) - SetEndpointDataToClient(client) - return -} - -// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair -// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md -func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) { - client = &Client{} - err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration) - SetEndpointDataToClient(client) - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/create_robot_task.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/create_robot_task.go deleted file mode 100644 index b5f2e56d..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/create_robot_task.go +++ /dev/null @@ -1,114 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// CreateRobotTask invokes the dyvmsapi.CreateRobotTask API synchronously -func (client *Client) CreateRobotTask(request *CreateRobotTaskRequest) (response *CreateRobotTaskResponse, err error) { - response = CreateCreateRobotTaskResponse() - err = client.DoAction(request, response) - return -} - -// CreateRobotTaskWithChan invokes the dyvmsapi.CreateRobotTask API asynchronously -func (client *Client) CreateRobotTaskWithChan(request *CreateRobotTaskRequest) (<-chan *CreateRobotTaskResponse, <-chan error) { - responseChan := make(chan *CreateRobotTaskResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.CreateRobotTask(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// CreateRobotTaskWithCallback invokes the dyvmsapi.CreateRobotTask API asynchronously -func (client *Client) CreateRobotTaskWithCallback(request *CreateRobotTaskRequest, callback func(response *CreateRobotTaskResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *CreateRobotTaskResponse - var err error - defer close(result) - response, err = client.CreateRobotTask(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// CreateRobotTaskRequest is the request struct for api CreateRobotTask -type CreateRobotTaskRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - RecallStateCodes string `position:"Query" name:"RecallStateCodes"` - TaskName string `position:"Query" name:"TaskName"` - RecallTimes requests.Integer `position:"Query" name:"RecallTimes"` - IsSelfLine requests.Boolean `position:"Query" name:"IsSelfLine"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - RetryType requests.Integer `position:"Query" name:"RetryType"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - DialogId requests.Integer `position:"Query" name:"DialogId"` - Caller string `position:"Query" name:"Caller"` - NumberStatusIdent requests.Boolean `position:"Query" name:"NumberStatusIdent"` - CorpName string `position:"Query" name:"CorpName"` - RecallInterval requests.Integer `position:"Query" name:"RecallInterval"` -} - -// CreateRobotTaskResponse is the response struct for api CreateRobotTask -type CreateRobotTaskResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateCreateRobotTaskRequest creates a request to invoke CreateRobotTask API -func CreateCreateRobotTaskRequest() (request *CreateRobotTaskRequest) { - request = &CreateRobotTaskRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "CreateRobotTask", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateCreateRobotTaskResponse creates a response to parse from CreateRobotTask response -func CreateCreateRobotTaskResponse() (response *CreateRobotTaskResponse) { - response = &CreateRobotTaskResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/delete_robot_task.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/delete_robot_task.go deleted file mode 100644 index 94d9b33a..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/delete_robot_task.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteRobotTask invokes the dyvmsapi.DeleteRobotTask API synchronously -func (client *Client) DeleteRobotTask(request *DeleteRobotTaskRequest) (response *DeleteRobotTaskResponse, err error) { - response = CreateDeleteRobotTaskResponse() - err = client.DoAction(request, response) - return -} - -// DeleteRobotTaskWithChan invokes the dyvmsapi.DeleteRobotTask API asynchronously -func (client *Client) DeleteRobotTaskWithChan(request *DeleteRobotTaskRequest) (<-chan *DeleteRobotTaskResponse, <-chan error) { - responseChan := make(chan *DeleteRobotTaskResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteRobotTask(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteRobotTaskWithCallback invokes the dyvmsapi.DeleteRobotTask API asynchronously -func (client *Client) DeleteRobotTaskWithCallback(request *DeleteRobotTaskRequest, callback func(response *DeleteRobotTaskResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteRobotTaskResponse - var err error - defer close(result) - response, err = client.DeleteRobotTask(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteRobotTaskRequest is the request struct for api DeleteRobotTask -type DeleteRobotTaskRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TaskId requests.Integer `position:"Query" name:"TaskId"` -} - -// DeleteRobotTaskResponse is the response struct for api DeleteRobotTask -type DeleteRobotTaskResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateDeleteRobotTaskRequest creates a request to invoke DeleteRobotTask API -func CreateDeleteRobotTaskRequest() (request *DeleteRobotTaskRequest) { - request = &DeleteRobotTaskRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "DeleteRobotTask", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateDeleteRobotTaskResponse creates a response to parse from DeleteRobotTask response -func CreateDeleteRobotTaskResponse() (response *DeleteRobotTaskResponse) { - response = &DeleteRobotTaskResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/endpoint.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/endpoint.go deleted file mode 100644 index afdb5c37..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/endpoint.go +++ /dev/null @@ -1,20 +0,0 @@ -package dyvmsapi - -// EndpointMap Endpoint Data -var EndpointMap map[string]string - -// EndpointType regional or central -var EndpointType = "central" - -// GetEndpointMap Get Endpoint Data Map -func GetEndpointMap() map[string]string { - if EndpointMap == nil { - EndpointMap = map[string]string{} - } - return EndpointMap -} - -// GetEndpointType Get Endpoint Type Value -func GetEndpointType() string { - return EndpointType -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/get_rtc_token.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/get_rtc_token.go deleted file mode 100644 index 02b968a7..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/get_rtc_token.go +++ /dev/null @@ -1,107 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// GetRtcToken invokes the dyvmsapi.GetRtcToken API synchronously -func (client *Client) GetRtcToken(request *GetRtcTokenRequest) (response *GetRtcTokenResponse, err error) { - response = CreateGetRtcTokenResponse() - err = client.DoAction(request, response) - return -} - -// GetRtcTokenWithChan invokes the dyvmsapi.GetRtcToken API asynchronously -func (client *Client) GetRtcTokenWithChan(request *GetRtcTokenRequest) (<-chan *GetRtcTokenResponse, <-chan error) { - responseChan := make(chan *GetRtcTokenResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.GetRtcToken(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// GetRtcTokenWithCallback invokes the dyvmsapi.GetRtcToken API asynchronously -func (client *Client) GetRtcTokenWithCallback(request *GetRtcTokenRequest, callback func(response *GetRtcTokenResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *GetRtcTokenResponse - var err error - defer close(result) - response, err = client.GetRtcToken(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// GetRtcTokenRequest is the request struct for api GetRtcToken -type GetRtcTokenRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - UserId string `position:"Query" name:"UserId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - DeviceId string `position:"Query" name:"DeviceId"` - IsCustomAccount requests.Boolean `position:"Query" name:"IsCustomAccount"` -} - -// GetRtcTokenResponse is the response struct for api GetRtcToken -type GetRtcTokenResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Module string `json:"Module" xml:"Module"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateGetRtcTokenRequest creates a request to invoke GetRtcToken API -func CreateGetRtcTokenRequest() (request *GetRtcTokenRequest) { - request = &GetRtcTokenRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "GetRtcToken", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateGetRtcTokenResponse creates a response to parse from GetRtcToken response -func CreateGetRtcTokenResponse() (response *GetRtcTokenResponse) { - response = &GetRtcTokenResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/ivr_call.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/ivr_call.go deleted file mode 100644 index 9efc0c19..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/ivr_call.go +++ /dev/null @@ -1,121 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// IvrCall invokes the dyvmsapi.IvrCall API synchronously -func (client *Client) IvrCall(request *IvrCallRequest) (response *IvrCallResponse, err error) { - response = CreateIvrCallResponse() - err = client.DoAction(request, response) - return -} - -// IvrCallWithChan invokes the dyvmsapi.IvrCall API asynchronously -func (client *Client) IvrCallWithChan(request *IvrCallRequest) (<-chan *IvrCallResponse, <-chan error) { - responseChan := make(chan *IvrCallResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.IvrCall(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// IvrCallWithCallback invokes the dyvmsapi.IvrCall API asynchronously -func (client *Client) IvrCallWithCallback(request *IvrCallRequest, callback func(response *IvrCallResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *IvrCallResponse - var err error - defer close(result) - response, err = client.IvrCall(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// IvrCallRequest is the request struct for api IvrCall -type IvrCallRequest struct { - *requests.RpcRequest - ByeCode string `position:"Query" name:"ByeCode"` - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - StartTtsParams string `position:"Query" name:"StartTtsParams"` - Timeout requests.Integer `position:"Query" name:"Timeout"` - StartCode string `position:"Query" name:"StartCode"` - CalledNumber string `position:"Query" name:"CalledNumber"` - CalledShowNumber string `position:"Query" name:"CalledShowNumber"` - MenuKeyMap *[]IvrCallMenuKeyMap `position:"Query" name:"MenuKeyMap" type:"Repeated"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - PlayTimes requests.Integer `position:"Query" name:"PlayTimes"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - OutId string `position:"Query" name:"OutId"` - ByeTtsParams string `position:"Query" name:"ByeTtsParams"` -} - -// IvrCallMenuKeyMap is a repeated param struct in IvrCallRequest -type IvrCallMenuKeyMap struct { - Code string `name:"Code"` - TtsParams string `name:"TtsParams"` - Key string `name:"Key"` -} - -// IvrCallResponse is the response struct for api IvrCall -type IvrCallResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - CallId string `json:"CallId" xml:"CallId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateIvrCallRequest creates a request to invoke IvrCall API -func CreateIvrCallRequest() (request *IvrCallRequest) { - request = &IvrCallRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "IvrCall", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateIvrCallResponse creates a response to parse from IvrCall response -func CreateIvrCallResponse() (response *IvrCallResponse) { - response = &IvrCallResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_call_id.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_call_id.go deleted file mode 100644 index e3e47c8a..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_call_id.go +++ /dev/null @@ -1,107 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryCallDetailByCallId invokes the dyvmsapi.QueryCallDetailByCallId API synchronously -func (client *Client) QueryCallDetailByCallId(request *QueryCallDetailByCallIdRequest) (response *QueryCallDetailByCallIdResponse, err error) { - response = CreateQueryCallDetailByCallIdResponse() - err = client.DoAction(request, response) - return -} - -// QueryCallDetailByCallIdWithChan invokes the dyvmsapi.QueryCallDetailByCallId API asynchronously -func (client *Client) QueryCallDetailByCallIdWithChan(request *QueryCallDetailByCallIdRequest) (<-chan *QueryCallDetailByCallIdResponse, <-chan error) { - responseChan := make(chan *QueryCallDetailByCallIdResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryCallDetailByCallId(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryCallDetailByCallIdWithCallback invokes the dyvmsapi.QueryCallDetailByCallId API asynchronously -func (client *Client) QueryCallDetailByCallIdWithCallback(request *QueryCallDetailByCallIdRequest, callback func(response *QueryCallDetailByCallIdResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryCallDetailByCallIdResponse - var err error - defer close(result) - response, err = client.QueryCallDetailByCallId(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryCallDetailByCallIdRequest is the request struct for api QueryCallDetailByCallId -type QueryCallDetailByCallIdRequest struct { - *requests.RpcRequest - CallId string `position:"Query" name:"CallId"` - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - QueryDate requests.Integer `position:"Query" name:"QueryDate"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - ProdId requests.Integer `position:"Query" name:"ProdId"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` -} - -// QueryCallDetailByCallIdResponse is the response struct for api QueryCallDetailByCallId -type QueryCallDetailByCallIdResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryCallDetailByCallIdRequest creates a request to invoke QueryCallDetailByCallId API -func CreateQueryCallDetailByCallIdRequest() (request *QueryCallDetailByCallIdRequest) { - request = &QueryCallDetailByCallIdRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryCallDetailByCallId", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryCallDetailByCallIdResponse creates a response to parse from QueryCallDetailByCallId response -func CreateQueryCallDetailByCallIdResponse() (response *QueryCallDetailByCallIdResponse) { - response = &QueryCallDetailByCallIdResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_task_id.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_task_id.go deleted file mode 100644 index 45151ba1..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_call_detail_by_task_id.go +++ /dev/null @@ -1,107 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryCallDetailByTaskId invokes the dyvmsapi.QueryCallDetailByTaskId API synchronously -func (client *Client) QueryCallDetailByTaskId(request *QueryCallDetailByTaskIdRequest) (response *QueryCallDetailByTaskIdResponse, err error) { - response = CreateQueryCallDetailByTaskIdResponse() - err = client.DoAction(request, response) - return -} - -// QueryCallDetailByTaskIdWithChan invokes the dyvmsapi.QueryCallDetailByTaskId API asynchronously -func (client *Client) QueryCallDetailByTaskIdWithChan(request *QueryCallDetailByTaskIdRequest) (<-chan *QueryCallDetailByTaskIdResponse, <-chan error) { - responseChan := make(chan *QueryCallDetailByTaskIdResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryCallDetailByTaskId(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryCallDetailByTaskIdWithCallback invokes the dyvmsapi.QueryCallDetailByTaskId API asynchronously -func (client *Client) QueryCallDetailByTaskIdWithCallback(request *QueryCallDetailByTaskIdRequest, callback func(response *QueryCallDetailByTaskIdResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryCallDetailByTaskIdResponse - var err error - defer close(result) - response, err = client.QueryCallDetailByTaskId(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryCallDetailByTaskIdRequest is the request struct for api QueryCallDetailByTaskId -type QueryCallDetailByTaskIdRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Callee string `position:"Query" name:"Callee"` - TaskId string `position:"Query" name:"TaskId"` - QueryDate requests.Integer `position:"Query" name:"QueryDate"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` -} - -// QueryCallDetailByTaskIdResponse is the response struct for api QueryCallDetailByTaskId -type QueryCallDetailByTaskIdResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryCallDetailByTaskIdRequest creates a request to invoke QueryCallDetailByTaskId API -func CreateQueryCallDetailByTaskIdRequest() (request *QueryCallDetailByTaskIdRequest) { - request = &QueryCallDetailByTaskIdRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryCallDetailByTaskId", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryCallDetailByTaskIdResponse creates a response to parse from QueryCallDetailByTaskId response -func CreateQueryCallDetailByTaskIdResponse() (response *QueryCallDetailByTaskIdResponse) { - response = &QueryCallDetailByTaskIdResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_info_list.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_info_list.go deleted file mode 100644 index 56e0266a..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_info_list.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryRobotInfoList invokes the dyvmsapi.QueryRobotInfoList API synchronously -func (client *Client) QueryRobotInfoList(request *QueryRobotInfoListRequest) (response *QueryRobotInfoListResponse, err error) { - response = CreateQueryRobotInfoListResponse() - err = client.DoAction(request, response) - return -} - -// QueryRobotInfoListWithChan invokes the dyvmsapi.QueryRobotInfoList API asynchronously -func (client *Client) QueryRobotInfoListWithChan(request *QueryRobotInfoListRequest) (<-chan *QueryRobotInfoListResponse, <-chan error) { - responseChan := make(chan *QueryRobotInfoListResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryRobotInfoList(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryRobotInfoListWithCallback invokes the dyvmsapi.QueryRobotInfoList API asynchronously -func (client *Client) QueryRobotInfoListWithCallback(request *QueryRobotInfoListRequest, callback func(response *QueryRobotInfoListResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryRobotInfoListResponse - var err error - defer close(result) - response, err = client.QueryRobotInfoList(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryRobotInfoListRequest is the request struct for api QueryRobotInfoList -type QueryRobotInfoListRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - AuditStatus string `position:"Query" name:"AuditStatus"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` -} - -// QueryRobotInfoListResponse is the response struct for api QueryRobotInfoList -type QueryRobotInfoListResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryRobotInfoListRequest creates a request to invoke QueryRobotInfoList API -func CreateQueryRobotInfoListRequest() (request *QueryRobotInfoListRequest) { - request = &QueryRobotInfoListRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryRobotInfoList", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryRobotInfoListResponse creates a response to parse from QueryRobotInfoList response -func CreateQueryRobotInfoListResponse() (response *QueryRobotInfoListResponse) { - response = &QueryRobotInfoListResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_detail.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_detail.go deleted file mode 100644 index 6ca960bc..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_detail.go +++ /dev/null @@ -1,107 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryRobotTaskCallDetail invokes the dyvmsapi.QueryRobotTaskCallDetail API synchronously -func (client *Client) QueryRobotTaskCallDetail(request *QueryRobotTaskCallDetailRequest) (response *QueryRobotTaskCallDetailResponse, err error) { - response = CreateQueryRobotTaskCallDetailResponse() - err = client.DoAction(request, response) - return -} - -// QueryRobotTaskCallDetailWithChan invokes the dyvmsapi.QueryRobotTaskCallDetail API asynchronously -func (client *Client) QueryRobotTaskCallDetailWithChan(request *QueryRobotTaskCallDetailRequest) (<-chan *QueryRobotTaskCallDetailResponse, <-chan error) { - responseChan := make(chan *QueryRobotTaskCallDetailResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryRobotTaskCallDetail(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryRobotTaskCallDetailWithCallback invokes the dyvmsapi.QueryRobotTaskCallDetail API asynchronously -func (client *Client) QueryRobotTaskCallDetailWithCallback(request *QueryRobotTaskCallDetailRequest, callback func(response *QueryRobotTaskCallDetailResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryRobotTaskCallDetailResponse - var err error - defer close(result) - response, err = client.QueryRobotTaskCallDetail(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryRobotTaskCallDetailRequest is the request struct for api QueryRobotTaskCallDetail -type QueryRobotTaskCallDetailRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Callee string `position:"Query" name:"Callee"` - TaskId requests.Integer `position:"Query" name:"TaskId"` - QueryDate requests.Integer `position:"Query" name:"QueryDate"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` -} - -// QueryRobotTaskCallDetailResponse is the response struct for api QueryRobotTaskCallDetail -type QueryRobotTaskCallDetailResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryRobotTaskCallDetailRequest creates a request to invoke QueryRobotTaskCallDetail API -func CreateQueryRobotTaskCallDetailRequest() (request *QueryRobotTaskCallDetailRequest) { - request = &QueryRobotTaskCallDetailRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryRobotTaskCallDetail", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryRobotTaskCallDetailResponse creates a response to parse from QueryRobotTaskCallDetail response -func CreateQueryRobotTaskCallDetailResponse() (response *QueryRobotTaskCallDetailResponse) { - response = &QueryRobotTaskCallDetailResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_list.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_list.go deleted file mode 100644 index c31fa046..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_call_list.go +++ /dev/null @@ -1,114 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryRobotTaskCallList invokes the dyvmsapi.QueryRobotTaskCallList API synchronously -func (client *Client) QueryRobotTaskCallList(request *QueryRobotTaskCallListRequest) (response *QueryRobotTaskCallListResponse, err error) { - response = CreateQueryRobotTaskCallListResponse() - err = client.DoAction(request, response) - return -} - -// QueryRobotTaskCallListWithChan invokes the dyvmsapi.QueryRobotTaskCallList API asynchronously -func (client *Client) QueryRobotTaskCallListWithChan(request *QueryRobotTaskCallListRequest) (<-chan *QueryRobotTaskCallListResponse, <-chan error) { - responseChan := make(chan *QueryRobotTaskCallListResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryRobotTaskCallList(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryRobotTaskCallListWithCallback invokes the dyvmsapi.QueryRobotTaskCallList API asynchronously -func (client *Client) QueryRobotTaskCallListWithCallback(request *QueryRobotTaskCallListRequest, callback func(response *QueryRobotTaskCallListResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryRobotTaskCallListResponse - var err error - defer close(result) - response, err = client.QueryRobotTaskCallList(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryRobotTaskCallListRequest is the request struct for api QueryRobotTaskCallList -type QueryRobotTaskCallListRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Called string `position:"Query" name:"Called"` - DialogCountTo string `position:"Query" name:"DialogCountTo"` - DurationFrom string `position:"Query" name:"DurationFrom"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - TaskId string `position:"Query" name:"TaskId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - DialogCountFrom string `position:"Query" name:"DialogCountFrom"` - DurationTo string `position:"Query" name:"DurationTo"` - HangupDirection string `position:"Query" name:"HangupDirection"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - PageNo requests.Integer `position:"Query" name:"PageNo"` - CallResult string `position:"Query" name:"CallResult"` -} - -// QueryRobotTaskCallListResponse is the response struct for api QueryRobotTaskCallList -type QueryRobotTaskCallListResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryRobotTaskCallListRequest creates a request to invoke QueryRobotTaskCallList API -func CreateQueryRobotTaskCallListRequest() (request *QueryRobotTaskCallListRequest) { - request = &QueryRobotTaskCallListRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryRobotTaskCallList", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryRobotTaskCallListResponse creates a response to parse from QueryRobotTaskCallList response -func CreateQueryRobotTaskCallListResponse() (response *QueryRobotTaskCallListResponse) { - response = &QueryRobotTaskCallListResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_detail.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_detail.go deleted file mode 100644 index 02ee6469..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_detail.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryRobotTaskDetail invokes the dyvmsapi.QueryRobotTaskDetail API synchronously -func (client *Client) QueryRobotTaskDetail(request *QueryRobotTaskDetailRequest) (response *QueryRobotTaskDetailResponse, err error) { - response = CreateQueryRobotTaskDetailResponse() - err = client.DoAction(request, response) - return -} - -// QueryRobotTaskDetailWithChan invokes the dyvmsapi.QueryRobotTaskDetail API asynchronously -func (client *Client) QueryRobotTaskDetailWithChan(request *QueryRobotTaskDetailRequest) (<-chan *QueryRobotTaskDetailResponse, <-chan error) { - responseChan := make(chan *QueryRobotTaskDetailResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryRobotTaskDetail(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryRobotTaskDetailWithCallback invokes the dyvmsapi.QueryRobotTaskDetail API asynchronously -func (client *Client) QueryRobotTaskDetailWithCallback(request *QueryRobotTaskDetailRequest, callback func(response *QueryRobotTaskDetailResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryRobotTaskDetailResponse - var err error - defer close(result) - response, err = client.QueryRobotTaskDetail(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryRobotTaskDetailRequest is the request struct for api QueryRobotTaskDetail -type QueryRobotTaskDetailRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - Id requests.Integer `position:"Query" name:"Id"` -} - -// QueryRobotTaskDetailResponse is the response struct for api QueryRobotTaskDetail -type QueryRobotTaskDetailResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryRobotTaskDetailRequest creates a request to invoke QueryRobotTaskDetail API -func CreateQueryRobotTaskDetailRequest() (request *QueryRobotTaskDetailRequest) { - request = &QueryRobotTaskDetailRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryRobotTaskDetail", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryRobotTaskDetailResponse creates a response to parse from QueryRobotTaskDetail response -func CreateQueryRobotTaskDetailResponse() (response *QueryRobotTaskDetailResponse) { - response = &QueryRobotTaskDetailResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_list.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_list.go deleted file mode 100644 index 73bcac36..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robot_task_list.go +++ /dev/null @@ -1,112 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryRobotTaskList invokes the dyvmsapi.QueryRobotTaskList API synchronously -func (client *Client) QueryRobotTaskList(request *QueryRobotTaskListRequest) (response *QueryRobotTaskListResponse, err error) { - response = CreateQueryRobotTaskListResponse() - err = client.DoAction(request, response) - return -} - -// QueryRobotTaskListWithChan invokes the dyvmsapi.QueryRobotTaskList API asynchronously -func (client *Client) QueryRobotTaskListWithChan(request *QueryRobotTaskListRequest) (<-chan *QueryRobotTaskListResponse, <-chan error) { - responseChan := make(chan *QueryRobotTaskListResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryRobotTaskList(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryRobotTaskListWithCallback invokes the dyvmsapi.QueryRobotTaskList API asynchronously -func (client *Client) QueryRobotTaskListWithCallback(request *QueryRobotTaskListRequest, callback func(response *QueryRobotTaskListResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryRobotTaskListResponse - var err error - defer close(result) - response, err = client.QueryRobotTaskList(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryRobotTaskListRequest is the request struct for api QueryRobotTaskList -type QueryRobotTaskListRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - TaskName string `position:"Query" name:"TaskName"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - PageNo requests.Integer `position:"Query" name:"PageNo"` - Time string `position:"Query" name:"Time"` - Status string `position:"Query" name:"Status"` -} - -// QueryRobotTaskListResponse is the response struct for api QueryRobotTaskList -type QueryRobotTaskListResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - PageSize string `json:"PageSize" xml:"PageSize"` - PageNo string `json:"PageNo" xml:"PageNo"` - TotalCount string `json:"TotalCount" xml:"TotalCount"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryRobotTaskListRequest creates a request to invoke QueryRobotTaskList API -func CreateQueryRobotTaskListRequest() (request *QueryRobotTaskListRequest) { - request = &QueryRobotTaskListRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryRobotTaskList", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryRobotTaskListResponse creates a response to parse from QueryRobotTaskList response -func CreateQueryRobotTaskListResponse() (response *QueryRobotTaskListResponse) { - response = &QueryRobotTaskListResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robotv2_all_list.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robotv2_all_list.go deleted file mode 100644 index c02f5ccd..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_robotv2_all_list.go +++ /dev/null @@ -1,104 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryRobotv2AllList invokes the dyvmsapi.QueryRobotv2AllList API synchronously -func (client *Client) QueryRobotv2AllList(request *QueryRobotv2AllListRequest) (response *QueryRobotv2AllListResponse, err error) { - response = CreateQueryRobotv2AllListResponse() - err = client.DoAction(request, response) - return -} - -// QueryRobotv2AllListWithChan invokes the dyvmsapi.QueryRobotv2AllList API asynchronously -func (client *Client) QueryRobotv2AllListWithChan(request *QueryRobotv2AllListRequest) (<-chan *QueryRobotv2AllListResponse, <-chan error) { - responseChan := make(chan *QueryRobotv2AllListResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryRobotv2AllList(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryRobotv2AllListWithCallback invokes the dyvmsapi.QueryRobotv2AllList API asynchronously -func (client *Client) QueryRobotv2AllListWithCallback(request *QueryRobotv2AllListRequest, callback func(response *QueryRobotv2AllListResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryRobotv2AllListResponse - var err error - defer close(result) - response, err = client.QueryRobotv2AllList(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryRobotv2AllListRequest is the request struct for api QueryRobotv2AllList -type QueryRobotv2AllListRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` -} - -// QueryRobotv2AllListResponse is the response struct for api QueryRobotv2AllList -type QueryRobotv2AllListResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryRobotv2AllListRequest creates a request to invoke QueryRobotv2AllList API -func CreateQueryRobotv2AllListRequest() (request *QueryRobotv2AllListRequest) { - request = &QueryRobotv2AllListRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryRobotv2AllList", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryRobotv2AllListResponse creates a response to parse from QueryRobotv2AllList response -func CreateQueryRobotv2AllListResponse() (response *QueryRobotv2AllListResponse) { - response = &QueryRobotv2AllListResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_voip_number_bind_infos.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_voip_number_bind_infos.go deleted file mode 100644 index 30fd776b..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/query_voip_number_bind_infos.go +++ /dev/null @@ -1,106 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// QueryVoipNumberBindInfos invokes the dyvmsapi.QueryVoipNumberBindInfos API synchronously -func (client *Client) QueryVoipNumberBindInfos(request *QueryVoipNumberBindInfosRequest) (response *QueryVoipNumberBindInfosResponse, err error) { - response = CreateQueryVoipNumberBindInfosResponse() - err = client.DoAction(request, response) - return -} - -// QueryVoipNumberBindInfosWithChan invokes the dyvmsapi.QueryVoipNumberBindInfos API asynchronously -func (client *Client) QueryVoipNumberBindInfosWithChan(request *QueryVoipNumberBindInfosRequest) (<-chan *QueryVoipNumberBindInfosResponse, <-chan error) { - responseChan := make(chan *QueryVoipNumberBindInfosResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.QueryVoipNumberBindInfos(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// QueryVoipNumberBindInfosWithCallback invokes the dyvmsapi.QueryVoipNumberBindInfos API asynchronously -func (client *Client) QueryVoipNumberBindInfosWithCallback(request *QueryVoipNumberBindInfosRequest, callback func(response *QueryVoipNumberBindInfosResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *QueryVoipNumberBindInfosResponse - var err error - defer close(result) - response, err = client.QueryVoipNumberBindInfos(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// QueryVoipNumberBindInfosRequest is the request struct for api QueryVoipNumberBindInfos -type QueryVoipNumberBindInfosRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - PhoneNumber string `position:"Query" name:"PhoneNumber"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - VoipId string `position:"Query" name:"VoipId"` -} - -// QueryVoipNumberBindInfosResponse is the response struct for api QueryVoipNumberBindInfos -type QueryVoipNumberBindInfosResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Module string `json:"Module" xml:"Module"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateQueryVoipNumberBindInfosRequest creates a request to invoke QueryVoipNumberBindInfos API -func CreateQueryVoipNumberBindInfosRequest() (request *QueryVoipNumberBindInfosRequest) { - request = &QueryVoipNumberBindInfosRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "QueryVoipNumberBindInfos", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateQueryVoipNumberBindInfosResponse creates a response to parse from QueryVoipNumberBindInfos response -func CreateQueryVoipNumberBindInfosResponse() (response *QueryVoipNumberBindInfosResponse) { - response = &QueryVoipNumberBindInfosResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/report_voip_problems.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/report_voip_problems.go deleted file mode 100644 index 290d92b4..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/report_voip_problems.go +++ /dev/null @@ -1,108 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ReportVoipProblems invokes the dyvmsapi.ReportVoipProblems API synchronously -func (client *Client) ReportVoipProblems(request *ReportVoipProblemsRequest) (response *ReportVoipProblemsResponse, err error) { - response = CreateReportVoipProblemsResponse() - err = client.DoAction(request, response) - return -} - -// ReportVoipProblemsWithChan invokes the dyvmsapi.ReportVoipProblems API asynchronously -func (client *Client) ReportVoipProblemsWithChan(request *ReportVoipProblemsRequest) (<-chan *ReportVoipProblemsResponse, <-chan error) { - responseChan := make(chan *ReportVoipProblemsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ReportVoipProblems(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ReportVoipProblemsWithCallback invokes the dyvmsapi.ReportVoipProblems API asynchronously -func (client *Client) ReportVoipProblemsWithCallback(request *ReportVoipProblemsRequest, callback func(response *ReportVoipProblemsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ReportVoipProblemsResponse - var err error - defer close(result) - response, err = client.ReportVoipProblems(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ReportVoipProblemsRequest is the request struct for api ReportVoipProblems -type ReportVoipProblemsRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Title string `position:"Query" name:"Title"` - VoipId string `position:"Query" name:"VoipId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - ChannelId string `position:"Query" name:"ChannelId"` - Desc string `position:"Query" name:"Desc"` -} - -// ReportVoipProblemsResponse is the response struct for api ReportVoipProblems -type ReportVoipProblemsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Code string `json:"Code" xml:"Code"` - Module string `json:"Module" xml:"Module"` - Message string `json:"Message" xml:"Message"` -} - -// CreateReportVoipProblemsRequest creates a request to invoke ReportVoipProblems API -func CreateReportVoipProblemsRequest() (request *ReportVoipProblemsRequest) { - request = &ReportVoipProblemsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "ReportVoipProblems", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateReportVoipProblemsResponse creates a response to parse from ReportVoipProblems response -func CreateReportVoipProblemsResponse() (response *ReportVoipProblemsResponse) { - response = &ReportVoipProblemsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_tts.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_tts.go deleted file mode 100644 index a0342a38..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_tts.go +++ /dev/null @@ -1,112 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SingleCallByTts invokes the dyvmsapi.SingleCallByTts API synchronously -func (client *Client) SingleCallByTts(request *SingleCallByTtsRequest) (response *SingleCallByTtsResponse, err error) { - response = CreateSingleCallByTtsResponse() - err = client.DoAction(request, response) - return -} - -// SingleCallByTtsWithChan invokes the dyvmsapi.SingleCallByTts API asynchronously -func (client *Client) SingleCallByTtsWithChan(request *SingleCallByTtsRequest) (<-chan *SingleCallByTtsResponse, <-chan error) { - responseChan := make(chan *SingleCallByTtsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SingleCallByTts(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SingleCallByTtsWithCallback invokes the dyvmsapi.SingleCallByTts API asynchronously -func (client *Client) SingleCallByTtsWithCallback(request *SingleCallByTtsRequest, callback func(response *SingleCallByTtsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SingleCallByTtsResponse - var err error - defer close(result) - response, err = client.SingleCallByTts(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SingleCallByTtsRequest is the request struct for api SingleCallByTts -type SingleCallByTtsRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - TtsParam string `position:"Query" name:"TtsParam"` - Speed requests.Integer `position:"Query" name:"Speed"` - CalledNumber string `position:"Query" name:"CalledNumber"` - CalledShowNumber string `position:"Query" name:"CalledShowNumber"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - TtsCode string `position:"Query" name:"TtsCode"` - PlayTimes requests.Integer `position:"Query" name:"PlayTimes"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - Volume requests.Integer `position:"Query" name:"Volume"` - OutId string `position:"Query" name:"OutId"` -} - -// SingleCallByTtsResponse is the response struct for api SingleCallByTts -type SingleCallByTtsResponse struct { - *responses.BaseResponse - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` - RequestId string `json:"RequestId" xml:"RequestId"` - CallId string `json:"CallId" xml:"CallId"` -} - -// CreateSingleCallByTtsRequest creates a request to invoke SingleCallByTts API -func CreateSingleCallByTtsRequest() (request *SingleCallByTtsRequest) { - request = &SingleCallByTtsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "SingleCallByTts", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateSingleCallByTtsResponse creates a response to parse from SingleCallByTts response -func CreateSingleCallByTtsResponse() (response *SingleCallByTtsResponse) { - response = &SingleCallByTtsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_voice.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_voice.go deleted file mode 100644 index 4fe0b508..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/single_call_by_voice.go +++ /dev/null @@ -1,111 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SingleCallByVoice invokes the dyvmsapi.SingleCallByVoice API synchronously -func (client *Client) SingleCallByVoice(request *SingleCallByVoiceRequest) (response *SingleCallByVoiceResponse, err error) { - response = CreateSingleCallByVoiceResponse() - err = client.DoAction(request, response) - return -} - -// SingleCallByVoiceWithChan invokes the dyvmsapi.SingleCallByVoice API asynchronously -func (client *Client) SingleCallByVoiceWithChan(request *SingleCallByVoiceRequest) (<-chan *SingleCallByVoiceResponse, <-chan error) { - responseChan := make(chan *SingleCallByVoiceResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SingleCallByVoice(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SingleCallByVoiceWithCallback invokes the dyvmsapi.SingleCallByVoice API asynchronously -func (client *Client) SingleCallByVoiceWithCallback(request *SingleCallByVoiceRequest, callback func(response *SingleCallByVoiceResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SingleCallByVoiceResponse - var err error - defer close(result) - response, err = client.SingleCallByVoice(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SingleCallByVoiceRequest is the request struct for api SingleCallByVoice -type SingleCallByVoiceRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Speed requests.Integer `position:"Query" name:"Speed"` - CalledNumber string `position:"Query" name:"CalledNumber"` - VoiceCode string `position:"Query" name:"VoiceCode"` - CalledShowNumber string `position:"Query" name:"CalledShowNumber"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - PlayTimes requests.Integer `position:"Query" name:"PlayTimes"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - Volume requests.Integer `position:"Query" name:"Volume"` - OutId string `position:"Query" name:"OutId"` -} - -// SingleCallByVoiceResponse is the response struct for api SingleCallByVoice -type SingleCallByVoiceResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - CallId string `json:"CallId" xml:"CallId"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateSingleCallByVoiceRequest creates a request to invoke SingleCallByVoice API -func CreateSingleCallByVoiceRequest() (request *SingleCallByVoiceRequest) { - request = &SingleCallByVoiceRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "SingleCallByVoice", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateSingleCallByVoiceResponse creates a response to parse from SingleCallByVoice response -func CreateSingleCallByVoiceResponse() (response *SingleCallByVoiceResponse) { - response = &SingleCallByVoiceResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call.go deleted file mode 100644 index 930bbb98..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call.go +++ /dev/null @@ -1,130 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SmartCall invokes the dyvmsapi.SmartCall API synchronously -func (client *Client) SmartCall(request *SmartCallRequest) (response *SmartCallResponse, err error) { - response = CreateSmartCallResponse() - err = client.DoAction(request, response) - return -} - -// SmartCallWithChan invokes the dyvmsapi.SmartCall API asynchronously -func (client *Client) SmartCallWithChan(request *SmartCallRequest) (<-chan *SmartCallResponse, <-chan error) { - responseChan := make(chan *SmartCallResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SmartCall(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SmartCallWithCallback invokes the dyvmsapi.SmartCall API asynchronously -func (client *Client) SmartCallWithCallback(request *SmartCallRequest, callback func(response *SmartCallResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SmartCallResponse - var err error - defer close(result) - response, err = client.SmartCall(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SmartCallRequest is the request struct for api SmartCall -type SmartCallRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - VoiceCodeParam string `position:"Query" name:"VoiceCodeParam"` - EarlyMediaAsr requests.Boolean `position:"Query" name:"EarlyMediaAsr"` - BackgroundSpeed requests.Integer `position:"Query" name:"BackgroundSpeed"` - BackgroundVolume requests.Integer `position:"Query" name:"BackgroundVolume"` - Speed requests.Integer `position:"Query" name:"Speed"` - AsrBaseId string `position:"Query" name:"AsrBaseId"` - SessionTimeout requests.Integer `position:"Query" name:"SessionTimeout"` - DynamicId string `position:"Query" name:"DynamicId"` - CalledNumber string `position:"Query" name:"CalledNumber"` - TtsSpeed requests.Integer `position:"Query" name:"TtsSpeed"` - VoiceCode string `position:"Query" name:"VoiceCode"` - CalledShowNumber string `position:"Query" name:"CalledShowNumber"` - EnableITN requests.Boolean `position:"Query" name:"EnableITN"` - ActionCodeTimeBreak requests.Integer `position:"Query" name:"ActionCodeTimeBreak"` - TtsConf requests.Boolean `position:"Query" name:"TtsConf"` - ActionCodeBreak requests.Boolean `position:"Query" name:"ActionCodeBreak"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - RecordFlag requests.Boolean `position:"Query" name:"RecordFlag"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TtsVolume requests.Integer `position:"Query" name:"TtsVolume"` - StreamAsr requests.Integer `position:"Query" name:"StreamAsr"` - Volume requests.Integer `position:"Query" name:"Volume"` - MuteTime requests.Integer `position:"Query" name:"MuteTime"` - BackgroundFileCode string `position:"Query" name:"BackgroundFileCode"` - OutId string `position:"Query" name:"OutId"` - AsrModelId string `position:"Query" name:"AsrModelId"` - PauseTime requests.Integer `position:"Query" name:"PauseTime"` - TtsStyle string `position:"Query" name:"TtsStyle"` -} - -// SmartCallResponse is the response struct for api SmartCall -type SmartCallResponse struct { - *responses.BaseResponse - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` - RequestId string `json:"RequestId" xml:"RequestId"` - CallId string `json:"CallId" xml:"CallId"` -} - -// CreateSmartCallRequest creates a request to invoke SmartCall API -func CreateSmartCallRequest() (request *SmartCallRequest) { - request = &SmartCallRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "SmartCall", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateSmartCallResponse creates a response to parse from SmartCall response -func CreateSmartCallResponse() (response *SmartCallResponse) { - response = &SmartCallResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call_operate.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call_operate.go deleted file mode 100644 index 7a38cc86..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/smart_call_operate.go +++ /dev/null @@ -1,107 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SmartCallOperate invokes the dyvmsapi.SmartCallOperate API synchronously -func (client *Client) SmartCallOperate(request *SmartCallOperateRequest) (response *SmartCallOperateResponse, err error) { - response = CreateSmartCallOperateResponse() - err = client.DoAction(request, response) - return -} - -// SmartCallOperateWithChan invokes the dyvmsapi.SmartCallOperate API asynchronously -func (client *Client) SmartCallOperateWithChan(request *SmartCallOperateRequest) (<-chan *SmartCallOperateResponse, <-chan error) { - responseChan := make(chan *SmartCallOperateResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SmartCallOperate(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SmartCallOperateWithCallback invokes the dyvmsapi.SmartCallOperate API asynchronously -func (client *Client) SmartCallOperateWithCallback(request *SmartCallOperateRequest, callback func(response *SmartCallOperateResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SmartCallOperateResponse - var err error - defer close(result) - response, err = client.SmartCallOperate(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SmartCallOperateRequest is the request struct for api SmartCallOperate -type SmartCallOperateRequest struct { - *requests.RpcRequest - CallId string `position:"Query" name:"CallId"` - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - Param string `position:"Query" name:"Param"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - Command string `position:"Query" name:"Command"` -} - -// SmartCallOperateResponse is the response struct for api SmartCallOperate -type SmartCallOperateResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Status bool `json:"Status" xml:"Status"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateSmartCallOperateRequest creates a request to invoke SmartCallOperate API -func CreateSmartCallOperateRequest() (request *SmartCallOperateRequest) { - request = &SmartCallOperateRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "SmartCallOperate", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateSmartCallOperateResponse creates a response to parse from SmartCallOperate response -func CreateSmartCallOperateResponse() (response *SmartCallOperateResponse) { - response = &SmartCallOperateResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/start_robot_task.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/start_robot_task.go deleted file mode 100644 index a7a0cdb9..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/start_robot_task.go +++ /dev/null @@ -1,106 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// StartRobotTask invokes the dyvmsapi.StartRobotTask API synchronously -func (client *Client) StartRobotTask(request *StartRobotTaskRequest) (response *StartRobotTaskResponse, err error) { - response = CreateStartRobotTaskResponse() - err = client.DoAction(request, response) - return -} - -// StartRobotTaskWithChan invokes the dyvmsapi.StartRobotTask API asynchronously -func (client *Client) StartRobotTaskWithChan(request *StartRobotTaskRequest) (<-chan *StartRobotTaskResponse, <-chan error) { - responseChan := make(chan *StartRobotTaskResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.StartRobotTask(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// StartRobotTaskWithCallback invokes the dyvmsapi.StartRobotTask API asynchronously -func (client *Client) StartRobotTaskWithCallback(request *StartRobotTaskRequest, callback func(response *StartRobotTaskResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *StartRobotTaskResponse - var err error - defer close(result) - response, err = client.StartRobotTask(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// StartRobotTaskRequest is the request struct for api StartRobotTask -type StartRobotTaskRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - ScheduleTime string `position:"Query" name:"ScheduleTime"` - TaskId requests.Integer `position:"Query" name:"TaskId"` -} - -// StartRobotTaskResponse is the response struct for api StartRobotTask -type StartRobotTaskResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateStartRobotTaskRequest creates a request to invoke StartRobotTask API -func CreateStartRobotTaskRequest() (request *StartRobotTaskRequest) { - request = &StartRobotTaskRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "StartRobotTask", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateStartRobotTaskResponse creates a response to parse from StartRobotTask response -func CreateStartRobotTaskResponse() (response *StartRobotTaskResponse) { - response = &StartRobotTaskResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/stop_robot_task.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/stop_robot_task.go deleted file mode 100644 index 0ffce725..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/stop_robot_task.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// StopRobotTask invokes the dyvmsapi.StopRobotTask API synchronously -func (client *Client) StopRobotTask(request *StopRobotTaskRequest) (response *StopRobotTaskResponse, err error) { - response = CreateStopRobotTaskResponse() - err = client.DoAction(request, response) - return -} - -// StopRobotTaskWithChan invokes the dyvmsapi.StopRobotTask API asynchronously -func (client *Client) StopRobotTaskWithChan(request *StopRobotTaskRequest) (<-chan *StopRobotTaskResponse, <-chan error) { - responseChan := make(chan *StopRobotTaskResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.StopRobotTask(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// StopRobotTaskWithCallback invokes the dyvmsapi.StopRobotTask API asynchronously -func (client *Client) StopRobotTaskWithCallback(request *StopRobotTaskRequest, callback func(response *StopRobotTaskResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *StopRobotTaskResponse - var err error - defer close(result) - response, err = client.StopRobotTask(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// StopRobotTaskRequest is the request struct for api StopRobotTask -type StopRobotTaskRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - TaskId requests.Integer `position:"Query" name:"TaskId"` -} - -// StopRobotTaskResponse is the response struct for api StopRobotTask -type StopRobotTaskResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateStopRobotTaskRequest creates a request to invoke StopRobotTask API -func CreateStopRobotTaskRequest() (request *StopRobotTaskRequest) { - request = &StopRobotTaskRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "StopRobotTask", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateStopRobotTaskResponse creates a response to parse from StopRobotTask response -func CreateStopRobotTaskResponse() (response *StopRobotTaskResponse) { - response = &StopRobotTaskResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/unbind_number_and_voip_id.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/unbind_number_and_voip_id.go deleted file mode 100644 index d07a4ad1..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/unbind_number_and_voip_id.go +++ /dev/null @@ -1,106 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UnbindNumberAndVoipId invokes the dyvmsapi.UnbindNumberAndVoipId API synchronously -func (client *Client) UnbindNumberAndVoipId(request *UnbindNumberAndVoipIdRequest) (response *UnbindNumberAndVoipIdResponse, err error) { - response = CreateUnbindNumberAndVoipIdResponse() - err = client.DoAction(request, response) - return -} - -// UnbindNumberAndVoipIdWithChan invokes the dyvmsapi.UnbindNumberAndVoipId API asynchronously -func (client *Client) UnbindNumberAndVoipIdWithChan(request *UnbindNumberAndVoipIdRequest) (<-chan *UnbindNumberAndVoipIdResponse, <-chan error) { - responseChan := make(chan *UnbindNumberAndVoipIdResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UnbindNumberAndVoipId(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UnbindNumberAndVoipIdWithCallback invokes the dyvmsapi.UnbindNumberAndVoipId API asynchronously -func (client *Client) UnbindNumberAndVoipIdWithCallback(request *UnbindNumberAndVoipIdRequest, callback func(response *UnbindNumberAndVoipIdResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UnbindNumberAndVoipIdResponse - var err error - defer close(result) - response, err = client.UnbindNumberAndVoipId(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UnbindNumberAndVoipIdRequest is the request struct for api UnbindNumberAndVoipId -type UnbindNumberAndVoipIdRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - PhoneNumber string `position:"Query" name:"PhoneNumber"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - VoipId string `position:"Query" name:"VoipId"` -} - -// UnbindNumberAndVoipIdResponse is the response struct for api UnbindNumberAndVoipId -type UnbindNumberAndVoipIdResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Code string `json:"Code" xml:"Code"` - Module string `json:"Module" xml:"Module"` - Message string `json:"Message" xml:"Message"` -} - -// CreateUnbindNumberAndVoipIdRequest creates a request to invoke UnbindNumberAndVoipId API -func CreateUnbindNumberAndVoipIdRequest() (request *UnbindNumberAndVoipIdRequest) { - request = &UnbindNumberAndVoipIdRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "UnbindNumberAndVoipId", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateUnbindNumberAndVoipIdResponse creates a response to parse from UnbindNumberAndVoipId response -func CreateUnbindNumberAndVoipIdResponse() (response *UnbindNumberAndVoipIdResponse) { - response = &UnbindNumberAndVoipIdResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/upload_robot_task_called_file.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/upload_robot_task_called_file.go deleted file mode 100644 index af085ed5..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/upload_robot_task_called_file.go +++ /dev/null @@ -1,108 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UploadRobotTaskCalledFile invokes the dyvmsapi.UploadRobotTaskCalledFile API synchronously -func (client *Client) UploadRobotTaskCalledFile(request *UploadRobotTaskCalledFileRequest) (response *UploadRobotTaskCalledFileResponse, err error) { - response = CreateUploadRobotTaskCalledFileResponse() - err = client.DoAction(request, response) - return -} - -// UploadRobotTaskCalledFileWithChan invokes the dyvmsapi.UploadRobotTaskCalledFile API asynchronously -func (client *Client) UploadRobotTaskCalledFileWithChan(request *UploadRobotTaskCalledFileRequest) (<-chan *UploadRobotTaskCalledFileResponse, <-chan error) { - responseChan := make(chan *UploadRobotTaskCalledFileResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UploadRobotTaskCalledFile(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UploadRobotTaskCalledFileWithCallback invokes the dyvmsapi.UploadRobotTaskCalledFile API asynchronously -func (client *Client) UploadRobotTaskCalledFileWithCallback(request *UploadRobotTaskCalledFileRequest, callback func(response *UploadRobotTaskCalledFileResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UploadRobotTaskCalledFileResponse - var err error - defer close(result) - response, err = client.UploadRobotTaskCalledFile(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UploadRobotTaskCalledFileRequest is the request struct for api UploadRobotTaskCalledFile -type UploadRobotTaskCalledFileRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - TtsParamHead string `position:"Query" name:"TtsParamHead"` - TtsParam string `position:"Query" name:"TtsParam"` - CalledNumber string `position:"Query" name:"CalledNumber"` - Id requests.Integer `position:"Query" name:"Id"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` -} - -// UploadRobotTaskCalledFileResponse is the response struct for api UploadRobotTaskCalledFile -type UploadRobotTaskCalledFileResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Data string `json:"Data" xml:"Data"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateUploadRobotTaskCalledFileRequest creates a request to invoke UploadRobotTaskCalledFile API -func CreateUploadRobotTaskCalledFileRequest() (request *UploadRobotTaskCalledFileRequest) { - request = &UploadRobotTaskCalledFileRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "UploadRobotTaskCalledFile", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateUploadRobotTaskCalledFileResponse creates a response to parse from UploadRobotTaskCalledFile response -func CreateUploadRobotTaskCalledFileResponse() (response *UploadRobotTaskCalledFileResponse) { - response = &UploadRobotTaskCalledFileResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_add_account.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_add_account.go deleted file mode 100644 index bf104b90..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_add_account.go +++ /dev/null @@ -1,105 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// VoipAddAccount invokes the dyvmsapi.VoipAddAccount API synchronously -func (client *Client) VoipAddAccount(request *VoipAddAccountRequest) (response *VoipAddAccountResponse, err error) { - response = CreateVoipAddAccountResponse() - err = client.DoAction(request, response) - return -} - -// VoipAddAccountWithChan invokes the dyvmsapi.VoipAddAccount API asynchronously -func (client *Client) VoipAddAccountWithChan(request *VoipAddAccountRequest) (<-chan *VoipAddAccountResponse, <-chan error) { - responseChan := make(chan *VoipAddAccountResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.VoipAddAccount(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// VoipAddAccountWithCallback invokes the dyvmsapi.VoipAddAccount API asynchronously -func (client *Client) VoipAddAccountWithCallback(request *VoipAddAccountRequest, callback func(response *VoipAddAccountResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *VoipAddAccountResponse - var err error - defer close(result) - response, err = client.VoipAddAccount(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// VoipAddAccountRequest is the request struct for api VoipAddAccount -type VoipAddAccountRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - DeviceId string `position:"Query" name:"DeviceId"` -} - -// VoipAddAccountResponse is the response struct for api VoipAddAccount -type VoipAddAccountResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Module string `json:"Module" xml:"Module"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateVoipAddAccountRequest creates a request to invoke VoipAddAccount API -func CreateVoipAddAccountRequest() (request *VoipAddAccountRequest) { - request = &VoipAddAccountRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "VoipAddAccount", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateVoipAddAccountResponse creates a response to parse from VoipAddAccount response -func CreateVoipAddAccountResponse() (response *VoipAddAccountResponse) { - response = &VoipAddAccountResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_get_token.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_get_token.go deleted file mode 100644 index 03b46925..00000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/dyvmsapi/voip_get_token.go +++ /dev/null @@ -1,107 +0,0 @@ -package dyvmsapi - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -//See the License for the specific language governing permissions and -//limitations under the License. -// -// Code generated by Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// VoipGetToken invokes the dyvmsapi.VoipGetToken API synchronously -func (client *Client) VoipGetToken(request *VoipGetTokenRequest) (response *VoipGetTokenResponse, err error) { - response = CreateVoipGetTokenResponse() - err = client.DoAction(request, response) - return -} - -// VoipGetTokenWithChan invokes the dyvmsapi.VoipGetToken API asynchronously -func (client *Client) VoipGetTokenWithChan(request *VoipGetTokenRequest) (<-chan *VoipGetTokenResponse, <-chan error) { - responseChan := make(chan *VoipGetTokenResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.VoipGetToken(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// VoipGetTokenWithCallback invokes the dyvmsapi.VoipGetToken API asynchronously -func (client *Client) VoipGetTokenWithCallback(request *VoipGetTokenRequest, callback func(response *VoipGetTokenResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *VoipGetTokenResponse - var err error - defer close(result) - response, err = client.VoipGetToken(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// VoipGetTokenRequest is the request struct for api VoipGetToken -type VoipGetTokenRequest struct { - *requests.RpcRequest - ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` - VoipId string `position:"Query" name:"VoipId"` - ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` - OwnerId requests.Integer `position:"Query" name:"OwnerId"` - DeviceId string `position:"Query" name:"DeviceId"` - IsCustomAccount requests.Boolean `position:"Query" name:"IsCustomAccount"` -} - -// VoipGetTokenResponse is the response struct for api VoipGetToken -type VoipGetTokenResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - Module string `json:"Module" xml:"Module"` - Code string `json:"Code" xml:"Code"` - Message string `json:"Message" xml:"Message"` -} - -// CreateVoipGetTokenRequest creates a request to invoke VoipGetToken API -func CreateVoipGetTokenRequest() (request *VoipGetTokenRequest) { - request = &VoipGetTokenRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Dyvmsapi", "2017-05-25", "VoipGetToken", "dyvms", "openAPI") - request.Method = requests.POST - return -} - -// CreateVoipGetTokenResponse creates a response to parse from VoipGetToken response -func CreateVoipGetTokenResponse() (response *VoipGetTokenResponse) { - response = &VoipGetTokenResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/astaxie/beego/.gitignore b/vendor/github.com/astaxie/beego/.gitignore deleted file mode 100644 index e1b65291..00000000 --- a/vendor/github.com/astaxie/beego/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -.idea -.vscode -.DS_Store -*.swp -*.swo -beego.iml diff --git a/vendor/github.com/astaxie/beego/.travis.yml b/vendor/github.com/astaxie/beego/.travis.yml deleted file mode 100644 index c019c999..00000000 --- a/vendor/github.com/astaxie/beego/.travis.yml +++ /dev/null @@ -1,73 +0,0 @@ -language: go - -go: - - "1.13.x" -services: - - redis-server - - mysql - - postgresql - - memcached -env: - global: - - GO_REPO_FULLNAME="github.com/astaxie/beego" - matrix: - - ORM_DRIVER=sqlite3 ORM_SOURCE=$TRAVIS_BUILD_DIR/orm_test.db - - ORM_DRIVER=postgres ORM_SOURCE="user=postgres dbname=orm_test sslmode=disable" -before_install: - # link the local repo with ${GOPATH}/src// - - GO_REPO_NAMESPACE=${GO_REPO_FULLNAME%/*} - # relies on GOPATH to contain only one directory... - - mkdir -p ${GOPATH}/src/${GO_REPO_NAMESPACE} - - ln -sv ${TRAVIS_BUILD_DIR} ${GOPATH}/src/${GO_REPO_FULLNAME} - - cd ${GOPATH}/src/${GO_REPO_FULLNAME} - # get and build ssdb - - git clone git://github.com/ideawu/ssdb.git - - cd ssdb - - make - - cd .. -install: - - go get github.com/lib/pq - - go get github.com/go-sql-driver/mysql - - go get github.com/mattn/go-sqlite3 - - go get github.com/bradfitz/gomemcache/memcache - - go get github.com/gomodule/redigo/redis - - go get github.com/beego/x2j - - go get github.com/couchbase/go-couchbase - - go get github.com/beego/goyaml2 - - go get gopkg.in/yaml.v2 - - go get github.com/belogik/goes - - go get github.com/ledisdb/ledisdb - - go get github.com/ssdb/gossdb/ssdb - - go get github.com/cloudflare/golz4 - - go get github.com/gogo/protobuf/proto - - go get github.com/Knetic/govaluate - - go get github.com/casbin/casbin - - go get github.com/elazarl/go-bindata-assetfs - - go get github.com/OwnLocal/goes - - go get github.com/shiena/ansicolor - - go get -u honnef.co/go/tools/cmd/staticcheck - - go get -u github.com/mdempsky/unconvert - - go get -u github.com/gordonklaus/ineffassign - - go get -u golang.org/x/lint/golint - - go get -u github.com/go-redis/redis -before_script: - - psql --version - - sh -c "if [ '$ORM_DRIVER' = 'postgres' ]; then psql -c 'create database orm_test;' -U postgres; fi" - - sh -c "if [ '$ORM_DRIVER' = 'mysql' ]; then mysql -u root -e 'create database orm_test;'; fi" - - sh -c "if [ '$ORM_DRIVER' = 'sqlite' ]; then touch $TRAVIS_BUILD_DIR/orm_test.db; fi" - - sh -c "go get github.com/golang/lint/golint; golint ./...;" - - sh -c "go list ./... | grep -v vendor | xargs go vet -v" - - mkdir -p res/var - - ./ssdb/ssdb-server ./ssdb/ssdb.conf -d -after_script: - - killall -w ssdb-server - - rm -rf ./res/var/* -script: - - go test -v ./... - - staticcheck -show-ignored -checks "-ST1017,-U1000,-ST1005,-S1034,-S1012,-SA4006,-SA6005,-SA1019,-SA1024" - - unconvert $(go list ./... | grep -v /vendor/) - - ineffassign . - - find . ! \( -path './vendor' -prune \) -type f -name '*.go' -print0 | xargs -0 gofmt -l -s - - golint ./... -addons: - postgresql: "9.6" diff --git a/vendor/github.com/astaxie/beego/CONTRIBUTING.md b/vendor/github.com/astaxie/beego/CONTRIBUTING.md deleted file mode 100644 index 9d511616..00000000 --- a/vendor/github.com/astaxie/beego/CONTRIBUTING.md +++ /dev/null @@ -1,52 +0,0 @@ -# Contributing to beego - -beego is an open source project. - -It is the work of hundreds of contributors. We appreciate your help! - -Here are instructions to get you started. They are probably not perfect, -please let us know if anything feels wrong or incomplete. - -## Contribution guidelines - -### Pull requests - -First of all. beego follow the gitflow. So please send you pull request -to **develop** branch. We will close the pull request to master branch. - -We are always happy to receive pull requests, and do our best to -review them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! Sometimes we can make a mistake, please do more explaining -for us. We will appreciate it. - -We're trying very hard to keep beego simple and fast. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. But we will give you some advice on how to -do it in other way. - -### Create issues - -Any significant improvement should be documented as [a GitHub -issue](https://github.com/astaxie/beego/issues) before anybody -starts working on it. - -Also when filing an issue, make sure to answer these five questions: - -- What version of beego are you using (bee version)? -- What operating system and processor architecture are you using? -- What did you do? -- What did you expect to see? -- What did you see instead? - -### but check existing issues and docs first! - -Please take a moment to check that an issue doesn't already exist -documenting your bug report or improvement proposal. If it does, it -never hurts to add a quick "+1" or "I have this problem too". This will -help prioritize the most common problems and requests. - -Also if you don't know how to use it. please make sure you have read though -the docs in http://beego.me/docs \ No newline at end of file diff --git a/vendor/github.com/astaxie/beego/LICENSE b/vendor/github.com/astaxie/beego/LICENSE deleted file mode 100644 index 5dbd4243..00000000 --- a/vendor/github.com/astaxie/beego/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2014 astaxie - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file diff --git a/vendor/github.com/astaxie/beego/README.md b/vendor/github.com/astaxie/beego/README.md deleted file mode 100644 index de8f0063..00000000 --- a/vendor/github.com/astaxie/beego/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Beego [![Build Status](https://travis-ci.org/astaxie/beego.svg?branch=master)](https://travis-ci.org/astaxie/beego) [![GoDoc](http://godoc.org/github.com/astaxie/beego?status.svg)](http://godoc.org/github.com/astaxie/beego) [![Foundation](https://img.shields.io/badge/Golang-Foundation-green.svg)](http://golangfoundation.org) [![Go Report Card](https://goreportcard.com/badge/github.com/astaxie/beego)](https://goreportcard.com/report/github.com/astaxie/beego) - - -beego is used for rapid development of RESTful APIs, web apps and backend services in Go. -It is inspired by Tornado, Sinatra and Flask. beego has some Go-specific features such as interfaces and struct embedding. - -###### More info at [beego.me](http://beego.me). - -## Quick Start - -#### Create `hello` directory, cd `hello` directory - - mkdir hello - cd hello - -#### Init module - - go mod init - -#### Download and install - - go get github.com/astaxie/beego - -#### Create file `hello.go` -```go -package main - -import "github.com/astaxie/beego" - -func main(){ - beego.Run() -} -``` -#### Build and run - - go build hello.go - ./hello - -#### Go to [http://localhost:8080](http://localhost:8080) - -Congratulations! You've just built your first **beego** app. - -###### Please see [Documentation](http://beego.me/docs) for more. - -###### [beego-example](https://github.com/beego-dev/beego-example) - -## Features - -* RESTful support -* MVC architecture -* Modularity -* Auto API documents -* Annotation router -* Namespace -* Powerful development tools -* Full stack for Web & API - -## Documentation - -* [English](http://beego.me/docs/intro/) -* [中文文档](http://beego.me/docs/intro/) -* [Русский](http://beego.me/docs/intro/) - -## Community - -* [http://beego.me/community](http://beego.me/community) -* Welcome to join us in Slack: [https://beego.slack.com](https://beego.slack.com), you can get invited from [here](https://github.com/beego/beedoc/issues/232) -* QQ Group Group ID:523992905 - -## License - -beego source code is licensed under the Apache Licence, Version 2.0 -(http://www.apache.org/licenses/LICENSE-2.0.html). diff --git a/vendor/github.com/astaxie/beego/admin.go b/vendor/github.com/astaxie/beego/admin.go deleted file mode 100644 index db52647e..00000000 --- a/vendor/github.com/astaxie/beego/admin.go +++ /dev/null @@ -1,458 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "os" - "reflect" - "strconv" - "text/template" - "time" - - "github.com/prometheus/client_golang/prometheus/promhttp" - - "github.com/astaxie/beego/grace" - "github.com/astaxie/beego/logs" - "github.com/astaxie/beego/toolbox" - "github.com/astaxie/beego/utils" -) - -// BeeAdminApp is the default adminApp used by admin module. -var beeAdminApp *adminApp - -// FilterMonitorFunc is default monitor filter when admin module is enable. -// if this func returns, admin module records qps for this request by condition of this function logic. -// usage: -// func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool { -// if method == "POST" { -// return false -// } -// if t.Nanoseconds() < 100 { -// return false -// } -// if strings.HasPrefix(requestPath, "/astaxie") { -// return false -// } -// return true -// } -// beego.FilterMonitorFunc = MyFilterMonitor. -var FilterMonitorFunc func(string, string, time.Duration, string, int) bool - -func init() { - beeAdminApp = &adminApp{ - routers: make(map[string]http.HandlerFunc), - } - // keep in mind that all data should be html escaped to avoid XSS attack - beeAdminApp.Route("/", adminIndex) - beeAdminApp.Route("/qps", qpsIndex) - beeAdminApp.Route("/prof", profIndex) - beeAdminApp.Route("/healthcheck", healthcheck) - beeAdminApp.Route("/task", taskStatus) - beeAdminApp.Route("/listconf", listConf) - beeAdminApp.Route("/metrics", promhttp.Handler().ServeHTTP) - FilterMonitorFunc = func(string, string, time.Duration, string, int) bool { return true } -} - -// AdminIndex is the default http.Handler for admin module. -// it matches url pattern "/". -func adminIndex(rw http.ResponseWriter, _ *http.Request) { - writeTemplate(rw, map[interface{}]interface{}{}, indexTpl, defaultScriptsTpl) -} - -// QpsIndex is the http.Handler for writing qps statistics map result info in http.ResponseWriter. -// it's registered with url pattern "/qps" in admin module. -func qpsIndex(rw http.ResponseWriter, _ *http.Request) { - data := make(map[interface{}]interface{}) - data["Content"] = toolbox.StatisticsMap.GetMap() - - // do html escape before display path, avoid xss - if content, ok := (data["Content"]).(M); ok { - if resultLists, ok := (content["Data"]).([][]string); ok { - for i := range resultLists { - if len(resultLists[i]) > 0 { - resultLists[i][0] = template.HTMLEscapeString(resultLists[i][0]) - } - } - } - } - - writeTemplate(rw, data, qpsTpl, defaultScriptsTpl) -} - -// ListConf is the http.Handler of displaying all beego configuration values as key/value pair. -// it's registered with url pattern "/listconf" in admin module. -func listConf(rw http.ResponseWriter, r *http.Request) { - r.ParseForm() - command := r.Form.Get("command") - if command == "" { - rw.Write([]byte("command not support")) - return - } - - data := make(map[interface{}]interface{}) - switch command { - case "conf": - m := make(M) - list("BConfig", BConfig, m) - m["AppConfigPath"] = template.HTMLEscapeString(appConfigPath) - m["AppConfigProvider"] = template.HTMLEscapeString(appConfigProvider) - tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl)) - tmpl = template.Must(tmpl.Parse(configTpl)) - tmpl = template.Must(tmpl.Parse(defaultScriptsTpl)) - - data["Content"] = m - - tmpl.Execute(rw, data) - - case "router": - content := PrintTree() - content["Fields"] = []string{ - "Router Pattern", - "Methods", - "Controller", - } - data["Content"] = content - data["Title"] = "Routers" - writeTemplate(rw, data, routerAndFilterTpl, defaultScriptsTpl) - case "filter": - var ( - content = M{ - "Fields": []string{ - "Router Pattern", - "Filter Function", - }, - } - filterTypes = []string{} - filterTypeData = make(M) - ) - - if BeeApp.Handlers.enableFilter { - var filterType string - for k, fr := range map[int]string{ - BeforeStatic: "Before Static", - BeforeRouter: "Before Router", - BeforeExec: "Before Exec", - AfterExec: "After Exec", - FinishRouter: "Finish Router"} { - if bf := BeeApp.Handlers.filters[k]; len(bf) > 0 { - filterType = fr - filterTypes = append(filterTypes, filterType) - resultList := new([][]string) - for _, f := range bf { - var result = []string{ - // void xss - template.HTMLEscapeString(f.pattern), - template.HTMLEscapeString(utils.GetFuncName(f.filterFunc)), - } - *resultList = append(*resultList, result) - } - filterTypeData[filterType] = resultList - } - } - } - - content["Data"] = filterTypeData - content["Methods"] = filterTypes - - data["Content"] = content - data["Title"] = "Filters" - writeTemplate(rw, data, routerAndFilterTpl, defaultScriptsTpl) - default: - rw.Write([]byte("command not support")) - } -} - -func list(root string, p interface{}, m M) { - pt := reflect.TypeOf(p) - pv := reflect.ValueOf(p) - if pt.Kind() == reflect.Ptr { - pt = pt.Elem() - pv = pv.Elem() - } - for i := 0; i < pv.NumField(); i++ { - var key string - if root == "" { - key = pt.Field(i).Name - } else { - key = root + "." + pt.Field(i).Name - } - if pv.Field(i).Kind() == reflect.Struct { - list(key, pv.Field(i).Interface(), m) - } else { - m[key] = pv.Field(i).Interface() - } - } -} - -// PrintTree prints all registered routers. -func PrintTree() M { - var ( - content = M{} - methods = []string{} - methodsData = make(M) - ) - for method, t := range BeeApp.Handlers.routers { - - resultList := new([][]string) - - printTree(resultList, t) - - methods = append(methods, template.HTMLEscapeString(method)) - methodsData[template.HTMLEscapeString(method)] = resultList - } - - content["Data"] = methodsData - content["Methods"] = methods - return content -} - -func printTree(resultList *[][]string, t *Tree) { - for _, tr := range t.fixrouters { - printTree(resultList, tr) - } - if t.wildcard != nil { - printTree(resultList, t.wildcard) - } - for _, l := range t.leaves { - if v, ok := l.runObject.(*ControllerInfo); ok { - if v.routerType == routerTypeBeego { - var result = []string{ - template.HTMLEscapeString(v.pattern), - template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)), - template.HTMLEscapeString(v.controllerType.String()), - } - *resultList = append(*resultList, result) - } else if v.routerType == routerTypeRESTFul { - var result = []string{ - template.HTMLEscapeString(v.pattern), - template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)), - "", - } - *resultList = append(*resultList, result) - } else if v.routerType == routerTypeHandler { - var result = []string{ - template.HTMLEscapeString(v.pattern), - "", - "", - } - *resultList = append(*resultList, result) - } - } - } -} - -// ProfIndex is a http.Handler for showing profile command. -// it's in url pattern "/prof" in admin module. -func profIndex(rw http.ResponseWriter, r *http.Request) { - r.ParseForm() - command := r.Form.Get("command") - if command == "" { - return - } - - var ( - format = r.Form.Get("format") - data = make(map[interface{}]interface{}) - result bytes.Buffer - ) - toolbox.ProcessInput(command, &result) - data["Content"] = template.HTMLEscapeString(result.String()) - - if format == "json" && command == "gc summary" { - dataJSON, err := json.Marshal(data) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - return - } - writeJSON(rw, dataJSON) - return - } - - data["Title"] = template.HTMLEscapeString(command) - defaultTpl := defaultScriptsTpl - if command == "gc summary" { - defaultTpl = gcAjaxTpl - } - writeTemplate(rw, data, profillingTpl, defaultTpl) -} - -// Healthcheck is a http.Handler calling health checking and showing the result. -// it's in "/healthcheck" pattern in admin module. -func healthcheck(rw http.ResponseWriter, r *http.Request) { - var ( - result []string - data = make(map[interface{}]interface{}) - resultList = new([][]string) - content = M{ - "Fields": []string{"Name", "Message", "Status"}, - } - ) - - for name, h := range toolbox.AdminCheckList { - if err := h.Check(); err != nil { - result = []string{ - "error", - template.HTMLEscapeString(name), - template.HTMLEscapeString(err.Error()), - } - } else { - result = []string{ - "success", - template.HTMLEscapeString(name), - "OK", - } - } - *resultList = append(*resultList, result) - } - - queryParams := r.URL.Query() - jsonFlag := queryParams.Get("json") - shouldReturnJSON, _ := strconv.ParseBool(jsonFlag) - - if shouldReturnJSON { - response := buildHealthCheckResponseList(resultList) - jsonResponse, err := json.Marshal(response) - - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } else { - writeJSON(rw, jsonResponse) - } - return - } - - content["Data"] = resultList - data["Content"] = content - data["Title"] = "Health Check" - - writeTemplate(rw, data, healthCheckTpl, defaultScriptsTpl) -} - -func buildHealthCheckResponseList(healthCheckResults *[][]string) []map[string]interface{} { - response := make([]map[string]interface{}, len(*healthCheckResults)) - - for i, healthCheckResult := range *healthCheckResults { - currentResultMap := make(map[string]interface{}) - - currentResultMap["name"] = healthCheckResult[0] - currentResultMap["message"] = healthCheckResult[1] - currentResultMap["status"] = healthCheckResult[2] - - response[i] = currentResultMap - } - - return response - -} - -func writeJSON(rw http.ResponseWriter, jsonData []byte) { - rw.Header().Set("Content-Type", "application/json") - rw.Write(jsonData) -} - -// TaskStatus is a http.Handler with running task status (task name, status and the last execution). -// it's in "/task" pattern in admin module. -func taskStatus(rw http.ResponseWriter, req *http.Request) { - data := make(map[interface{}]interface{}) - - // Run Task - req.ParseForm() - taskname := req.Form.Get("taskname") - if taskname != "" { - if t, ok := toolbox.AdminTaskList[taskname]; ok { - if err := t.Run(); err != nil { - data["Message"] = []string{"error", template.HTMLEscapeString(fmt.Sprintf("%s", err))} - } - data["Message"] = []string{"success", template.HTMLEscapeString(fmt.Sprintf("%s run success,Now the Status is
%s", taskname, t.GetStatus()))} - } else { - data["Message"] = []string{"warning", template.HTMLEscapeString(fmt.Sprintf("there's no task which named: %s", taskname))} - } - } - - // List Tasks - content := make(M) - resultList := new([][]string) - var fields = []string{ - "Task Name", - "Task Spec", - "Task Status", - "Last Time", - "", - } - for tname, tk := range toolbox.AdminTaskList { - result := []string{ - template.HTMLEscapeString(tname), - template.HTMLEscapeString(tk.GetSpec()), - template.HTMLEscapeString(tk.GetStatus()), - template.HTMLEscapeString(tk.GetPrev().String()), - } - *resultList = append(*resultList, result) - } - - content["Fields"] = fields - content["Data"] = resultList - data["Content"] = content - data["Title"] = "Tasks" - writeTemplate(rw, data, tasksTpl, defaultScriptsTpl) -} - -func writeTemplate(rw http.ResponseWriter, data map[interface{}]interface{}, tpls ...string) { - tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl)) - for _, tpl := range tpls { - tmpl = template.Must(tmpl.Parse(tpl)) - } - tmpl.Execute(rw, data) -} - -// adminApp is an http.HandlerFunc map used as beeAdminApp. -type adminApp struct { - routers map[string]http.HandlerFunc -} - -// Route adds http.HandlerFunc to adminApp with url pattern. -func (admin *adminApp) Route(pattern string, f http.HandlerFunc) { - admin.routers[pattern] = f -} - -// Run adminApp http server. -// Its addr is defined in configuration file as adminhttpaddr and adminhttpport. -func (admin *adminApp) Run() { - if len(toolbox.AdminTaskList) > 0 { - toolbox.StartTask() - } - addr := BConfig.Listen.AdminAddr - - if BConfig.Listen.AdminPort != 0 { - addr = fmt.Sprintf("%s:%d", BConfig.Listen.AdminAddr, BConfig.Listen.AdminPort) - } - for p, f := range admin.routers { - http.Handle(p, f) - } - logs.Info("Admin server Running on %s", addr) - - var err error - if BConfig.Listen.Graceful { - err = grace.ListenAndServe(addr, nil) - } else { - err = http.ListenAndServe(addr, nil) - } - if err != nil { - logs.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) - } -} diff --git a/vendor/github.com/astaxie/beego/adminui.go b/vendor/github.com/astaxie/beego/adminui.go deleted file mode 100644 index cdcdef33..00000000 --- a/vendor/github.com/astaxie/beego/adminui.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -var indexTpl = ` -{{define "content"}} -

Beego Admin Dashboard

-

-For detail usage please check our document: -

-

-Toolbox -

-

-Live Monitor -

-{{.Content}} -{{end}}` - -var profillingTpl = ` -{{define "content"}} -

{{.Title}}

-
-
{{.Content}}
-
-{{end}}` - -var defaultScriptsTpl = `` - -var gcAjaxTpl = ` -{{define "scripts"}} - -{{end}} -` - -var qpsTpl = `{{define "content"}} -

Requests statistics

- - - - {{range .Content.Fields}} - - {{end}} - - - - - {{range $i, $elem := .Content.Data}} - - - - - - - - - - - {{end}} - - -
- {{.}} -
{{index $elem 0}}{{index $elem 1}}{{index $elem 2}}{{index $elem 4}}{{index $elem 6}}{{index $elem 8}}{{index $elem 10}}
-{{end}}` - -var configTpl = ` -{{define "content"}} -

Configurations

-
-{{range $index, $elem := .Content}}
-{{$index}}={{$elem}}
-{{end}}
-
-{{end}} -` - -var routerAndFilterTpl = `{{define "content"}} - - -

{{.Title}}

- -{{range .Content.Methods}} - -
-
{{.}}
-
- - - - {{range $.Content.Fields}} - - {{end}} - - - - - {{$slice := index $.Content.Data .}} - {{range $i, $elem := $slice}} - - - {{range $elem}} - - {{end}} - - - {{end}} - - -
- {{.}} -
- {{.}} -
-
-
-{{end}} - - -{{end}}` - -var tasksTpl = `{{define "content"}} - -

{{.Title}}

- -{{if .Message }} -{{ $messageType := index .Message 0}} -

-{{index .Message 1}} -

-{{end}} - - - - - -{{range .Content.Fields}} - -{{end}} - - - - -{{range $i, $slice := .Content.Data}} - - {{range $slice}} - - {{end}} - - -{{end}} - -
-{{.}} -
- {{.}} - - Run -
- -{{end}}` - -var healthCheckTpl = ` -{{define "content"}} - -

{{.Title}}

- - - -{{range .Content.Fields}} - -{{end}} - - - -{{range $i, $slice := .Content.Data}} - {{ $header := index $slice 0}} - {{ if eq "success" $header}} - - {{else if eq "error" $header}} - - {{else}} - - {{end}} - {{range $j, $elem := $slice}} - {{if ne $j 0}} - - {{end}} - {{end}} - - -{{end}} - - -
- {{.}} -
- {{$elem}} - - {{$header}} -
-{{end}}` - -// The base dashboardTpl -var dashboardTpl = ` - - - - - - - - - - -Welcome to Beego Admin Dashboard - - - - - - - - - - - - - -
-{{template "content" .}} -
- - - - - - - -{{template "scripts" .}} - - -` diff --git a/vendor/github.com/astaxie/beego/app.go b/vendor/github.com/astaxie/beego/app.go deleted file mode 100644 index 3dee8999..00000000 --- a/vendor/github.com/astaxie/beego/app.go +++ /dev/null @@ -1,496 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/http/fcgi" - "os" - "path" - "strings" - "time" - - "github.com/astaxie/beego/grace" - "github.com/astaxie/beego/logs" - "github.com/astaxie/beego/utils" - "golang.org/x/crypto/acme/autocert" -) - -var ( - // BeeApp is an application instance - BeeApp *App -) - -func init() { - // create beego application - BeeApp = NewApp() -} - -// App defines beego application with a new PatternServeMux. -type App struct { - Handlers *ControllerRegister - Server *http.Server -} - -// NewApp returns a new beego application. -func NewApp() *App { - cr := NewControllerRegister() - app := &App{Handlers: cr, Server: &http.Server{}} - return app -} - -// MiddleWare function for http.Handler -type MiddleWare func(http.Handler) http.Handler - -// Run beego application. -func (app *App) Run(mws ...MiddleWare) { - addr := BConfig.Listen.HTTPAddr - - if BConfig.Listen.HTTPPort != 0 { - addr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPAddr, BConfig.Listen.HTTPPort) - } - - var ( - err error - l net.Listener - endRunning = make(chan bool, 1) - ) - - // run cgi server - if BConfig.Listen.EnableFcgi { - if BConfig.Listen.EnableStdIo { - if err = fcgi.Serve(nil, app.Handlers); err == nil { // standard I/O - logs.Info("Use FCGI via standard I/O") - } else { - logs.Critical("Cannot use FCGI via standard I/O", err) - } - return - } - if BConfig.Listen.HTTPPort == 0 { - // remove the Socket file before start - if utils.FileExists(addr) { - os.Remove(addr) - } - l, err = net.Listen("unix", addr) - } else { - l, err = net.Listen("tcp", addr) - } - if err != nil { - logs.Critical("Listen: ", err) - } - if err = fcgi.Serve(l, app.Handlers); err != nil { - logs.Critical("fcgi.Serve: ", err) - } - return - } - - app.Server.Handler = app.Handlers - for i := len(mws) - 1; i >= 0; i-- { - if mws[i] == nil { - continue - } - app.Server.Handler = mws[i](app.Server.Handler) - } - app.Server.ReadTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second - app.Server.WriteTimeout = time.Duration(BConfig.Listen.ServerTimeOut) * time.Second - app.Server.ErrorLog = logs.GetLogger("HTTP") - - // run graceful mode - if BConfig.Listen.Graceful { - httpsAddr := BConfig.Listen.HTTPSAddr - app.Server.Addr = httpsAddr - if BConfig.Listen.EnableHTTPS || BConfig.Listen.EnableMutualHTTPS { - go func() { - time.Sleep(1000 * time.Microsecond) - if BConfig.Listen.HTTPSPort != 0 { - httpsAddr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort) - app.Server.Addr = httpsAddr - } - server := grace.NewServer(httpsAddr, app.Server.Handler) - server.Server.ReadTimeout = app.Server.ReadTimeout - server.Server.WriteTimeout = app.Server.WriteTimeout - if BConfig.Listen.EnableMutualHTTPS { - if err := server.ListenAndServeMutualTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile, BConfig.Listen.TrustCaFile); err != nil { - logs.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid())) - time.Sleep(100 * time.Microsecond) - } - } else { - if BConfig.Listen.AutoTLS { - m := autocert.Manager{ - Prompt: autocert.AcceptTOS, - HostPolicy: autocert.HostWhitelist(BConfig.Listen.Domains...), - Cache: autocert.DirCache(BConfig.Listen.TLSCacheDir), - } - app.Server.TLSConfig = &tls.Config{GetCertificate: m.GetCertificate} - BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile = "", "" - } - if err := server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err != nil { - logs.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid())) - time.Sleep(100 * time.Microsecond) - } - } - endRunning <- true - }() - } - if BConfig.Listen.EnableHTTP { - go func() { - server := grace.NewServer(addr, app.Server.Handler) - server.Server.ReadTimeout = app.Server.ReadTimeout - server.Server.WriteTimeout = app.Server.WriteTimeout - if BConfig.Listen.ListenTCP4 { - server.Network = "tcp4" - } - if err := server.ListenAndServe(); err != nil { - logs.Critical("ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) - time.Sleep(100 * time.Microsecond) - } - endRunning <- true - }() - } - <-endRunning - return - } - - // run normal mode - if BConfig.Listen.EnableHTTPS || BConfig.Listen.EnableMutualHTTPS { - go func() { - time.Sleep(1000 * time.Microsecond) - if BConfig.Listen.HTTPSPort != 0 { - app.Server.Addr = fmt.Sprintf("%s:%d", BConfig.Listen.HTTPSAddr, BConfig.Listen.HTTPSPort) - } else if BConfig.Listen.EnableHTTP { - logs.Info("Start https server error, conflict with http. Please reset https port") - return - } - logs.Info("https server Running on https://%s", app.Server.Addr) - if BConfig.Listen.AutoTLS { - m := autocert.Manager{ - Prompt: autocert.AcceptTOS, - HostPolicy: autocert.HostWhitelist(BConfig.Listen.Domains...), - Cache: autocert.DirCache(BConfig.Listen.TLSCacheDir), - } - app.Server.TLSConfig = &tls.Config{GetCertificate: m.GetCertificate} - BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile = "", "" - } else if BConfig.Listen.EnableMutualHTTPS { - pool := x509.NewCertPool() - data, err := ioutil.ReadFile(BConfig.Listen.TrustCaFile) - if err != nil { - logs.Info("MutualHTTPS should provide TrustCaFile") - return - } - pool.AppendCertsFromPEM(data) - app.Server.TLSConfig = &tls.Config{ - ClientCAs: pool, - ClientAuth: BConfig.Listen.ClientAuth, - } - } - if err := app.Server.ListenAndServeTLS(BConfig.Listen.HTTPSCertFile, BConfig.Listen.HTTPSKeyFile); err != nil { - logs.Critical("ListenAndServeTLS: ", err) - time.Sleep(100 * time.Microsecond) - endRunning <- true - } - }() - - } - if BConfig.Listen.EnableHTTP { - go func() { - app.Server.Addr = addr - logs.Info("http server Running on http://%s", app.Server.Addr) - if BConfig.Listen.ListenTCP4 { - ln, err := net.Listen("tcp4", app.Server.Addr) - if err != nil { - logs.Critical("ListenAndServe: ", err) - time.Sleep(100 * time.Microsecond) - endRunning <- true - return - } - if err = app.Server.Serve(ln); err != nil { - logs.Critical("ListenAndServe: ", err) - time.Sleep(100 * time.Microsecond) - endRunning <- true - return - } - } else { - if err := app.Server.ListenAndServe(); err != nil { - logs.Critical("ListenAndServe: ", err) - time.Sleep(100 * time.Microsecond) - endRunning <- true - } - } - }() - } - <-endRunning -} - -// Router adds a patterned controller handler to BeeApp. -// it's an alias method of App.Router. -// usage: -// simple router -// beego.Router("/admin", &admin.UserController{}) -// beego.Router("/admin/index", &admin.ArticleController{}) -// -// regex router -// -// beego.Router("/api/:id([0-9]+)", &controllers.RController{}) -// -// custom rules -// beego.Router("/api/list",&RestController{},"*:ListFood") -// beego.Router("/api/create",&RestController{},"post:CreateFood") -// beego.Router("/api/update",&RestController{},"put:UpdateFood") -// beego.Router("/api/delete",&RestController{},"delete:DeleteFood") -func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *App { - BeeApp.Handlers.Add(rootpath, c, mappingMethods...) - return BeeApp -} - -// UnregisterFixedRoute unregisters the route with the specified fixedRoute. It is particularly useful -// in web applications that inherit most routes from a base webapp via the underscore -// import, and aim to overwrite only certain paths. -// The method parameter can be empty or "*" for all HTTP methods, or a particular -// method type (e.g. "GET" or "POST") for selective removal. -// -// Usage (replace "GET" with "*" for all methods): -// beego.UnregisterFixedRoute("/yourpreviouspath", "GET") -// beego.Router("/yourpreviouspath", yourControllerAddress, "get:GetNewPage") -func UnregisterFixedRoute(fixedRoute string, method string) *App { - subPaths := splitPath(fixedRoute) - if method == "" || method == "*" { - for m := range HTTPMETHOD { - if _, ok := BeeApp.Handlers.routers[m]; !ok { - continue - } - if BeeApp.Handlers.routers[m].prefix == strings.Trim(fixedRoute, "/ ") { - findAndRemoveSingleTree(BeeApp.Handlers.routers[m]) - continue - } - findAndRemoveTree(subPaths, BeeApp.Handlers.routers[m], m) - } - return BeeApp - } - // Single HTTP method - um := strings.ToUpper(method) - if _, ok := BeeApp.Handlers.routers[um]; ok { - if BeeApp.Handlers.routers[um].prefix == strings.Trim(fixedRoute, "/ ") { - findAndRemoveSingleTree(BeeApp.Handlers.routers[um]) - return BeeApp - } - findAndRemoveTree(subPaths, BeeApp.Handlers.routers[um], um) - } - return BeeApp -} - -func findAndRemoveTree(paths []string, entryPointTree *Tree, method string) { - for i := range entryPointTree.fixrouters { - if entryPointTree.fixrouters[i].prefix == paths[0] { - if len(paths) == 1 { - if len(entryPointTree.fixrouters[i].fixrouters) > 0 { - // If the route had children subtrees, remove just the functional leaf, - // to allow children to function as before - if len(entryPointTree.fixrouters[i].leaves) > 0 { - entryPointTree.fixrouters[i].leaves[0] = nil - entryPointTree.fixrouters[i].leaves = entryPointTree.fixrouters[i].leaves[1:] - } - } else { - // Remove the *Tree from the fixrouters slice - entryPointTree.fixrouters[i] = nil - - if i == len(entryPointTree.fixrouters)-1 { - entryPointTree.fixrouters = entryPointTree.fixrouters[:i] - } else { - entryPointTree.fixrouters = append(entryPointTree.fixrouters[:i], entryPointTree.fixrouters[i+1:len(entryPointTree.fixrouters)]...) - } - } - return - } - findAndRemoveTree(paths[1:], entryPointTree.fixrouters[i], method) - } - } -} - -func findAndRemoveSingleTree(entryPointTree *Tree) { - if entryPointTree == nil { - return - } - if len(entryPointTree.fixrouters) > 0 { - // If the route had children subtrees, remove just the functional leaf, - // to allow children to function as before - if len(entryPointTree.leaves) > 0 { - entryPointTree.leaves[0] = nil - entryPointTree.leaves = entryPointTree.leaves[1:] - } - } -} - -// Include will generate router file in the router/xxx.go from the controller's comments -// usage: -// beego.Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{}) -// type BankAccount struct{ -// beego.Controller -// } -// -// register the function -// func (b *BankAccount)Mapping(){ -// b.Mapping("ShowAccount" , b.ShowAccount) -// b.Mapping("ModifyAccount", b.ModifyAccount) -//} -// -// //@router /account/:id [get] -// func (b *BankAccount) ShowAccount(){ -// //logic -// } -// -// -// //@router /account/:id [post] -// func (b *BankAccount) ModifyAccount(){ -// //logic -// } -// -// the comments @router url methodlist -// url support all the function Router's pattern -// methodlist [get post head put delete options *] -func Include(cList ...ControllerInterface) *App { - BeeApp.Handlers.Include(cList...) - return BeeApp -} - -// RESTRouter adds a restful controller handler to BeeApp. -// its' controller implements beego.ControllerInterface and -// defines a param "pattern/:objectId" to visit each resource. -func RESTRouter(rootpath string, c ControllerInterface) *App { - Router(rootpath, c) - Router(path.Join(rootpath, ":objectId"), c) - return BeeApp -} - -// AutoRouter adds defined controller handler to BeeApp. -// it's same to App.AutoRouter. -// if beego.AddAuto(&MainContorlller{}) and MainController has methods List and Page, -// visit the url /main/list to exec List function or /main/page to exec Page function. -func AutoRouter(c ControllerInterface) *App { - BeeApp.Handlers.AddAuto(c) - return BeeApp -} - -// AutoPrefix adds controller handler to BeeApp with prefix. -// it's same to App.AutoRouterWithPrefix. -// if beego.AutoPrefix("/admin",&MainContorlller{}) and MainController has methods List and Page, -// visit the url /admin/main/list to exec List function or /admin/main/page to exec Page function. -func AutoPrefix(prefix string, c ControllerInterface) *App { - BeeApp.Handlers.AddAutoPrefix(prefix, c) - return BeeApp -} - -// Get used to register router for Get method -// usage: -// beego.Get("/", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Get(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Get(rootpath, f) - return BeeApp -} - -// Post used to register router for Post method -// usage: -// beego.Post("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Post(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Post(rootpath, f) - return BeeApp -} - -// Delete used to register router for Delete method -// usage: -// beego.Delete("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Delete(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Delete(rootpath, f) - return BeeApp -} - -// Put used to register router for Put method -// usage: -// beego.Put("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Put(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Put(rootpath, f) - return BeeApp -} - -// Head used to register router for Head method -// usage: -// beego.Head("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Head(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Head(rootpath, f) - return BeeApp -} - -// Options used to register router for Options method -// usage: -// beego.Options("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Options(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Options(rootpath, f) - return BeeApp -} - -// Patch used to register router for Patch method -// usage: -// beego.Patch("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Patch(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Patch(rootpath, f) - return BeeApp -} - -// Any used to register router for all methods -// usage: -// beego.Any("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func Any(rootpath string, f FilterFunc) *App { - BeeApp.Handlers.Any(rootpath, f) - return BeeApp -} - -// Handler used to register a Handler router -// usage: -// beego.Handler("/api", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { -// fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) -// })) -func Handler(rootpath string, h http.Handler, options ...interface{}) *App { - BeeApp.Handlers.Handler(rootpath, h, options...) - return BeeApp -} - -// InsertFilter adds a FilterFunc with pattern condition and action constant. -// The pos means action constant including -// beego.BeforeStatic, beego.BeforeRouter, beego.BeforeExec, beego.AfterExec and beego.FinishRouter. -// The bool params is for setting the returnOnOutput value (false allows multiple filters to execute) -func InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) *App { - BeeApp.Handlers.InsertFilter(pattern, pos, filter, params...) - return BeeApp -} diff --git a/vendor/github.com/astaxie/beego/beego.go b/vendor/github.com/astaxie/beego/beego.go deleted file mode 100644 index 44184c25..00000000 --- a/vendor/github.com/astaxie/beego/beego.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "os" - "path/filepath" - "strconv" - "strings" -) - -const ( - // VERSION represent beego web framework version. - VERSION = "1.12.3" - - // DEV is for develop - DEV = "dev" - // PROD is for production - PROD = "prod" -) - -// M is Map shortcut -type M map[string]interface{} - -// Hook function to run -type hookfunc func() error - -var ( - hooks = make([]hookfunc, 0) //hook function slice to store the hookfunc -) - -// AddAPPStartHook is used to register the hookfunc -// The hookfuncs will run in beego.Run() -// such as initiating session , starting middleware , building template, starting admin control and so on. -func AddAPPStartHook(hf ...hookfunc) { - hooks = append(hooks, hf...) -} - -// Run beego application. -// beego.Run() default run on HttpPort -// beego.Run("localhost") -// beego.Run(":8089") -// beego.Run("127.0.0.1:8089") -func Run(params ...string) { - - initBeforeHTTPRun() - - if len(params) > 0 && params[0] != "" { - strs := strings.Split(params[0], ":") - if len(strs) > 0 && strs[0] != "" { - BConfig.Listen.HTTPAddr = strs[0] - } - if len(strs) > 1 && strs[1] != "" { - BConfig.Listen.HTTPPort, _ = strconv.Atoi(strs[1]) - } - - BConfig.Listen.Domains = params - } - - BeeApp.Run() -} - -// RunWithMiddleWares Run beego application with middlewares. -func RunWithMiddleWares(addr string, mws ...MiddleWare) { - initBeforeHTTPRun() - - strs := strings.Split(addr, ":") - if len(strs) > 0 && strs[0] != "" { - BConfig.Listen.HTTPAddr = strs[0] - BConfig.Listen.Domains = []string{strs[0]} - } - if len(strs) > 1 && strs[1] != "" { - BConfig.Listen.HTTPPort, _ = strconv.Atoi(strs[1]) - } - - BeeApp.Run(mws...) -} - -func initBeforeHTTPRun() { - //init hooks - AddAPPStartHook( - registerMime, - registerDefaultErrorHandler, - registerSession, - registerTemplate, - registerAdmin, - registerGzip, - ) - - for _, hk := range hooks { - if err := hk(); err != nil { - panic(err) - } - } -} - -// TestBeegoInit is for test package init -func TestBeegoInit(ap string) { - path := filepath.Join(ap, "conf", "app.conf") - os.Chdir(ap) - InitBeegoBeforeTest(path) -} - -// InitBeegoBeforeTest is for test package init -func InitBeegoBeforeTest(appConfigPath string) { - if err := LoadAppConfig(appConfigProvider, appConfigPath); err != nil { - panic(err) - } - BConfig.RunMode = "test" - initBeforeHTTPRun() -} diff --git a/vendor/github.com/astaxie/beego/config.go b/vendor/github.com/astaxie/beego/config.go deleted file mode 100644 index bd5bf2a1..00000000 --- a/vendor/github.com/astaxie/beego/config.go +++ /dev/null @@ -1,533 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "crypto/tls" - "fmt" - "net/http" - "os" - "path/filepath" - "reflect" - "runtime" - "strings" - - "github.com/astaxie/beego/config" - "github.com/astaxie/beego/context" - "github.com/astaxie/beego/logs" - "github.com/astaxie/beego/session" - "github.com/astaxie/beego/utils" -) - -// Config is the main struct for BConfig -type Config struct { - AppName string //Application name - RunMode string //Running Mode: dev | prod - RouterCaseSensitive bool - ServerName string - RecoverPanic bool - RecoverFunc func(*context.Context) - CopyRequestBody bool - EnableGzip bool - MaxMemory int64 - EnableErrorsShow bool - EnableErrorsRender bool - Listen Listen - WebConfig WebConfig - Log LogConfig -} - -// Listen holds for http and https related config -type Listen struct { - Graceful bool // Graceful means use graceful module to start the server - ServerTimeOut int64 - ListenTCP4 bool - EnableHTTP bool - HTTPAddr string - HTTPPort int - AutoTLS bool - Domains []string - TLSCacheDir string - EnableHTTPS bool - EnableMutualHTTPS bool - HTTPSAddr string - HTTPSPort int - HTTPSCertFile string - HTTPSKeyFile string - TrustCaFile string - ClientAuth tls.ClientAuthType - EnableAdmin bool - AdminAddr string - AdminPort int - EnableFcgi bool - EnableStdIo bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O -} - -// WebConfig holds web related config -type WebConfig struct { - AutoRender bool - EnableDocs bool - FlashName string - FlashSeparator string - DirectoryIndex bool - StaticDir map[string]string - StaticExtensionsToGzip []string - StaticCacheFileSize int - StaticCacheFileNum int - TemplateLeft string - TemplateRight string - ViewsPath string - EnableXSRF bool - XSRFKey string - XSRFExpire int - Session SessionConfig -} - -// SessionConfig holds session related config -type SessionConfig struct { - SessionOn bool - SessionProvider string - SessionName string - SessionGCMaxLifetime int64 - SessionProviderConfig string - SessionCookieLifeTime int - SessionAutoSetCookie bool - SessionDomain string - SessionDisableHTTPOnly bool // used to allow for cross domain cookies/javascript cookies. - SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers - SessionNameInHTTPHeader string - SessionEnableSidInURLQuery bool // enable get the sessionId from Url Query params - SessionCookieSameSite http.SameSite -} - -// LogConfig holds Log related config -type LogConfig struct { - AccessLogs bool - EnableStaticLogs bool //log static files requests default: false - AccessLogsFormat string //access log format: JSON_FORMAT, APACHE_FORMAT or empty string - FileLineNum bool - Outputs map[string]string // Store Adaptor : config -} - -var ( - // BConfig is the default config for Application - BConfig *Config - // AppConfig is the instance of Config, store the config information from file - AppConfig *beegoAppConfig - // AppPath is the absolute path to the app - AppPath string - // GlobalSessions is the instance for the session manager - GlobalSessions *session.Manager - - // appConfigPath is the path to the config files - appConfigPath string - // appConfigProvider is the provider for the config, default is ini - appConfigProvider = "ini" - // WorkPath is the absolute path to project root directory - WorkPath string -) - -func init() { - BConfig = newBConfig() - var err error - if AppPath, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil { - panic(err) - } - WorkPath, err = os.Getwd() - if err != nil { - panic(err) - } - var filename = "app.conf" - if os.Getenv("BEEGO_RUNMODE") != "" { - filename = os.Getenv("BEEGO_RUNMODE") + ".app.conf" - } - appConfigPath = filepath.Join(WorkPath, "conf", filename) - if configPath := os.Getenv("BEEGO_CONFIG_PATH"); configPath != "" { - appConfigPath = configPath - } - if !utils.FileExists(appConfigPath) { - appConfigPath = filepath.Join(AppPath, "conf", filename) - if !utils.FileExists(appConfigPath) { - AppConfig = &beegoAppConfig{innerConfig: config.NewFakeConfig()} - return - } - } - if err = parseConfig(appConfigPath); err != nil { - panic(err) - } -} - -func recoverPanic(ctx *context.Context) { - if err := recover(); err != nil { - if err == ErrAbort { - return - } - if !BConfig.RecoverPanic { - panic(err) - } - if BConfig.EnableErrorsShow { - if _, ok := ErrorMaps[fmt.Sprint(err)]; ok { - exception(fmt.Sprint(err), ctx) - return - } - } - var stack string - logs.Critical("the request url is ", ctx.Input.URL()) - logs.Critical("Handler crashed with error", err) - for i := 1; ; i++ { - _, file, line, ok := runtime.Caller(i) - if !ok { - break - } - logs.Critical(fmt.Sprintf("%s:%d", file, line)) - stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line)) - } - if BConfig.RunMode == DEV && BConfig.EnableErrorsRender { - showErr(err, ctx, stack) - } - if ctx.Output.Status != 0 { - ctx.ResponseWriter.WriteHeader(ctx.Output.Status) - } else { - ctx.ResponseWriter.WriteHeader(500) - } - } -} - -func newBConfig() *Config { - return &Config{ - AppName: "beego", - RunMode: PROD, - RouterCaseSensitive: true, - ServerName: "beegoServer:" + VERSION, - RecoverPanic: true, - RecoverFunc: recoverPanic, - CopyRequestBody: false, - EnableGzip: false, - MaxMemory: 1 << 26, //64MB - EnableErrorsShow: true, - EnableErrorsRender: true, - Listen: Listen{ - Graceful: false, - ServerTimeOut: 0, - ListenTCP4: false, - EnableHTTP: true, - AutoTLS: false, - Domains: []string{}, - TLSCacheDir: ".", - HTTPAddr: "", - HTTPPort: 8080, - EnableHTTPS: false, - HTTPSAddr: "", - HTTPSPort: 10443, - HTTPSCertFile: "", - HTTPSKeyFile: "", - EnableAdmin: false, - AdminAddr: "", - AdminPort: 8088, - EnableFcgi: false, - EnableStdIo: false, - ClientAuth: tls.RequireAndVerifyClientCert, - }, - WebConfig: WebConfig{ - AutoRender: true, - EnableDocs: false, - FlashName: "BEEGO_FLASH", - FlashSeparator: "BEEGOFLASH", - DirectoryIndex: false, - StaticDir: map[string]string{"/static": "static"}, - StaticExtensionsToGzip: []string{".css", ".js"}, - StaticCacheFileSize: 1024 * 100, - StaticCacheFileNum: 1000, - TemplateLeft: "{{", - TemplateRight: "}}", - ViewsPath: "views", - EnableXSRF: false, - XSRFKey: "beegoxsrf", - XSRFExpire: 0, - Session: SessionConfig{ - SessionOn: false, - SessionProvider: "memory", - SessionName: "beegosessionID", - SessionGCMaxLifetime: 3600, - SessionProviderConfig: "", - SessionDisableHTTPOnly: false, - SessionCookieLifeTime: 0, //set cookie default is the browser life - SessionAutoSetCookie: true, - SessionDomain: "", - SessionEnableSidInHTTPHeader: false, // enable store/get the sessionId into/from http headers - SessionNameInHTTPHeader: "Beegosessionid", - SessionEnableSidInURLQuery: false, // enable get the sessionId from Url Query params - SessionCookieSameSite: http.SameSiteDefaultMode, - }, - }, - Log: LogConfig{ - AccessLogs: false, - EnableStaticLogs: false, - AccessLogsFormat: "APACHE_FORMAT", - FileLineNum: true, - Outputs: map[string]string{"console": ""}, - }, - } -} - -// now only support ini, next will support json. -func parseConfig(appConfigPath string) (err error) { - AppConfig, err = newAppConfig(appConfigProvider, appConfigPath) - if err != nil { - return err - } - return assignConfig(AppConfig) -} - -func assignConfig(ac config.Configer) error { - for _, i := range []interface{}{BConfig, &BConfig.Listen, &BConfig.WebConfig, &BConfig.Log, &BConfig.WebConfig.Session} { - assignSingleConfig(i, ac) - } - // set the run mode first - if envRunMode := os.Getenv("BEEGO_RUNMODE"); envRunMode != "" { - BConfig.RunMode = envRunMode - } else if runMode := ac.String("RunMode"); runMode != "" { - BConfig.RunMode = runMode - } - - if sd := ac.String("StaticDir"); sd != "" { - BConfig.WebConfig.StaticDir = map[string]string{} - sds := strings.Fields(sd) - for _, v := range sds { - if url2fsmap := strings.SplitN(v, ":", 2); len(url2fsmap) == 2 { - BConfig.WebConfig.StaticDir["/"+strings.Trim(url2fsmap[0], "/")] = url2fsmap[1] - } else { - BConfig.WebConfig.StaticDir["/"+strings.Trim(url2fsmap[0], "/")] = url2fsmap[0] - } - } - } - - if sgz := ac.String("StaticExtensionsToGzip"); sgz != "" { - extensions := strings.Split(sgz, ",") - fileExts := []string{} - for _, ext := range extensions { - ext = strings.TrimSpace(ext) - if ext == "" { - continue - } - if !strings.HasPrefix(ext, ".") { - ext = "." + ext - } - fileExts = append(fileExts, ext) - } - if len(fileExts) > 0 { - BConfig.WebConfig.StaticExtensionsToGzip = fileExts - } - } - - if sfs, err := ac.Int("StaticCacheFileSize"); err == nil { - BConfig.WebConfig.StaticCacheFileSize = sfs - } - - if sfn, err := ac.Int("StaticCacheFileNum"); err == nil { - BConfig.WebConfig.StaticCacheFileNum = sfn - } - - if lo := ac.String("LogOutputs"); lo != "" { - // if lo is not nil or empty - // means user has set his own LogOutputs - // clear the default setting to BConfig.Log.Outputs - BConfig.Log.Outputs = make(map[string]string) - los := strings.Split(lo, ";") - for _, v := range los { - if logType2Config := strings.SplitN(v, ",", 2); len(logType2Config) == 2 { - BConfig.Log.Outputs[logType2Config[0]] = logType2Config[1] - } else { - continue - } - } - } - - //init log - logs.Reset() - for adaptor, config := range BConfig.Log.Outputs { - err := logs.SetLogger(adaptor, config) - if err != nil { - fmt.Fprintln(os.Stderr, fmt.Sprintf("%s with the config %q got err:%s", adaptor, config, err.Error())) - } - } - logs.SetLogFuncCall(BConfig.Log.FileLineNum) - - return nil -} - -func assignSingleConfig(p interface{}, ac config.Configer) { - pt := reflect.TypeOf(p) - if pt.Kind() != reflect.Ptr { - return - } - pt = pt.Elem() - if pt.Kind() != reflect.Struct { - return - } - pv := reflect.ValueOf(p).Elem() - - for i := 0; i < pt.NumField(); i++ { - pf := pv.Field(i) - if !pf.CanSet() { - continue - } - name := pt.Field(i).Name - switch pf.Kind() { - case reflect.String: - pf.SetString(ac.DefaultString(name, pf.String())) - case reflect.Int, reflect.Int64: - pf.SetInt(ac.DefaultInt64(name, pf.Int())) - case reflect.Bool: - pf.SetBool(ac.DefaultBool(name, pf.Bool())) - case reflect.Struct: - default: - //do nothing here - } - } - -} - -// LoadAppConfig allow developer to apply a config file -func LoadAppConfig(adapterName, configPath string) error { - absConfigPath, err := filepath.Abs(configPath) - if err != nil { - return err - } - - if !utils.FileExists(absConfigPath) { - return fmt.Errorf("the target config file: %s don't exist", configPath) - } - - appConfigPath = absConfigPath - appConfigProvider = adapterName - - return parseConfig(appConfigPath) -} - -type beegoAppConfig struct { - innerConfig config.Configer -} - -func newAppConfig(appConfigProvider, appConfigPath string) (*beegoAppConfig, error) { - ac, err := config.NewConfig(appConfigProvider, appConfigPath) - if err != nil { - return nil, err - } - return &beegoAppConfig{ac}, nil -} - -func (b *beegoAppConfig) Set(key, val string) error { - if err := b.innerConfig.Set(BConfig.RunMode+"::"+key, val); err != nil { - return b.innerConfig.Set(key, val) - } - return nil -} - -func (b *beegoAppConfig) String(key string) string { - if v := b.innerConfig.String(BConfig.RunMode + "::" + key); v != "" { - return v - } - return b.innerConfig.String(key) -} - -func (b *beegoAppConfig) Strings(key string) []string { - if v := b.innerConfig.Strings(BConfig.RunMode + "::" + key); len(v) > 0 { - return v - } - return b.innerConfig.Strings(key) -} - -func (b *beegoAppConfig) Int(key string) (int, error) { - if v, err := b.innerConfig.Int(BConfig.RunMode + "::" + key); err == nil { - return v, nil - } - return b.innerConfig.Int(key) -} - -func (b *beegoAppConfig) Int64(key string) (int64, error) { - if v, err := b.innerConfig.Int64(BConfig.RunMode + "::" + key); err == nil { - return v, nil - } - return b.innerConfig.Int64(key) -} - -func (b *beegoAppConfig) Bool(key string) (bool, error) { - if v, err := b.innerConfig.Bool(BConfig.RunMode + "::" + key); err == nil { - return v, nil - } - return b.innerConfig.Bool(key) -} - -func (b *beegoAppConfig) Float(key string) (float64, error) { - if v, err := b.innerConfig.Float(BConfig.RunMode + "::" + key); err == nil { - return v, nil - } - return b.innerConfig.Float(key) -} - -func (b *beegoAppConfig) DefaultString(key string, defaultVal string) string { - if v := b.String(key); v != "" { - return v - } - return defaultVal -} - -func (b *beegoAppConfig) DefaultStrings(key string, defaultVal []string) []string { - if v := b.Strings(key); len(v) != 0 { - return v - } - return defaultVal -} - -func (b *beegoAppConfig) DefaultInt(key string, defaultVal int) int { - if v, err := b.Int(key); err == nil { - return v - } - return defaultVal -} - -func (b *beegoAppConfig) DefaultInt64(key string, defaultVal int64) int64 { - if v, err := b.Int64(key); err == nil { - return v - } - return defaultVal -} - -func (b *beegoAppConfig) DefaultBool(key string, defaultVal bool) bool { - if v, err := b.Bool(key); err == nil { - return v - } - return defaultVal -} - -func (b *beegoAppConfig) DefaultFloat(key string, defaultVal float64) float64 { - if v, err := b.Float(key); err == nil { - return v - } - return defaultVal -} - -func (b *beegoAppConfig) DIY(key string) (interface{}, error) { - return b.innerConfig.DIY(key) -} - -func (b *beegoAppConfig) GetSection(section string) (map[string]string, error) { - return b.innerConfig.GetSection(section) -} - -func (b *beegoAppConfig) SaveConfigFile(filename string) error { - return b.innerConfig.SaveConfigFile(filename) -} diff --git a/vendor/github.com/astaxie/beego/config/config.go b/vendor/github.com/astaxie/beego/config/config.go deleted file mode 100644 index bfd79e85..00000000 --- a/vendor/github.com/astaxie/beego/config/config.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package config is used to parse config. -// Usage: -// import "github.com/astaxie/beego/config" -//Examples. -// -// cnf, err := config.NewConfig("ini", "config.conf") -// -// cnf APIS: -// -// cnf.Set(key, val string) error -// cnf.String(key string) string -// cnf.Strings(key string) []string -// cnf.Int(key string) (int, error) -// cnf.Int64(key string) (int64, error) -// cnf.Bool(key string) (bool, error) -// cnf.Float(key string) (float64, error) -// cnf.DefaultString(key string, defaultVal string) string -// cnf.DefaultStrings(key string, defaultVal []string) []string -// cnf.DefaultInt(key string, defaultVal int) int -// cnf.DefaultInt64(key string, defaultVal int64) int64 -// cnf.DefaultBool(key string, defaultVal bool) bool -// cnf.DefaultFloat(key string, defaultVal float64) float64 -// cnf.DIY(key string) (interface{}, error) -// cnf.GetSection(section string) (map[string]string, error) -// cnf.SaveConfigFile(filename string) error -//More docs http://beego.me/docs/module/config.md -package config - -import ( - "fmt" - "os" - "reflect" - "time" -) - -// Configer defines how to get and set value from configuration raw data. -type Configer interface { - Set(key, val string) error //support section::key type in given key when using ini type. - String(key string) string //support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same. - Strings(key string) []string //get string slice - Int(key string) (int, error) - Int64(key string) (int64, error) - Bool(key string) (bool, error) - Float(key string) (float64, error) - DefaultString(key string, defaultVal string) string // support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same. - DefaultStrings(key string, defaultVal []string) []string //get string slice - DefaultInt(key string, defaultVal int) int - DefaultInt64(key string, defaultVal int64) int64 - DefaultBool(key string, defaultVal bool) bool - DefaultFloat(key string, defaultVal float64) float64 - DIY(key string) (interface{}, error) - GetSection(section string) (map[string]string, error) - SaveConfigFile(filename string) error -} - -// Config is the adapter interface for parsing config file to get raw data to Configer. -type Config interface { - Parse(key string) (Configer, error) - ParseData(data []byte) (Configer, error) -} - -var adapters = make(map[string]Config) - -// Register makes a config adapter available by the adapter name. -// If Register is called twice with the same name or if driver is nil, -// it panics. -func Register(name string, adapter Config) { - if adapter == nil { - panic("config: Register adapter is nil") - } - if _, ok := adapters[name]; ok { - panic("config: Register called twice for adapter " + name) - } - adapters[name] = adapter -} - -// NewConfig adapterName is ini/json/xml/yaml. -// filename is the config file path. -func NewConfig(adapterName, filename string) (Configer, error) { - adapter, ok := adapters[adapterName] - if !ok { - return nil, fmt.Errorf("config: unknown adaptername %q (forgotten import?)", adapterName) - } - return adapter.Parse(filename) -} - -// NewConfigData adapterName is ini/json/xml/yaml. -// data is the config data. -func NewConfigData(adapterName string, data []byte) (Configer, error) { - adapter, ok := adapters[adapterName] - if !ok { - return nil, fmt.Errorf("config: unknown adaptername %q (forgotten import?)", adapterName) - } - return adapter.ParseData(data) -} - -// ExpandValueEnvForMap convert all string value with environment variable. -func ExpandValueEnvForMap(m map[string]interface{}) map[string]interface{} { - for k, v := range m { - switch value := v.(type) { - case string: - m[k] = ExpandValueEnv(value) - case map[string]interface{}: - m[k] = ExpandValueEnvForMap(value) - case map[string]string: - for k2, v2 := range value { - value[k2] = ExpandValueEnv(v2) - } - m[k] = value - } - } - return m -} - -// ExpandValueEnv returns value of convert with environment variable. -// -// Return environment variable if value start with "${" and end with "}". -// Return default value if environment variable is empty or not exist. -// -// It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue". -// Examples: -// v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable. -// v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/". -// v3 := config.ExpandValueEnv("Astaxie") // return the value "Astaxie". -func ExpandValueEnv(value string) (realValue string) { - realValue = value - - vLen := len(value) - // 3 = ${} - if vLen < 3 { - return - } - // Need start with "${" and end with "}", then return. - if value[0] != '$' || value[1] != '{' || value[vLen-1] != '}' { - return - } - - key := "" - defaultV := "" - // value start with "${" - for i := 2; i < vLen; i++ { - if value[i] == '|' && (i+1 < vLen && value[i+1] == '|') { - key = value[2:i] - defaultV = value[i+2 : vLen-1] // other string is default value. - break - } else if value[i] == '}' { - key = value[2:i] - break - } - } - - realValue = os.Getenv(key) - if realValue == "" { - realValue = defaultV - } - - return -} - -// ParseBool returns the boolean value represented by the string. -// -// It accepts 1, 1.0, t, T, TRUE, true, True, YES, yes, Yes,Y, y, ON, on, On, -// 0, 0.0, f, F, FALSE, false, False, NO, no, No, N,n, OFF, off, Off. -// Any other value returns an error. -func ParseBool(val interface{}) (value bool, err error) { - if val != nil { - switch v := val.(type) { - case bool: - return v, nil - case string: - switch v { - case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "Y", "y", "ON", "on", "On": - return true, nil - case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "N", "n", "OFF", "off", "Off": - return false, nil - } - case int8, int32, int64: - strV := fmt.Sprintf("%d", v) - if strV == "1" { - return true, nil - } else if strV == "0" { - return false, nil - } - case float64: - if v == 1.0 { - return true, nil - } else if v == 0.0 { - return false, nil - } - } - return false, fmt.Errorf("parsing %q: invalid syntax", val) - } - return false, fmt.Errorf("parsing : invalid syntax") -} - -// ToString converts values of any type to string. -func ToString(x interface{}) string { - switch y := x.(type) { - - // Handle dates with special logic - // This needs to come above the fmt.Stringer - // test since time.Time's have a .String() - // method - case time.Time: - return y.Format("A Monday") - - // Handle type string - case string: - return y - - // Handle type with .String() method - case fmt.Stringer: - return y.String() - - // Handle type with .Error() method - case error: - return y.Error() - - } - - // Handle named string type - if v := reflect.ValueOf(x); v.Kind() == reflect.String { - return v.String() - } - - // Fallback to fmt package for anything else like numeric types - return fmt.Sprint(x) -} diff --git a/vendor/github.com/astaxie/beego/config/fake.go b/vendor/github.com/astaxie/beego/config/fake.go deleted file mode 100644 index d21ab820..00000000 --- a/vendor/github.com/astaxie/beego/config/fake.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "errors" - "strconv" - "strings" -) - -type fakeConfigContainer struct { - data map[string]string -} - -func (c *fakeConfigContainer) getData(key string) string { - return c.data[strings.ToLower(key)] -} - -func (c *fakeConfigContainer) Set(key, val string) error { - c.data[strings.ToLower(key)] = val - return nil -} - -func (c *fakeConfigContainer) String(key string) string { - return c.getData(key) -} - -func (c *fakeConfigContainer) DefaultString(key string, defaultval string) string { - v := c.String(key) - if v == "" { - return defaultval - } - return v -} - -func (c *fakeConfigContainer) Strings(key string) []string { - v := c.String(key) - if v == "" { - return nil - } - return strings.Split(v, ";") -} - -func (c *fakeConfigContainer) DefaultStrings(key string, defaultval []string) []string { - v := c.Strings(key) - if v == nil { - return defaultval - } - return v -} - -func (c *fakeConfigContainer) Int(key string) (int, error) { - return strconv.Atoi(c.getData(key)) -} - -func (c *fakeConfigContainer) DefaultInt(key string, defaultval int) int { - v, err := c.Int(key) - if err != nil { - return defaultval - } - return v -} - -func (c *fakeConfigContainer) Int64(key string) (int64, error) { - return strconv.ParseInt(c.getData(key), 10, 64) -} - -func (c *fakeConfigContainer) DefaultInt64(key string, defaultval int64) int64 { - v, err := c.Int64(key) - if err != nil { - return defaultval - } - return v -} - -func (c *fakeConfigContainer) Bool(key string) (bool, error) { - return ParseBool(c.getData(key)) -} - -func (c *fakeConfigContainer) DefaultBool(key string, defaultval bool) bool { - v, err := c.Bool(key) - if err != nil { - return defaultval - } - return v -} - -func (c *fakeConfigContainer) Float(key string) (float64, error) { - return strconv.ParseFloat(c.getData(key), 64) -} - -func (c *fakeConfigContainer) DefaultFloat(key string, defaultval float64) float64 { - v, err := c.Float(key) - if err != nil { - return defaultval - } - return v -} - -func (c *fakeConfigContainer) DIY(key string) (interface{}, error) { - if v, ok := c.data[strings.ToLower(key)]; ok { - return v, nil - } - return nil, errors.New("key not find") -} - -func (c *fakeConfigContainer) GetSection(section string) (map[string]string, error) { - return nil, errors.New("not implement in the fakeConfigContainer") -} - -func (c *fakeConfigContainer) SaveConfigFile(filename string) error { - return errors.New("not implement in the fakeConfigContainer") -} - -var _ Configer = new(fakeConfigContainer) - -// NewFakeConfig return a fake Configer -func NewFakeConfig() Configer { - return &fakeConfigContainer{ - data: make(map[string]string), - } -} diff --git a/vendor/github.com/astaxie/beego/config/ini.go b/vendor/github.com/astaxie/beego/config/ini.go deleted file mode 100644 index 002e5e05..00000000 --- a/vendor/github.com/astaxie/beego/config/ini.go +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "bufio" - "bytes" - "errors" - "io" - "io/ioutil" - "os" - "os/user" - "path/filepath" - "strconv" - "strings" - "sync" -) - -var ( - defaultSection = "default" // default section means if some ini items not in a section, make them in default section, - bNumComment = []byte{'#'} // number signal - bSemComment = []byte{';'} // semicolon signal - bEmpty = []byte{} - bEqual = []byte{'='} // equal signal - bDQuote = []byte{'"'} // quote signal - sectionStart = []byte{'['} // section start signal - sectionEnd = []byte{']'} // section end signal - lineBreak = "\n" -) - -// IniConfig implements Config to parse ini file. -type IniConfig struct { -} - -// Parse creates a new Config and parses the file configuration from the named file. -func (ini *IniConfig) Parse(name string) (Configer, error) { - return ini.parseFile(name) -} - -func (ini *IniConfig) parseFile(name string) (*IniConfigContainer, error) { - data, err := ioutil.ReadFile(name) - if err != nil { - return nil, err - } - - return ini.parseData(filepath.Dir(name), data) -} - -func (ini *IniConfig) parseData(dir string, data []byte) (*IniConfigContainer, error) { - cfg := &IniConfigContainer{ - data: make(map[string]map[string]string), - sectionComment: make(map[string]string), - keyComment: make(map[string]string), - RWMutex: sync.RWMutex{}, - } - cfg.Lock() - defer cfg.Unlock() - - var comment bytes.Buffer - buf := bufio.NewReader(bytes.NewBuffer(data)) - // check the BOM - head, err := buf.Peek(3) - if err == nil && head[0] == 239 && head[1] == 187 && head[2] == 191 { - for i := 1; i <= 3; i++ { - buf.ReadByte() - } - } - section := defaultSection - tmpBuf := bytes.NewBuffer(nil) - for { - tmpBuf.Reset() - - shouldBreak := false - for { - tmp, isPrefix, err := buf.ReadLine() - if err == io.EOF { - shouldBreak = true - break - } - - //It might be a good idea to throw a error on all unknonw errors? - if _, ok := err.(*os.PathError); ok { - return nil, err - } - - tmpBuf.Write(tmp) - if isPrefix { - continue - } - - if !isPrefix { - break - } - } - if shouldBreak { - break - } - - line := tmpBuf.Bytes() - line = bytes.TrimSpace(line) - if bytes.Equal(line, bEmpty) { - continue - } - var bComment []byte - switch { - case bytes.HasPrefix(line, bNumComment): - bComment = bNumComment - case bytes.HasPrefix(line, bSemComment): - bComment = bSemComment - } - if bComment != nil { - line = bytes.TrimLeft(line, string(bComment)) - // Need append to a new line if multi-line comments. - if comment.Len() > 0 { - comment.WriteByte('\n') - } - comment.Write(line) - continue - } - - if bytes.HasPrefix(line, sectionStart) && bytes.HasSuffix(line, sectionEnd) { - section = strings.ToLower(string(line[1 : len(line)-1])) // section name case insensitive - if comment.Len() > 0 { - cfg.sectionComment[section] = comment.String() - comment.Reset() - } - if _, ok := cfg.data[section]; !ok { - cfg.data[section] = make(map[string]string) - } - continue - } - - if _, ok := cfg.data[section]; !ok { - cfg.data[section] = make(map[string]string) - } - keyValue := bytes.SplitN(line, bEqual, 2) - - key := string(bytes.TrimSpace(keyValue[0])) // key name case insensitive - key = strings.ToLower(key) - - // handle include "other.conf" - if len(keyValue) == 1 && strings.HasPrefix(key, "include") { - - includefiles := strings.Fields(key) - if includefiles[0] == "include" && len(includefiles) == 2 { - - otherfile := strings.Trim(includefiles[1], "\"") - if !filepath.IsAbs(otherfile) { - otherfile = filepath.Join(dir, otherfile) - } - - i, err := ini.parseFile(otherfile) - if err != nil { - return nil, err - } - - for sec, dt := range i.data { - if _, ok := cfg.data[sec]; !ok { - cfg.data[sec] = make(map[string]string) - } - for k, v := range dt { - cfg.data[sec][k] = v - } - } - - for sec, comm := range i.sectionComment { - cfg.sectionComment[sec] = comm - } - - for k, comm := range i.keyComment { - cfg.keyComment[k] = comm - } - - continue - } - } - - if len(keyValue) != 2 { - return nil, errors.New("read the content error: \"" + string(line) + "\", should key = val") - } - val := bytes.TrimSpace(keyValue[1]) - if bytes.HasPrefix(val, bDQuote) { - val = bytes.Trim(val, `"`) - } - - cfg.data[section][key] = ExpandValueEnv(string(val)) - if comment.Len() > 0 { - cfg.keyComment[section+"."+key] = comment.String() - comment.Reset() - } - - } - return cfg, nil -} - -// ParseData parse ini the data -// When include other.conf,other.conf is either absolute directory -// or under beego in default temporary directory(/tmp/beego[-username]). -func (ini *IniConfig) ParseData(data []byte) (Configer, error) { - dir := "beego" - currentUser, err := user.Current() - if err == nil { - dir = "beego-" + currentUser.Username - } - dir = filepath.Join(os.TempDir(), dir) - if err = os.MkdirAll(dir, os.ModePerm); err != nil { - return nil, err - } - - return ini.parseData(dir, data) -} - -// IniConfigContainer A Config represents the ini configuration. -// When set and get value, support key as section:name type. -type IniConfigContainer struct { - data map[string]map[string]string // section=> key:val - sectionComment map[string]string // section : comment - keyComment map[string]string // id: []{comment, key...}; id 1 is for main comment. - sync.RWMutex -} - -// Bool returns the boolean value for a given key. -func (c *IniConfigContainer) Bool(key string) (bool, error) { - return ParseBool(c.getdata(key)) -} - -// DefaultBool returns the boolean value for a given key. -// if err != nil return defaultval -func (c *IniConfigContainer) DefaultBool(key string, defaultval bool) bool { - v, err := c.Bool(key) - if err != nil { - return defaultval - } - return v -} - -// Int returns the integer value for a given key. -func (c *IniConfigContainer) Int(key string) (int, error) { - return strconv.Atoi(c.getdata(key)) -} - -// DefaultInt returns the integer value for a given key. -// if err != nil return defaultval -func (c *IniConfigContainer) DefaultInt(key string, defaultval int) int { - v, err := c.Int(key) - if err != nil { - return defaultval - } - return v -} - -// Int64 returns the int64 value for a given key. -func (c *IniConfigContainer) Int64(key string) (int64, error) { - return strconv.ParseInt(c.getdata(key), 10, 64) -} - -// DefaultInt64 returns the int64 value for a given key. -// if err != nil return defaultval -func (c *IniConfigContainer) DefaultInt64(key string, defaultval int64) int64 { - v, err := c.Int64(key) - if err != nil { - return defaultval - } - return v -} - -// Float returns the float value for a given key. -func (c *IniConfigContainer) Float(key string) (float64, error) { - return strconv.ParseFloat(c.getdata(key), 64) -} - -// DefaultFloat returns the float64 value for a given key. -// if err != nil return defaultval -func (c *IniConfigContainer) DefaultFloat(key string, defaultval float64) float64 { - v, err := c.Float(key) - if err != nil { - return defaultval - } - return v -} - -// String returns the string value for a given key. -func (c *IniConfigContainer) String(key string) string { - return c.getdata(key) -} - -// DefaultString returns the string value for a given key. -// if err != nil return defaultval -func (c *IniConfigContainer) DefaultString(key string, defaultval string) string { - v := c.String(key) - if v == "" { - return defaultval - } - return v -} - -// Strings returns the []string value for a given key. -// Return nil if config value does not exist or is empty. -func (c *IniConfigContainer) Strings(key string) []string { - v := c.String(key) - if v == "" { - return nil - } - return strings.Split(v, ";") -} - -// DefaultStrings returns the []string value for a given key. -// if err != nil return defaultval -func (c *IniConfigContainer) DefaultStrings(key string, defaultval []string) []string { - v := c.Strings(key) - if v == nil { - return defaultval - } - return v -} - -// GetSection returns map for the given section -func (c *IniConfigContainer) GetSection(section string) (map[string]string, error) { - if v, ok := c.data[section]; ok { - return v, nil - } - return nil, errors.New("not exist section") -} - -// SaveConfigFile save the config into file. -// -// BUG(env): The environment variable config item will be saved with real value in SaveConfigFile Function. -func (c *IniConfigContainer) SaveConfigFile(filename string) (err error) { - // Write configuration file by filename. - f, err := os.Create(filename) - if err != nil { - return err - } - defer f.Close() - - // Get section or key comments. Fixed #1607 - getCommentStr := func(section, key string) string { - var ( - comment string - ok bool - ) - if len(key) == 0 { - comment, ok = c.sectionComment[section] - } else { - comment, ok = c.keyComment[section+"."+key] - } - - if ok { - // Empty comment - if len(comment) == 0 || len(strings.TrimSpace(comment)) == 0 { - return string(bNumComment) - } - prefix := string(bNumComment) - // Add the line head character "#" - return prefix + strings.Replace(comment, lineBreak, lineBreak+prefix, -1) - } - return "" - } - - buf := bytes.NewBuffer(nil) - // Save default section at first place - if dt, ok := c.data[defaultSection]; ok { - for key, val := range dt { - if key != " " { - // Write key comments. - if v := getCommentStr(defaultSection, key); len(v) > 0 { - if _, err = buf.WriteString(v + lineBreak); err != nil { - return err - } - } - - // Write key and value. - if _, err = buf.WriteString(key + string(bEqual) + val + lineBreak); err != nil { - return err - } - } - } - - // Put a line between sections. - if _, err = buf.WriteString(lineBreak); err != nil { - return err - } - } - // Save named sections - for section, dt := range c.data { - if section != defaultSection { - // Write section comments. - if v := getCommentStr(section, ""); len(v) > 0 { - if _, err = buf.WriteString(v + lineBreak); err != nil { - return err - } - } - - // Write section name. - if _, err = buf.WriteString(string(sectionStart) + section + string(sectionEnd) + lineBreak); err != nil { - return err - } - - for key, val := range dt { - if key != " " { - // Write key comments. - if v := getCommentStr(section, key); len(v) > 0 { - if _, err = buf.WriteString(v + lineBreak); err != nil { - return err - } - } - - // Write key and value. - if _, err = buf.WriteString(key + string(bEqual) + val + lineBreak); err != nil { - return err - } - } - } - - // Put a line between sections. - if _, err = buf.WriteString(lineBreak); err != nil { - return err - } - } - } - _, err = buf.WriteTo(f) - return err -} - -// Set writes a new value for key. -// if write to one section, the key need be "section::key". -// if the section is not existed, it panics. -func (c *IniConfigContainer) Set(key, value string) error { - c.Lock() - defer c.Unlock() - if len(key) == 0 { - return errors.New("key is empty") - } - - var ( - section, k string - sectionKey = strings.Split(strings.ToLower(key), "::") - ) - - if len(sectionKey) >= 2 { - section = sectionKey[0] - k = sectionKey[1] - } else { - section = defaultSection - k = sectionKey[0] - } - - if _, ok := c.data[section]; !ok { - c.data[section] = make(map[string]string) - } - c.data[section][k] = value - return nil -} - -// DIY returns the raw value by a given key. -func (c *IniConfigContainer) DIY(key string) (v interface{}, err error) { - if v, ok := c.data[strings.ToLower(key)]; ok { - return v, nil - } - return v, errors.New("key not find") -} - -// section.key or key -func (c *IniConfigContainer) getdata(key string) string { - if len(key) == 0 { - return "" - } - c.RLock() - defer c.RUnlock() - - var ( - section, k string - sectionKey = strings.Split(strings.ToLower(key), "::") - ) - if len(sectionKey) >= 2 { - section = sectionKey[0] - k = sectionKey[1] - } else { - section = defaultSection - k = sectionKey[0] - } - if v, ok := c.data[section]; ok { - if vv, ok := v[k]; ok { - return vv - } - } - return "" -} - -func init() { - Register("ini", &IniConfig{}) -} diff --git a/vendor/github.com/astaxie/beego/config/json.go b/vendor/github.com/astaxie/beego/config/json.go deleted file mode 100644 index c4ef25cd..00000000 --- a/vendor/github.com/astaxie/beego/config/json.go +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "os" - "strconv" - "strings" - "sync" -) - -// JSONConfig is a json config parser and implements Config interface. -type JSONConfig struct { -} - -// Parse returns a ConfigContainer with parsed json config map. -func (js *JSONConfig) Parse(filename string) (Configer, error) { - file, err := os.Open(filename) - if err != nil { - return nil, err - } - defer file.Close() - content, err := ioutil.ReadAll(file) - if err != nil { - return nil, err - } - - return js.ParseData(content) -} - -// ParseData returns a ConfigContainer with json string -func (js *JSONConfig) ParseData(data []byte) (Configer, error) { - x := &JSONConfigContainer{ - data: make(map[string]interface{}), - } - err := json.Unmarshal(data, &x.data) - if err != nil { - var wrappingArray []interface{} - err2 := json.Unmarshal(data, &wrappingArray) - if err2 != nil { - return nil, err - } - x.data["rootArray"] = wrappingArray - } - - x.data = ExpandValueEnvForMap(x.data) - - return x, nil -} - -// JSONConfigContainer A Config represents the json configuration. -// Only when get value, support key as section:name type. -type JSONConfigContainer struct { - data map[string]interface{} - sync.RWMutex -} - -// Bool returns the boolean value for a given key. -func (c *JSONConfigContainer) Bool(key string) (bool, error) { - val := c.getData(key) - if val != nil { - return ParseBool(val) - } - return false, fmt.Errorf("not exist key: %q", key) -} - -// DefaultBool return the bool value if has no error -// otherwise return the defaultval -func (c *JSONConfigContainer) DefaultBool(key string, defaultval bool) bool { - if v, err := c.Bool(key); err == nil { - return v - } - return defaultval -} - -// Int returns the integer value for a given key. -func (c *JSONConfigContainer) Int(key string) (int, error) { - val := c.getData(key) - if val != nil { - if v, ok := val.(float64); ok { - return int(v), nil - } else if v, ok := val.(string); ok { - return strconv.Atoi(v) - } - return 0, errors.New("not valid value") - } - return 0, errors.New("not exist key:" + key) -} - -// DefaultInt returns the integer value for a given key. -// if err != nil return defaultval -func (c *JSONConfigContainer) DefaultInt(key string, defaultval int) int { - if v, err := c.Int(key); err == nil { - return v - } - return defaultval -} - -// Int64 returns the int64 value for a given key. -func (c *JSONConfigContainer) Int64(key string) (int64, error) { - val := c.getData(key) - if val != nil { - if v, ok := val.(float64); ok { - return int64(v), nil - } - return 0, errors.New("not int64 value") - } - return 0, errors.New("not exist key:" + key) -} - -// DefaultInt64 returns the int64 value for a given key. -// if err != nil return defaultval -func (c *JSONConfigContainer) DefaultInt64(key string, defaultval int64) int64 { - if v, err := c.Int64(key); err == nil { - return v - } - return defaultval -} - -// Float returns the float value for a given key. -func (c *JSONConfigContainer) Float(key string) (float64, error) { - val := c.getData(key) - if val != nil { - if v, ok := val.(float64); ok { - return v, nil - } - return 0.0, errors.New("not float64 value") - } - return 0.0, errors.New("not exist key:" + key) -} - -// DefaultFloat returns the float64 value for a given key. -// if err != nil return defaultval -func (c *JSONConfigContainer) DefaultFloat(key string, defaultval float64) float64 { - if v, err := c.Float(key); err == nil { - return v - } - return defaultval -} - -// String returns the string value for a given key. -func (c *JSONConfigContainer) String(key string) string { - val := c.getData(key) - if val != nil { - if v, ok := val.(string); ok { - return v - } - } - return "" -} - -// DefaultString returns the string value for a given key. -// if err != nil return defaultval -func (c *JSONConfigContainer) DefaultString(key string, defaultval string) string { - // TODO FIXME should not use "" to replace non existence - if v := c.String(key); v != "" { - return v - } - return defaultval -} - -// Strings returns the []string value for a given key. -func (c *JSONConfigContainer) Strings(key string) []string { - stringVal := c.String(key) - if stringVal == "" { - return nil - } - return strings.Split(c.String(key), ";") -} - -// DefaultStrings returns the []string value for a given key. -// if err != nil return defaultval -func (c *JSONConfigContainer) DefaultStrings(key string, defaultval []string) []string { - if v := c.Strings(key); v != nil { - return v - } - return defaultval -} - -// GetSection returns map for the given section -func (c *JSONConfigContainer) GetSection(section string) (map[string]string, error) { - if v, ok := c.data[section]; ok { - return v.(map[string]string), nil - } - return nil, errors.New("nonexist section " + section) -} - -// SaveConfigFile save the config into file -func (c *JSONConfigContainer) SaveConfigFile(filename string) (err error) { - // Write configuration file by filename. - f, err := os.Create(filename) - if err != nil { - return err - } - defer f.Close() - b, err := json.MarshalIndent(c.data, "", " ") - if err != nil { - return err - } - _, err = f.Write(b) - return err -} - -// Set writes a new value for key. -func (c *JSONConfigContainer) Set(key, val string) error { - c.Lock() - defer c.Unlock() - c.data[key] = val - return nil -} - -// DIY returns the raw value by a given key. -func (c *JSONConfigContainer) DIY(key string) (v interface{}, err error) { - val := c.getData(key) - if val != nil { - return val, nil - } - return nil, errors.New("not exist key") -} - -// section.key or key -func (c *JSONConfigContainer) getData(key string) interface{} { - if len(key) == 0 { - return nil - } - - c.RLock() - defer c.RUnlock() - - sectionKeys := strings.Split(key, "::") - if len(sectionKeys) >= 2 { - curValue, ok := c.data[sectionKeys[0]] - if !ok { - return nil - } - for _, key := range sectionKeys[1:] { - if v, ok := curValue.(map[string]interface{}); ok { - if curValue, ok = v[key]; !ok { - return nil - } - } - } - return curValue - } - if v, ok := c.data[key]; ok { - return v - } - return nil -} - -func init() { - Register("json", &JSONConfig{}) -} diff --git a/vendor/github.com/astaxie/beego/context/acceptencoder.go b/vendor/github.com/astaxie/beego/context/acceptencoder.go deleted file mode 100644 index b4e2492c..00000000 --- a/vendor/github.com/astaxie/beego/context/acceptencoder.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2015 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package context - -import ( - "bytes" - "compress/flate" - "compress/gzip" - "compress/zlib" - "io" - "net/http" - "os" - "strconv" - "strings" - "sync" -) - -var ( - //Default size==20B same as nginx - defaultGzipMinLength = 20 - //Content will only be compressed if content length is either unknown or greater than gzipMinLength. - gzipMinLength = defaultGzipMinLength - //The compression level used for deflate compression. (0-9). - gzipCompressLevel int - //List of HTTP methods to compress. If not set, only GET requests are compressed. - includedMethods map[string]bool - getMethodOnly bool -) - -// InitGzip init the gzipcompress -func InitGzip(minLength, compressLevel int, methods []string) { - if minLength >= 0 { - gzipMinLength = minLength - } - gzipCompressLevel = compressLevel - if gzipCompressLevel < flate.NoCompression || gzipCompressLevel > flate.BestCompression { - gzipCompressLevel = flate.BestSpeed - } - getMethodOnly = (len(methods) == 0) || (len(methods) == 1 && strings.ToUpper(methods[0]) == "GET") - includedMethods = make(map[string]bool, len(methods)) - for _, v := range methods { - includedMethods[strings.ToUpper(v)] = true - } -} - -type resetWriter interface { - io.Writer - Reset(w io.Writer) -} - -type nopResetWriter struct { - io.Writer -} - -func (n nopResetWriter) Reset(w io.Writer) { - //do nothing -} - -type acceptEncoder struct { - name string - levelEncode func(int) resetWriter - customCompressLevelPool *sync.Pool - bestCompressionPool *sync.Pool -} - -func (ac acceptEncoder) encode(wr io.Writer, level int) resetWriter { - if ac.customCompressLevelPool == nil || ac.bestCompressionPool == nil { - return nopResetWriter{wr} - } - var rwr resetWriter - switch level { - case flate.BestSpeed: - rwr = ac.customCompressLevelPool.Get().(resetWriter) - case flate.BestCompression: - rwr = ac.bestCompressionPool.Get().(resetWriter) - default: - rwr = ac.levelEncode(level) - } - rwr.Reset(wr) - return rwr -} - -func (ac acceptEncoder) put(wr resetWriter, level int) { - if ac.customCompressLevelPool == nil || ac.bestCompressionPool == nil { - return - } - wr.Reset(nil) - - //notice - //compressionLevel==BestCompression DOES NOT MATTER - //sync.Pool will not memory leak - - switch level { - case gzipCompressLevel: - ac.customCompressLevelPool.Put(wr) - case flate.BestCompression: - ac.bestCompressionPool.Put(wr) - } -} - -var ( - noneCompressEncoder = acceptEncoder{"", nil, nil, nil} - gzipCompressEncoder = acceptEncoder{ - name: "gzip", - levelEncode: func(level int) resetWriter { wr, _ := gzip.NewWriterLevel(nil, level); return wr }, - customCompressLevelPool: &sync.Pool{New: func() interface{} { wr, _ := gzip.NewWriterLevel(nil, gzipCompressLevel); return wr }}, - bestCompressionPool: &sync.Pool{New: func() interface{} { wr, _ := gzip.NewWriterLevel(nil, flate.BestCompression); return wr }}, - } - - //according to the sec :http://tools.ietf.org/html/rfc2616#section-3.5 ,the deflate compress in http is zlib indeed - //deflate - //The "zlib" format defined in RFC 1950 [31] in combination with - //the "deflate" compression mechanism described in RFC 1951 [29]. - deflateCompressEncoder = acceptEncoder{ - name: "deflate", - levelEncode: func(level int) resetWriter { wr, _ := zlib.NewWriterLevel(nil, level); return wr }, - customCompressLevelPool: &sync.Pool{New: func() interface{} { wr, _ := zlib.NewWriterLevel(nil, gzipCompressLevel); return wr }}, - bestCompressionPool: &sync.Pool{New: func() interface{} { wr, _ := zlib.NewWriterLevel(nil, flate.BestCompression); return wr }}, - } -) - -var ( - encoderMap = map[string]acceptEncoder{ // all the other compress methods will ignore - "gzip": gzipCompressEncoder, - "deflate": deflateCompressEncoder, - "*": gzipCompressEncoder, // * means any compress will accept,we prefer gzip - "identity": noneCompressEncoder, // identity means none-compress - } -) - -// WriteFile reads from file and writes to writer by the specific encoding(gzip/deflate) -func WriteFile(encoding string, writer io.Writer, file *os.File) (bool, string, error) { - return writeLevel(encoding, writer, file, flate.BestCompression) -} - -// WriteBody reads writes content to writer by the specific encoding(gzip/deflate) -func WriteBody(encoding string, writer io.Writer, content []byte) (bool, string, error) { - if encoding == "" || len(content) < gzipMinLength { - _, err := writer.Write(content) - return false, "", err - } - return writeLevel(encoding, writer, bytes.NewReader(content), gzipCompressLevel) -} - -// writeLevel reads from reader,writes to writer by specific encoding and compress level -// the compress level is defined by deflate package -func writeLevel(encoding string, writer io.Writer, reader io.Reader, level int) (bool, string, error) { - var outputWriter resetWriter - var err error - var ce = noneCompressEncoder - - if cf, ok := encoderMap[encoding]; ok { - ce = cf - } - encoding = ce.name - outputWriter = ce.encode(writer, level) - defer ce.put(outputWriter, level) - - _, err = io.Copy(outputWriter, reader) - if err != nil { - return false, "", err - } - - switch outputWriter.(type) { - case io.WriteCloser: - outputWriter.(io.WriteCloser).Close() - } - return encoding != "", encoding, nil -} - -// ParseEncoding will extract the right encoding for response -// the Accept-Encoding's sec is here: -// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 -func ParseEncoding(r *http.Request) string { - if r == nil { - return "" - } - if (getMethodOnly && r.Method == "GET") || includedMethods[r.Method] { - return parseEncoding(r) - } - return "" -} - -type q struct { - name string - value float64 -} - -func parseEncoding(r *http.Request) string { - acceptEncoding := r.Header.Get("Accept-Encoding") - if acceptEncoding == "" { - return "" - } - var lastQ q - for _, v := range strings.Split(acceptEncoding, ",") { - v = strings.TrimSpace(v) - if v == "" { - continue - } - vs := strings.Split(v, ";") - var cf acceptEncoder - var ok bool - if cf, ok = encoderMap[vs[0]]; !ok { - continue - } - if len(vs) == 1 { - return cf.name - } - if len(vs) == 2 { - f, _ := strconv.ParseFloat(strings.Replace(vs[1], "q=", "", -1), 64) - if f == 0 { - continue - } - if f > lastQ.value { - lastQ = q{cf.name, f} - } - } - } - return lastQ.name -} diff --git a/vendor/github.com/astaxie/beego/context/context.go b/vendor/github.com/astaxie/beego/context/context.go deleted file mode 100644 index 7c161ac0..00000000 --- a/vendor/github.com/astaxie/beego/context/context.go +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package context provide the context utils -// Usage: -// -// import "github.com/astaxie/beego/context" -// -// ctx := context.Context{Request:req,ResponseWriter:rw} -// -// more docs http://beego.me/docs/module/context.md -package context - -import ( - "bufio" - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "errors" - "fmt" - "net" - "net/http" - "strconv" - "strings" - "time" - - "github.com/astaxie/beego/utils" -) - -//commonly used mime-types -const ( - ApplicationJSON = "application/json" - ApplicationXML = "application/xml" - ApplicationYAML = "application/x-yaml" - TextXML = "text/xml" -) - -// NewContext return the Context with Input and Output -func NewContext() *Context { - return &Context{ - Input: NewInput(), - Output: NewOutput(), - } -} - -// Context Http request context struct including BeegoInput, BeegoOutput, http.Request and http.ResponseWriter. -// BeegoInput and BeegoOutput provides some api to operate request and response more easily. -type Context struct { - Input *BeegoInput - Output *BeegoOutput - Request *http.Request - ResponseWriter *Response - _xsrfToken string -} - -// Reset init Context, BeegoInput and BeegoOutput -func (ctx *Context) Reset(rw http.ResponseWriter, r *http.Request) { - ctx.Request = r - if ctx.ResponseWriter == nil { - ctx.ResponseWriter = &Response{} - } - ctx.ResponseWriter.reset(rw) - ctx.Input.Reset(ctx) - ctx.Output.Reset(ctx) - ctx._xsrfToken = "" -} - -// Redirect does redirection to localurl with http header status code. -func (ctx *Context) Redirect(status int, localurl string) { - http.Redirect(ctx.ResponseWriter, ctx.Request, localurl, status) -} - -// Abort stops this request. -// if beego.ErrorMaps exists, panic body. -func (ctx *Context) Abort(status int, body string) { - ctx.Output.SetStatus(status) - panic(body) -} - -// WriteString Write string to response body. -// it sends response body. -func (ctx *Context) WriteString(content string) { - ctx.ResponseWriter.Write([]byte(content)) -} - -// GetCookie Get cookie from request by a given key. -// It's alias of BeegoInput.Cookie. -func (ctx *Context) GetCookie(key string) string { - return ctx.Input.Cookie(key) -} - -// SetCookie Set cookie for response. -// It's alias of BeegoOutput.Cookie. -func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { - ctx.Output.Cookie(name, value, others...) -} - -// GetSecureCookie Get secure cookie from request by a given key. -func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) { - val := ctx.Input.Cookie(key) - if val == "" { - return "", false - } - - parts := strings.SplitN(val, "|", 3) - - if len(parts) != 3 { - return "", false - } - - vs := parts[0] - timestamp := parts[1] - sig := parts[2] - - h := hmac.New(sha256.New, []byte(Secret)) - fmt.Fprintf(h, "%s%s", vs, timestamp) - - if fmt.Sprintf("%02x", h.Sum(nil)) != sig { - return "", false - } - res, _ := base64.URLEncoding.DecodeString(vs) - return string(res), true -} - -// SetSecureCookie Set Secure cookie for response. -func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) { - vs := base64.URLEncoding.EncodeToString([]byte(value)) - timestamp := strconv.FormatInt(time.Now().UnixNano(), 10) - h := hmac.New(sha256.New, []byte(Secret)) - fmt.Fprintf(h, "%s%s", vs, timestamp) - sig := fmt.Sprintf("%02x", h.Sum(nil)) - cookie := strings.Join([]string{vs, timestamp, sig}, "|") - ctx.Output.Cookie(name, cookie, others...) -} - -// XSRFToken creates a xsrf token string and returns. -func (ctx *Context) XSRFToken(key string, expire int64) string { - if ctx._xsrfToken == "" { - token, ok := ctx.GetSecureCookie(key, "_xsrf") - if !ok { - token = string(utils.RandomCreateBytes(32)) - ctx.SetSecureCookie(key, "_xsrf", token, expire, "", "", true, true) - } - ctx._xsrfToken = token - } - return ctx._xsrfToken -} - -// CheckXSRFCookie checks xsrf token in this request is valid or not. -// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken" -// or in form field value named as "_xsrf". -func (ctx *Context) CheckXSRFCookie() bool { - token := ctx.Input.Query("_xsrf") - if token == "" { - token = ctx.Request.Header.Get("X-Xsrftoken") - } - if token == "" { - token = ctx.Request.Header.Get("X-Csrftoken") - } - if token == "" { - ctx.Abort(422, "422") - return false - } - if ctx._xsrfToken != token { - ctx.Abort(417, "417") - return false - } - return true -} - -// RenderMethodResult renders the return value of a controller method to the output -func (ctx *Context) RenderMethodResult(result interface{}) { - if result != nil { - renderer, ok := result.(Renderer) - if !ok { - err, ok := result.(error) - if ok { - renderer = errorRenderer(err) - } else { - renderer = jsonRenderer(result) - } - } - renderer.Render(ctx) - } -} - -//Response is a wrapper for the http.ResponseWriter -//started set to true if response was written to then don't execute other handler -type Response struct { - http.ResponseWriter - Started bool - Status int - Elapsed time.Duration -} - -func (r *Response) reset(rw http.ResponseWriter) { - r.ResponseWriter = rw - r.Status = 0 - r.Started = false -} - -// Write writes the data to the connection as part of an HTTP reply, -// and sets `started` to true. -// started means the response has sent out. -func (r *Response) Write(p []byte) (int, error) { - r.Started = true - return r.ResponseWriter.Write(p) -} - -// WriteHeader sends an HTTP response header with status code, -// and sets `started` to true. -func (r *Response) WriteHeader(code int) { - if r.Status > 0 { - //prevent multiple response.WriteHeader calls - return - } - r.Status = code - r.Started = true - r.ResponseWriter.WriteHeader(code) -} - -// Hijack hijacker for http -func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) { - hj, ok := r.ResponseWriter.(http.Hijacker) - if !ok { - return nil, nil, errors.New("webserver doesn't support hijacking") - } - return hj.Hijack() -} - -// Flush http.Flusher -func (r *Response) Flush() { - if f, ok := r.ResponseWriter.(http.Flusher); ok { - f.Flush() - } -} - -// CloseNotify http.CloseNotifier -func (r *Response) CloseNotify() <-chan bool { - if cn, ok := r.ResponseWriter.(http.CloseNotifier); ok { - return cn.CloseNotify() - } - return nil -} - -// Pusher http.Pusher -func (r *Response) Pusher() (pusher http.Pusher) { - if pusher, ok := r.ResponseWriter.(http.Pusher); ok { - return pusher - } - return nil -} diff --git a/vendor/github.com/astaxie/beego/context/input.go b/vendor/github.com/astaxie/beego/context/input.go deleted file mode 100644 index 385549c1..00000000 --- a/vendor/github.com/astaxie/beego/context/input.go +++ /dev/null @@ -1,689 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package context - -import ( - "bytes" - "compress/gzip" - "errors" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "reflect" - "regexp" - "strconv" - "strings" - "sync" - - "github.com/astaxie/beego/session" -) - -// Regexes for checking the accept headers -// TODO make sure these are correct -var ( - acceptsHTMLRegex = regexp.MustCompile(`(text/html|application/xhtml\+xml)(?:,|$)`) - acceptsXMLRegex = regexp.MustCompile(`(application/xml|text/xml)(?:,|$)`) - acceptsJSONRegex = regexp.MustCompile(`(application/json)(?:,|$)`) - acceptsYAMLRegex = regexp.MustCompile(`(application/x-yaml)(?:,|$)`) - maxParam = 50 -) - -// BeegoInput operates the http request header, data, cookie and body. -// it also contains router params and current session. -type BeegoInput struct { - Context *Context - CruSession session.Store - pnames []string - pvalues []string - data map[interface{}]interface{} // store some values in this context when calling context in filter or controller. - dataLock sync.RWMutex - RequestBody []byte - RunMethod string - RunController reflect.Type -} - -// NewInput return BeegoInput generated by Context. -func NewInput() *BeegoInput { - return &BeegoInput{ - pnames: make([]string, 0, maxParam), - pvalues: make([]string, 0, maxParam), - data: make(map[interface{}]interface{}), - } -} - -// Reset init the BeegoInput -func (input *BeegoInput) Reset(ctx *Context) { - input.Context = ctx - input.CruSession = nil - input.pnames = input.pnames[:0] - input.pvalues = input.pvalues[:0] - input.dataLock.Lock() - input.data = nil - input.dataLock.Unlock() - input.RequestBody = []byte{} -} - -// Protocol returns request protocol name, such as HTTP/1.1 . -func (input *BeegoInput) Protocol() string { - return input.Context.Request.Proto -} - -// URI returns full request url with query string, fragment. -func (input *BeegoInput) URI() string { - return input.Context.Request.RequestURI -} - -// URL returns request url path (without query string, fragment). -func (input *BeegoInput) URL() string { - return input.Context.Request.URL.EscapedPath() -} - -// Site returns base site url as scheme://domain type. -func (input *BeegoInput) Site() string { - return input.Scheme() + "://" + input.Domain() -} - -// Scheme returns request scheme as "http" or "https". -func (input *BeegoInput) Scheme() string { - if scheme := input.Header("X-Forwarded-Proto"); scheme != "" { - return scheme - } - if input.Context.Request.URL.Scheme != "" { - return input.Context.Request.URL.Scheme - } - if input.Context.Request.TLS == nil { - return "http" - } - return "https" -} - -// Domain returns host name. -// Alias of Host method. -func (input *BeegoInput) Domain() string { - return input.Host() -} - -// Host returns host name. -// if no host info in request, return localhost. -func (input *BeegoInput) Host() string { - if input.Context.Request.Host != "" { - if hostPart, _, err := net.SplitHostPort(input.Context.Request.Host); err == nil { - return hostPart - } - return input.Context.Request.Host - } - return "localhost" -} - -// Method returns http request method. -func (input *BeegoInput) Method() string { - return input.Context.Request.Method -} - -// Is returns boolean of this request is on given method, such as Is("POST"). -func (input *BeegoInput) Is(method string) bool { - return input.Method() == method -} - -// IsGet Is this a GET method request? -func (input *BeegoInput) IsGet() bool { - return input.Is("GET") -} - -// IsPost Is this a POST method request? -func (input *BeegoInput) IsPost() bool { - return input.Is("POST") -} - -// IsHead Is this a Head method request? -func (input *BeegoInput) IsHead() bool { - return input.Is("HEAD") -} - -// IsOptions Is this a OPTIONS method request? -func (input *BeegoInput) IsOptions() bool { - return input.Is("OPTIONS") -} - -// IsPut Is this a PUT method request? -func (input *BeegoInput) IsPut() bool { - return input.Is("PUT") -} - -// IsDelete Is this a DELETE method request? -func (input *BeegoInput) IsDelete() bool { - return input.Is("DELETE") -} - -// IsPatch Is this a PATCH method request? -func (input *BeegoInput) IsPatch() bool { - return input.Is("PATCH") -} - -// IsAjax returns boolean of this request is generated by ajax. -func (input *BeegoInput) IsAjax() bool { - return input.Header("X-Requested-With") == "XMLHttpRequest" -} - -// IsSecure returns boolean of this request is in https. -func (input *BeegoInput) IsSecure() bool { - return input.Scheme() == "https" -} - -// IsWebsocket returns boolean of this request is in webSocket. -func (input *BeegoInput) IsWebsocket() bool { - return input.Header("Upgrade") == "websocket" -} - -// IsUpload returns boolean of whether file uploads in this request or not.. -func (input *BeegoInput) IsUpload() bool { - return strings.Contains(input.Header("Content-Type"), "multipart/form-data") -} - -// AcceptsHTML Checks if request accepts html response -func (input *BeegoInput) AcceptsHTML() bool { - return acceptsHTMLRegex.MatchString(input.Header("Accept")) -} - -// AcceptsXML Checks if request accepts xml response -func (input *BeegoInput) AcceptsXML() bool { - return acceptsXMLRegex.MatchString(input.Header("Accept")) -} - -// AcceptsJSON Checks if request accepts json response -func (input *BeegoInput) AcceptsJSON() bool { - return acceptsJSONRegex.MatchString(input.Header("Accept")) -} - -// AcceptsYAML Checks if request accepts json response -func (input *BeegoInput) AcceptsYAML() bool { - return acceptsYAMLRegex.MatchString(input.Header("Accept")) -} - -// IP returns request client ip. -// if in proxy, return first proxy id. -// if error, return RemoteAddr. -func (input *BeegoInput) IP() string { - ips := input.Proxy() - if len(ips) > 0 && ips[0] != "" { - rip, _, err := net.SplitHostPort(ips[0]) - if err != nil { - rip = ips[0] - } - return rip - } - if ip, _, err := net.SplitHostPort(input.Context.Request.RemoteAddr); err == nil { - return ip - } - return input.Context.Request.RemoteAddr -} - -// Proxy returns proxy client ips slice. -func (input *BeegoInput) Proxy() []string { - if ips := input.Header("X-Forwarded-For"); ips != "" { - return strings.Split(ips, ",") - } - return []string{} -} - -// Referer returns http referer header. -func (input *BeegoInput) Referer() string { - return input.Header("Referer") -} - -// Refer returns http referer header. -func (input *BeegoInput) Refer() string { - return input.Referer() -} - -// SubDomains returns sub domain string. -// if aa.bb.domain.com, returns aa.bb . -func (input *BeegoInput) SubDomains() string { - parts := strings.Split(input.Host(), ".") - if len(parts) >= 3 { - return strings.Join(parts[:len(parts)-2], ".") - } - return "" -} - -// Port returns request client port. -// when error or empty, return 80. -func (input *BeegoInput) Port() int { - if _, portPart, err := net.SplitHostPort(input.Context.Request.Host); err == nil { - port, _ := strconv.Atoi(portPart) - return port - } - return 80 -} - -// UserAgent returns request client user agent string. -func (input *BeegoInput) UserAgent() string { - return input.Header("User-Agent") -} - -// ParamsLen return the length of the params -func (input *BeegoInput) ParamsLen() int { - return len(input.pnames) -} - -// Param returns router param by a given key. -func (input *BeegoInput) Param(key string) string { - for i, v := range input.pnames { - if v == key && i <= len(input.pvalues) { - // we cannot use url.PathEscape(input.pvalues[i]) - // for example, if the value is /a/b - // after url.PathEscape(input.pvalues[i]), the value is %2Fa%2Fb - // However, the value is used in ControllerRegister.ServeHTTP - // and split by "/", so function crash... - return input.pvalues[i] - } - } - return "" -} - -// Params returns the map[key]value. -func (input *BeegoInput) Params() map[string]string { - m := make(map[string]string) - for i, v := range input.pnames { - if i <= len(input.pvalues) { - m[v] = input.pvalues[i] - } - } - return m -} - -// SetParam will set the param with key and value -func (input *BeegoInput) SetParam(key, val string) { - // check if already exists - for i, v := range input.pnames { - if v == key && i <= len(input.pvalues) { - input.pvalues[i] = val - return - } - } - input.pvalues = append(input.pvalues, val) - input.pnames = append(input.pnames, key) -} - -// ResetParams clears any of the input's Params -// This function is used to clear parameters so they may be reset between filter -// passes. -func (input *BeegoInput) ResetParams() { - input.pnames = input.pnames[:0] - input.pvalues = input.pvalues[:0] -} - -// Query returns input data item string by a given string. -func (input *BeegoInput) Query(key string) string { - if val := input.Param(key); val != "" { - return val - } - if input.Context.Request.Form == nil { - input.dataLock.Lock() - if input.Context.Request.Form == nil { - input.Context.Request.ParseForm() - } - input.dataLock.Unlock() - } - input.dataLock.RLock() - defer input.dataLock.RUnlock() - return input.Context.Request.Form.Get(key) -} - -// Header returns request header item string by a given string. -// if non-existed, return empty string. -func (input *BeegoInput) Header(key string) string { - return input.Context.Request.Header.Get(key) -} - -// Cookie returns request cookie item string by a given key. -// if non-existed, return empty string. -func (input *BeegoInput) Cookie(key string) string { - ck, err := input.Context.Request.Cookie(key) - if err != nil { - return "" - } - return ck.Value -} - -// Session returns current session item value by a given key. -// if non-existed, return nil. -func (input *BeegoInput) Session(key interface{}) interface{} { - return input.CruSession.Get(key) -} - -// CopyBody returns the raw request body data as bytes. -func (input *BeegoInput) CopyBody(MaxMemory int64) []byte { - if input.Context.Request.Body == nil { - return []byte{} - } - - var requestbody []byte - safe := &io.LimitedReader{R: input.Context.Request.Body, N: MaxMemory} - if input.Header("Content-Encoding") == "gzip" { - reader, err := gzip.NewReader(safe) - if err != nil { - return nil - } - requestbody, _ = ioutil.ReadAll(reader) - } else { - requestbody, _ = ioutil.ReadAll(safe) - } - - input.Context.Request.Body.Close() - bf := bytes.NewBuffer(requestbody) - input.Context.Request.Body = http.MaxBytesReader(input.Context.ResponseWriter, ioutil.NopCloser(bf), MaxMemory) - input.RequestBody = requestbody - return requestbody -} - -// Data return the implicit data in the input -func (input *BeegoInput) Data() map[interface{}]interface{} { - input.dataLock.Lock() - defer input.dataLock.Unlock() - if input.data == nil { - input.data = make(map[interface{}]interface{}) - } - return input.data -} - -// GetData returns the stored data in this context. -func (input *BeegoInput) GetData(key interface{}) interface{} { - input.dataLock.Lock() - defer input.dataLock.Unlock() - if v, ok := input.data[key]; ok { - return v - } - return nil -} - -// SetData stores data with given key in this context. -// This data are only available in this context. -func (input *BeegoInput) SetData(key, val interface{}) { - input.dataLock.Lock() - defer input.dataLock.Unlock() - if input.data == nil { - input.data = make(map[interface{}]interface{}) - } - input.data[key] = val -} - -// ParseFormOrMulitForm parseForm or parseMultiForm based on Content-type -func (input *BeegoInput) ParseFormOrMulitForm(maxMemory int64) error { - // Parse the body depending on the content type. - if strings.Contains(input.Header("Content-Type"), "multipart/form-data") { - if err := input.Context.Request.ParseMultipartForm(maxMemory); err != nil { - return errors.New("Error parsing request body:" + err.Error()) - } - } else if err := input.Context.Request.ParseForm(); err != nil { - return errors.New("Error parsing request body:" + err.Error()) - } - return nil -} - -// Bind data from request.Form[key] to dest -// like /?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie -// var id int beegoInput.Bind(&id, "id") id ==123 -// var isok bool beegoInput.Bind(&isok, "isok") isok ==true -// var ft float64 beegoInput.Bind(&ft, "ft") ft ==1.2 -// ol := make([]int, 0, 2) beegoInput.Bind(&ol, "ol") ol ==[1 2] -// ul := make([]string, 0, 2) beegoInput.Bind(&ul, "ul") ul ==[str array] -// user struct{Name} beegoInput.Bind(&user, "user") user == {Name:"astaxie"} -func (input *BeegoInput) Bind(dest interface{}, key string) error { - value := reflect.ValueOf(dest) - if value.Kind() != reflect.Ptr { - return errors.New("beego: non-pointer passed to Bind: " + key) - } - value = value.Elem() - if !value.CanSet() { - return errors.New("beego: non-settable variable passed to Bind: " + key) - } - typ := value.Type() - // Get real type if dest define with interface{}. - // e.g var dest interface{} dest=1.0 - if value.Kind() == reflect.Interface { - typ = value.Elem().Type() - } - rv := input.bind(key, typ) - if !rv.IsValid() { - return errors.New("beego: reflect value is empty") - } - value.Set(rv) - return nil -} - -func (input *BeegoInput) bind(key string, typ reflect.Type) reflect.Value { - if input.Context.Request.Form == nil { - input.Context.Request.ParseForm() - } - rv := reflect.Zero(typ) - switch typ.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - val := input.Query(key) - if len(val) == 0 { - return rv - } - rv = input.bindInt(val, typ) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - val := input.Query(key) - if len(val) == 0 { - return rv - } - rv = input.bindUint(val, typ) - case reflect.Float32, reflect.Float64: - val := input.Query(key) - if len(val) == 0 { - return rv - } - rv = input.bindFloat(val, typ) - case reflect.String: - val := input.Query(key) - if len(val) == 0 { - return rv - } - rv = input.bindString(val, typ) - case reflect.Bool: - val := input.Query(key) - if len(val) == 0 { - return rv - } - rv = input.bindBool(val, typ) - case reflect.Slice: - rv = input.bindSlice(&input.Context.Request.Form, key, typ) - case reflect.Struct: - rv = input.bindStruct(&input.Context.Request.Form, key, typ) - case reflect.Ptr: - rv = input.bindPoint(key, typ) - case reflect.Map: - rv = input.bindMap(&input.Context.Request.Form, key, typ) - } - return rv -} - -func (input *BeegoInput) bindValue(val string, typ reflect.Type) reflect.Value { - rv := reflect.Zero(typ) - switch typ.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - rv = input.bindInt(val, typ) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - rv = input.bindUint(val, typ) - case reflect.Float32, reflect.Float64: - rv = input.bindFloat(val, typ) - case reflect.String: - rv = input.bindString(val, typ) - case reflect.Bool: - rv = input.bindBool(val, typ) - case reflect.Slice: - rv = input.bindSlice(&url.Values{"": {val}}, "", typ) - case reflect.Struct: - rv = input.bindStruct(&url.Values{"": {val}}, "", typ) - case reflect.Ptr: - rv = input.bindPoint(val, typ) - case reflect.Map: - rv = input.bindMap(&url.Values{"": {val}}, "", typ) - } - return rv -} - -func (input *BeegoInput) bindInt(val string, typ reflect.Type) reflect.Value { - intValue, err := strconv.ParseInt(val, 10, 64) - if err != nil { - return reflect.Zero(typ) - } - pValue := reflect.New(typ) - pValue.Elem().SetInt(intValue) - return pValue.Elem() -} - -func (input *BeegoInput) bindUint(val string, typ reflect.Type) reflect.Value { - uintValue, err := strconv.ParseUint(val, 10, 64) - if err != nil { - return reflect.Zero(typ) - } - pValue := reflect.New(typ) - pValue.Elem().SetUint(uintValue) - return pValue.Elem() -} - -func (input *BeegoInput) bindFloat(val string, typ reflect.Type) reflect.Value { - floatValue, err := strconv.ParseFloat(val, 64) - if err != nil { - return reflect.Zero(typ) - } - pValue := reflect.New(typ) - pValue.Elem().SetFloat(floatValue) - return pValue.Elem() -} - -func (input *BeegoInput) bindString(val string, typ reflect.Type) reflect.Value { - return reflect.ValueOf(val) -} - -func (input *BeegoInput) bindBool(val string, typ reflect.Type) reflect.Value { - val = strings.TrimSpace(strings.ToLower(val)) - switch val { - case "true", "on", "1": - return reflect.ValueOf(true) - } - return reflect.ValueOf(false) -} - -type sliceValue struct { - index int // Index extracted from brackets. If -1, no index was provided. - value reflect.Value // the bound value for this slice element. -} - -func (input *BeegoInput) bindSlice(params *url.Values, key string, typ reflect.Type) reflect.Value { - maxIndex := -1 - numNoIndex := 0 - sliceValues := []sliceValue{} - for reqKey, vals := range *params { - if !strings.HasPrefix(reqKey, key+"[") { - continue - } - // Extract the index, and the index where a sub-key starts. (e.g. field[0].subkey) - index := -1 - leftBracket, rightBracket := len(key), strings.Index(reqKey[len(key):], "]")+len(key) - if rightBracket > leftBracket+1 { - index, _ = strconv.Atoi(reqKey[leftBracket+1 : rightBracket]) - } - subKeyIndex := rightBracket + 1 - - // Handle the indexed case. - if index > -1 { - if index > maxIndex { - maxIndex = index - } - sliceValues = append(sliceValues, sliceValue{ - index: index, - value: input.bind(reqKey[:subKeyIndex], typ.Elem()), - }) - continue - } - - // It's an un-indexed element. (e.g. element[]) - numNoIndex += len(vals) - for _, val := range vals { - // Unindexed values can only be direct-bound. - sliceValues = append(sliceValues, sliceValue{ - index: -1, - value: input.bindValue(val, typ.Elem()), - }) - } - } - resultArray := reflect.MakeSlice(typ, maxIndex+1, maxIndex+1+numNoIndex) - for _, sv := range sliceValues { - if sv.index != -1 { - resultArray.Index(sv.index).Set(sv.value) - } else { - resultArray = reflect.Append(resultArray, sv.value) - } - } - return resultArray -} - -func (input *BeegoInput) bindStruct(params *url.Values, key string, typ reflect.Type) reflect.Value { - result := reflect.New(typ).Elem() - fieldValues := make(map[string]reflect.Value) - for reqKey, val := range *params { - var fieldName string - if strings.HasPrefix(reqKey, key+".") { - fieldName = reqKey[len(key)+1:] - } else if strings.HasPrefix(reqKey, key+"[") && reqKey[len(reqKey)-1] == ']' { - fieldName = reqKey[len(key)+1 : len(reqKey)-1] - } else { - continue - } - - if _, ok := fieldValues[fieldName]; !ok { - // Time to bind this field. Get it and make sure we can set it. - fieldValue := result.FieldByName(fieldName) - if !fieldValue.IsValid() { - continue - } - if !fieldValue.CanSet() { - continue - } - boundVal := input.bindValue(val[0], fieldValue.Type()) - fieldValue.Set(boundVal) - fieldValues[fieldName] = boundVal - } - } - - return result -} - -func (input *BeegoInput) bindPoint(key string, typ reflect.Type) reflect.Value { - return input.bind(key, typ.Elem()).Addr() -} - -func (input *BeegoInput) bindMap(params *url.Values, key string, typ reflect.Type) reflect.Value { - var ( - result = reflect.MakeMap(typ) - keyType = typ.Key() - valueType = typ.Elem() - ) - for paramName, values := range *params { - if !strings.HasPrefix(paramName, key+"[") || paramName[len(paramName)-1] != ']' { - continue - } - - key := paramName[len(key)+1 : len(paramName)-1] - result.SetMapIndex(input.bindValue(key, keyType), input.bindValue(values[0], valueType)) - } - return result -} diff --git a/vendor/github.com/astaxie/beego/context/output.go b/vendor/github.com/astaxie/beego/context/output.go deleted file mode 100644 index 238dcf45..00000000 --- a/vendor/github.com/astaxie/beego/context/output.go +++ /dev/null @@ -1,408 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package context - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "errors" - "fmt" - "html/template" - "io" - "mime" - "net/http" - "net/url" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - yaml "gopkg.in/yaml.v2" -) - -// BeegoOutput does work for sending response header. -type BeegoOutput struct { - Context *Context - Status int - EnableGzip bool -} - -// NewOutput returns new BeegoOutput. -// it contains nothing now. -func NewOutput() *BeegoOutput { - return &BeegoOutput{} -} - -// Reset init BeegoOutput -func (output *BeegoOutput) Reset(ctx *Context) { - output.Context = ctx - output.Status = 0 -} - -// Header sets response header item string via given key. -func (output *BeegoOutput) Header(key, val string) { - output.Context.ResponseWriter.Header().Set(key, val) -} - -// Body sets response body content. -// if EnableGzip, compress content string. -// it sends out response body directly. -func (output *BeegoOutput) Body(content []byte) error { - var encoding string - var buf = &bytes.Buffer{} - if output.EnableGzip { - encoding = ParseEncoding(output.Context.Request) - } - if b, n, _ := WriteBody(encoding, buf, content); b { - output.Header("Content-Encoding", n) - output.Header("Content-Length", strconv.Itoa(buf.Len())) - } else { - output.Header("Content-Length", strconv.Itoa(len(content))) - } - // Write status code if it has been set manually - // Set it to 0 afterwards to prevent "multiple response.WriteHeader calls" - if output.Status != 0 { - output.Context.ResponseWriter.WriteHeader(output.Status) - output.Status = 0 - } else { - output.Context.ResponseWriter.Started = true - } - io.Copy(output.Context.ResponseWriter, buf) - return nil -} - -// Cookie sets cookie value via given key. -// others are ordered as cookie's max age time, path,domain, secure and httponly. -func (output *BeegoOutput) Cookie(name string, value string, others ...interface{}) { - var b bytes.Buffer - fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value)) - - //fix cookie not work in IE - if len(others) > 0 { - var maxAge int64 - - switch v := others[0].(type) { - case int: - maxAge = int64(v) - case int32: - maxAge = int64(v) - case int64: - maxAge = v - } - - switch { - case maxAge > 0: - fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(maxAge)*time.Second).UTC().Format(time.RFC1123), maxAge) - case maxAge < 0: - fmt.Fprintf(&b, "; Max-Age=0") - } - } - - // the settings below - // Path, Domain, Secure, HttpOnly - // can use nil skip set - - // default "/" - if len(others) > 1 { - if v, ok := others[1].(string); ok && len(v) > 0 { - fmt.Fprintf(&b, "; Path=%s", sanitizeValue(v)) - } - } else { - fmt.Fprintf(&b, "; Path=%s", "/") - } - - // default empty - if len(others) > 2 { - if v, ok := others[2].(string); ok && len(v) > 0 { - fmt.Fprintf(&b, "; Domain=%s", sanitizeValue(v)) - } - } - - // default empty - if len(others) > 3 { - var secure bool - switch v := others[3].(type) { - case bool: - secure = v - default: - if others[3] != nil { - secure = true - } - } - if secure { - fmt.Fprintf(&b, "; Secure") - } - } - - // default false. for session cookie default true - if len(others) > 4 { - if v, ok := others[4].(bool); ok && v { - fmt.Fprintf(&b, "; HttpOnly") - } - } - - output.Context.ResponseWriter.Header().Add("Set-Cookie", b.String()) -} - -var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-") - -func sanitizeName(n string) string { - return cookieNameSanitizer.Replace(n) -} - -var cookieValueSanitizer = strings.NewReplacer("\n", " ", "\r", " ", ";", " ") - -func sanitizeValue(v string) string { - return cookieValueSanitizer.Replace(v) -} - -func jsonRenderer(value interface{}) Renderer { - return rendererFunc(func(ctx *Context) { - ctx.Output.JSON(value, false, false) - }) -} - -func errorRenderer(err error) Renderer { - return rendererFunc(func(ctx *Context) { - ctx.Output.SetStatus(500) - ctx.Output.Body([]byte(err.Error())) - }) -} - -// JSON writes json to response body. -// if encoding is true, it converts utf-8 to \u0000 type. -func (output *BeegoOutput) JSON(data interface{}, hasIndent bool, encoding bool) error { - output.Header("Content-Type", "application/json; charset=utf-8") - var content []byte - var err error - if hasIndent { - content, err = json.MarshalIndent(data, "", " ") - } else { - content, err = json.Marshal(data) - } - if err != nil { - http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError) - return err - } - if encoding { - content = []byte(stringsToJSON(string(content))) - } - return output.Body(content) -} - -// YAML writes yaml to response body. -func (output *BeegoOutput) YAML(data interface{}) error { - output.Header("Content-Type", "application/x-yaml; charset=utf-8") - var content []byte - var err error - content, err = yaml.Marshal(data) - if err != nil { - http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError) - return err - } - return output.Body(content) -} - -// JSONP writes jsonp to response body. -func (output *BeegoOutput) JSONP(data interface{}, hasIndent bool) error { - output.Header("Content-Type", "application/javascript; charset=utf-8") - var content []byte - var err error - if hasIndent { - content, err = json.MarshalIndent(data, "", " ") - } else { - content, err = json.Marshal(data) - } - if err != nil { - http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError) - return err - } - callback := output.Context.Input.Query("callback") - if callback == "" { - return errors.New(`"callback" parameter required`) - } - callback = template.JSEscapeString(callback) - callbackContent := bytes.NewBufferString(" if(window." + callback + ")" + callback) - callbackContent.WriteString("(") - callbackContent.Write(content) - callbackContent.WriteString(");\r\n") - return output.Body(callbackContent.Bytes()) -} - -// XML writes xml string to response body. -func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error { - output.Header("Content-Type", "application/xml; charset=utf-8") - var content []byte - var err error - if hasIndent { - content, err = xml.MarshalIndent(data, "", " ") - } else { - content, err = xml.Marshal(data) - } - if err != nil { - http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError) - return err - } - return output.Body(content) -} - -// ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header -func (output *BeegoOutput) ServeFormatted(data interface{}, hasIndent bool, hasEncode ...bool) { - accept := output.Context.Input.Header("Accept") - switch accept { - case ApplicationYAML: - output.YAML(data) - case ApplicationXML, TextXML: - output.XML(data, hasIndent) - default: - output.JSON(data, hasIndent, len(hasEncode) > 0 && hasEncode[0]) - } -} - -// Download forces response for download file. -// it prepares the download response header automatically. -func (output *BeegoOutput) Download(file string, filename ...string) { - // check get file error, file not found or other error. - if _, err := os.Stat(file); err != nil { - http.ServeFile(output.Context.ResponseWriter, output.Context.Request, file) - return - } - - var fName string - if len(filename) > 0 && filename[0] != "" { - fName = filename[0] - } else { - fName = filepath.Base(file) - } - //https://tools.ietf.org/html/rfc6266#section-4.3 - fn := url.PathEscape(fName) - if fName == fn { - fn = "filename=" + fn - } else { - /** - The parameters "filename" and "filename*" differ only in that - "filename*" uses the encoding defined in [RFC5987], allowing the use - of characters not present in the ISO-8859-1 character set - ([ISO-8859-1]). - */ - fn = "filename=" + fName + "; filename*=utf-8''" + fn - } - output.Header("Content-Disposition", "attachment; "+fn) - output.Header("Content-Description", "File Transfer") - output.Header("Content-Type", "application/octet-stream") - output.Header("Content-Transfer-Encoding", "binary") - output.Header("Expires", "0") - output.Header("Cache-Control", "must-revalidate") - output.Header("Pragma", "public") - http.ServeFile(output.Context.ResponseWriter, output.Context.Request, file) -} - -// ContentType sets the content type from ext string. -// MIME type is given in mime package. -func (output *BeegoOutput) ContentType(ext string) { - if !strings.HasPrefix(ext, ".") { - ext = "." + ext - } - ctype := mime.TypeByExtension(ext) - if ctype != "" { - output.Header("Content-Type", ctype) - } -} - -// SetStatus sets response status code. -// It writes response header directly. -func (output *BeegoOutput) SetStatus(status int) { - output.Status = status -} - -// IsCachable returns boolean of this request is cached. -// HTTP 304 means cached. -func (output *BeegoOutput) IsCachable() bool { - return output.Status >= 200 && output.Status < 300 || output.Status == 304 -} - -// IsEmpty returns boolean of this request is empty. -// HTTP 201,204 and 304 means empty. -func (output *BeegoOutput) IsEmpty() bool { - return output.Status == 201 || output.Status == 204 || output.Status == 304 -} - -// IsOk returns boolean of this request runs well. -// HTTP 200 means ok. -func (output *BeegoOutput) IsOk() bool { - return output.Status == 200 -} - -// IsSuccessful returns boolean of this request runs successfully. -// HTTP 2xx means ok. -func (output *BeegoOutput) IsSuccessful() bool { - return output.Status >= 200 && output.Status < 300 -} - -// IsRedirect returns boolean of this request is redirection header. -// HTTP 301,302,307 means redirection. -func (output *BeegoOutput) IsRedirect() bool { - return output.Status == 301 || output.Status == 302 || output.Status == 303 || output.Status == 307 -} - -// IsForbidden returns boolean of this request is forbidden. -// HTTP 403 means forbidden. -func (output *BeegoOutput) IsForbidden() bool { - return output.Status == 403 -} - -// IsNotFound returns boolean of this request is not found. -// HTTP 404 means not found. -func (output *BeegoOutput) IsNotFound() bool { - return output.Status == 404 -} - -// IsClientError returns boolean of this request client sends error data. -// HTTP 4xx means client error. -func (output *BeegoOutput) IsClientError() bool { - return output.Status >= 400 && output.Status < 500 -} - -// IsServerError returns boolean of this server handler errors. -// HTTP 5xx means server internal error. -func (output *BeegoOutput) IsServerError() bool { - return output.Status >= 500 && output.Status < 600 -} - -func stringsToJSON(str string) string { - var jsons bytes.Buffer - for _, r := range str { - rint := int(r) - if rint < 128 { - jsons.WriteRune(r) - } else { - jsons.WriteString("\\u") - if rint < 0x100 { - jsons.WriteString("00") - } else if rint < 0x1000 { - jsons.WriteString("0") - } - jsons.WriteString(strconv.FormatInt(int64(rint), 16)) - } - } - return jsons.String() -} - -// Session sets session item value with given key. -func (output *BeegoOutput) Session(name interface{}, value interface{}) { - output.Context.Input.CruSession.Set(name, value) -} diff --git a/vendor/github.com/astaxie/beego/context/param/conv.go b/vendor/github.com/astaxie/beego/context/param/conv.go deleted file mode 100644 index c200e008..00000000 --- a/vendor/github.com/astaxie/beego/context/param/conv.go +++ /dev/null @@ -1,78 +0,0 @@ -package param - -import ( - "fmt" - "reflect" - - beecontext "github.com/astaxie/beego/context" - "github.com/astaxie/beego/logs" -) - -// ConvertParams converts http method params to values that will be passed to the method controller as arguments -func ConvertParams(methodParams []*MethodParam, methodType reflect.Type, ctx *beecontext.Context) (result []reflect.Value) { - result = make([]reflect.Value, 0, len(methodParams)) - for i := 0; i < len(methodParams); i++ { - reflectValue := convertParam(methodParams[i], methodType.In(i), ctx) - result = append(result, reflectValue) - } - return -} - -func convertParam(param *MethodParam, paramType reflect.Type, ctx *beecontext.Context) (result reflect.Value) { - paramValue := getParamValue(param, ctx) - if paramValue == "" { - if param.required { - ctx.Abort(400, fmt.Sprintf("Missing parameter %s", param.name)) - } else { - paramValue = param.defaultValue - } - } - - reflectValue, err := parseValue(param, paramValue, paramType) - if err != nil { - logs.Debug(fmt.Sprintf("Error converting param %s to type %s. Value: %v, Error: %s", param.name, paramType, paramValue, err)) - ctx.Abort(400, fmt.Sprintf("Invalid parameter %s. Can not convert %v to type %s", param.name, paramValue, paramType)) - } - - return reflectValue -} - -func getParamValue(param *MethodParam, ctx *beecontext.Context) string { - switch param.in { - case body: - return string(ctx.Input.RequestBody) - case header: - return ctx.Input.Header(param.name) - case path: - return ctx.Input.Query(":" + param.name) - default: - return ctx.Input.Query(param.name) - } -} - -func parseValue(param *MethodParam, paramValue string, paramType reflect.Type) (result reflect.Value, err error) { - if paramValue == "" { - return reflect.Zero(paramType), nil - } - parser := getParser(param, paramType) - value, err := parser.parse(paramValue, paramType) - if err != nil { - return result, err - } - - return safeConvert(reflect.ValueOf(value), paramType) -} - -func safeConvert(value reflect.Value, t reflect.Type) (result reflect.Value, err error) { - defer func() { - if r := recover(); r != nil { - var ok bool - err, ok = r.(error) - if !ok { - err = fmt.Errorf("%v", r) - } - } - }() - result = value.Convert(t) - return -} diff --git a/vendor/github.com/astaxie/beego/context/param/methodparams.go b/vendor/github.com/astaxie/beego/context/param/methodparams.go deleted file mode 100644 index cd6708a2..00000000 --- a/vendor/github.com/astaxie/beego/context/param/methodparams.go +++ /dev/null @@ -1,69 +0,0 @@ -package param - -import ( - "fmt" - "strings" -) - -//MethodParam keeps param information to be auto passed to controller methods -type MethodParam struct { - name string - in paramType - required bool - defaultValue string -} - -type paramType byte - -const ( - param paramType = iota - path - body - header -) - -//New creates a new MethodParam with name and specific options -func New(name string, opts ...MethodParamOption) *MethodParam { - return newParam(name, nil, opts) -} - -func newParam(name string, parser paramParser, opts []MethodParamOption) (param *MethodParam) { - param = &MethodParam{name: name} - for _, option := range opts { - option(param) - } - return -} - -//Make creates an array of MethodParmas or an empty array -func Make(list ...*MethodParam) []*MethodParam { - if len(list) > 0 { - return list - } - return nil -} - -func (mp *MethodParam) String() string { - options := []string{} - result := "param.New(\"" + mp.name + "\"" - if mp.required { - options = append(options, "param.IsRequired") - } - switch mp.in { - case path: - options = append(options, "param.InPath") - case body: - options = append(options, "param.InBody") - case header: - options = append(options, "param.InHeader") - } - if mp.defaultValue != "" { - options = append(options, fmt.Sprintf(`param.Default("%s")`, mp.defaultValue)) - } - if len(options) > 0 { - result += ", " - } - result += strings.Join(options, ", ") - result += ")" - return result -} diff --git a/vendor/github.com/astaxie/beego/context/param/options.go b/vendor/github.com/astaxie/beego/context/param/options.go deleted file mode 100644 index 3d5ba013..00000000 --- a/vendor/github.com/astaxie/beego/context/param/options.go +++ /dev/null @@ -1,37 +0,0 @@ -package param - -import ( - "fmt" -) - -// MethodParamOption defines a func which apply options on a MethodParam -type MethodParamOption func(*MethodParam) - -// IsRequired indicates that this param is required and can not be omitted from the http request -var IsRequired MethodParamOption = func(p *MethodParam) { - p.required = true -} - -// InHeader indicates that this param is passed via an http header -var InHeader MethodParamOption = func(p *MethodParam) { - p.in = header -} - -// InPath indicates that this param is part of the URL path -var InPath MethodParamOption = func(p *MethodParam) { - p.in = path -} - -// InBody indicates that this param is passed as an http request body -var InBody MethodParamOption = func(p *MethodParam) { - p.in = body -} - -// Default provides a default value for the http param -func Default(defaultValue interface{}) MethodParamOption { - return func(p *MethodParam) { - if defaultValue != nil { - p.defaultValue = fmt.Sprint(defaultValue) - } - } -} diff --git a/vendor/github.com/astaxie/beego/context/param/parsers.go b/vendor/github.com/astaxie/beego/context/param/parsers.go deleted file mode 100644 index 421aecf0..00000000 --- a/vendor/github.com/astaxie/beego/context/param/parsers.go +++ /dev/null @@ -1,149 +0,0 @@ -package param - -import ( - "encoding/json" - "reflect" - "strconv" - "strings" - "time" -) - -type paramParser interface { - parse(value string, toType reflect.Type) (interface{}, error) -} - -func getParser(param *MethodParam, t reflect.Type) paramParser { - switch t.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return intParser{} - case reflect.Slice: - if t.Elem().Kind() == reflect.Uint8 { //treat []byte as string - return stringParser{} - } - if param.in == body { - return jsonParser{} - } - elemParser := getParser(param, t.Elem()) - if elemParser == (jsonParser{}) { - return elemParser - } - return sliceParser(elemParser) - case reflect.Bool: - return boolParser{} - case reflect.String: - return stringParser{} - case reflect.Float32, reflect.Float64: - return floatParser{} - case reflect.Ptr: - elemParser := getParser(param, t.Elem()) - if elemParser == (jsonParser{}) { - return elemParser - } - return ptrParser(elemParser) - default: - if t.PkgPath() == "time" && t.Name() == "Time" { - return timeParser{} - } - return jsonParser{} - } -} - -type parserFunc func(value string, toType reflect.Type) (interface{}, error) - -func (f parserFunc) parse(value string, toType reflect.Type) (interface{}, error) { - return f(value, toType) -} - -type boolParser struct { -} - -func (p boolParser) parse(value string, toType reflect.Type) (interface{}, error) { - return strconv.ParseBool(value) -} - -type stringParser struct { -} - -func (p stringParser) parse(value string, toType reflect.Type) (interface{}, error) { - return value, nil -} - -type intParser struct { -} - -func (p intParser) parse(value string, toType reflect.Type) (interface{}, error) { - return strconv.Atoi(value) -} - -type floatParser struct { -} - -func (p floatParser) parse(value string, toType reflect.Type) (interface{}, error) { - if toType.Kind() == reflect.Float32 { - res, err := strconv.ParseFloat(value, 32) - if err != nil { - return nil, err - } - return float32(res), nil - } - return strconv.ParseFloat(value, 64) -} - -type timeParser struct { -} - -func (p timeParser) parse(value string, toType reflect.Type) (result interface{}, err error) { - result, err = time.Parse(time.RFC3339, value) - if err != nil { - result, err = time.Parse("2006-01-02", value) - } - return -} - -type jsonParser struct { -} - -func (p jsonParser) parse(value string, toType reflect.Type) (interface{}, error) { - pResult := reflect.New(toType) - v := pResult.Interface() - err := json.Unmarshal([]byte(value), v) - if err != nil { - return nil, err - } - return pResult.Elem().Interface(), nil -} - -func sliceParser(elemParser paramParser) paramParser { - return parserFunc(func(value string, toType reflect.Type) (interface{}, error) { - values := strings.Split(value, ",") - result := reflect.MakeSlice(toType, 0, len(values)) - elemType := toType.Elem() - for _, v := range values { - parsedValue, err := elemParser.parse(v, elemType) - if err != nil { - return nil, err - } - result = reflect.Append(result, reflect.ValueOf(parsedValue)) - } - return result.Interface(), nil - }) -} - -func ptrParser(elemParser paramParser) paramParser { - return parserFunc(func(value string, toType reflect.Type) (interface{}, error) { - parsedValue, err := elemParser.parse(value, toType.Elem()) - if err != nil { - return nil, err - } - newValPtr := reflect.New(toType.Elem()) - newVal := reflect.Indirect(newValPtr) - convertedVal, err := safeConvert(reflect.ValueOf(parsedValue), toType.Elem()) - if err != nil { - return nil, err - } - - newVal.Set(convertedVal) - return newValPtr.Interface(), nil - }) -} diff --git a/vendor/github.com/astaxie/beego/context/renderer.go b/vendor/github.com/astaxie/beego/context/renderer.go deleted file mode 100644 index 36a7cb53..00000000 --- a/vendor/github.com/astaxie/beego/context/renderer.go +++ /dev/null @@ -1,12 +0,0 @@ -package context - -// Renderer defines an http response renderer -type Renderer interface { - Render(ctx *Context) -} - -type rendererFunc func(ctx *Context) - -func (f rendererFunc) Render(ctx *Context) { - f(ctx) -} diff --git a/vendor/github.com/astaxie/beego/context/response.go b/vendor/github.com/astaxie/beego/context/response.go deleted file mode 100644 index 9c3c715a..00000000 --- a/vendor/github.com/astaxie/beego/context/response.go +++ /dev/null @@ -1,27 +0,0 @@ -package context - -import ( - "strconv" - - "net/http" -) - -const ( - //BadRequest indicates http error 400 - BadRequest StatusCode = http.StatusBadRequest - - //NotFound indicates http error 404 - NotFound StatusCode = http.StatusNotFound -) - -// StatusCode sets the http response status code -type StatusCode int - -func (s StatusCode) Error() string { - return strconv.Itoa(int(s)) -} - -// Render sets the http status code -func (s StatusCode) Render(ctx *Context) { - ctx.Output.SetStatus(int(s)) -} diff --git a/vendor/github.com/astaxie/beego/controller.go b/vendor/github.com/astaxie/beego/controller.go deleted file mode 100644 index 0e8853b3..00000000 --- a/vendor/github.com/astaxie/beego/controller.go +++ /dev/null @@ -1,706 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "bytes" - "errors" - "fmt" - "html/template" - "io" - "mime/multipart" - "net/http" - "net/url" - "os" - "reflect" - "strconv" - "strings" - - "github.com/astaxie/beego/context" - "github.com/astaxie/beego/context/param" - "github.com/astaxie/beego/session" -) - -var ( - // ErrAbort custom error when user stop request handler manually. - ErrAbort = errors.New("user stop run") - // GlobalControllerRouter store comments with controller. pkgpath+controller:comments - GlobalControllerRouter = make(map[string][]ControllerComments) -) - -// ControllerFilter store the filter for controller -type ControllerFilter struct { - Pattern string - Pos int - Filter FilterFunc - ReturnOnOutput bool - ResetParams bool -} - -// ControllerFilterComments store the comment for controller level filter -type ControllerFilterComments struct { - Pattern string - Pos int - Filter string // NOQA - ReturnOnOutput bool - ResetParams bool -} - -// ControllerImportComments store the import comment for controller needed -type ControllerImportComments struct { - ImportPath string - ImportAlias string -} - -// ControllerComments store the comment for the controller method -type ControllerComments struct { - Method string - Router string - Filters []*ControllerFilter - ImportComments []*ControllerImportComments - FilterComments []*ControllerFilterComments - AllowHTTPMethods []string - Params []map[string]string - MethodParams []*param.MethodParam -} - -// ControllerCommentsSlice implements the sort interface -type ControllerCommentsSlice []ControllerComments - -func (p ControllerCommentsSlice) Len() int { return len(p) } -func (p ControllerCommentsSlice) Less(i, j int) bool { return p[i].Router < p[j].Router } -func (p ControllerCommentsSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// Controller defines some basic http request handler operations, such as -// http context, template and view, session and xsrf. -type Controller struct { - // context data - Ctx *context.Context - Data map[interface{}]interface{} - - // route controller info - controllerName string - actionName string - methodMapping map[string]func() //method:routertree - AppController interface{} - - // template data - TplName string - ViewPath string - Layout string - LayoutSections map[string]string // the key is the section name and the value is the template name - TplPrefix string - TplExt string - EnableRender bool - - // xsrf data - _xsrfToken string - XSRFExpire int - EnableXSRF bool - - // session - CruSession session.Store -} - -// ControllerInterface is an interface to uniform all controller handler. -type ControllerInterface interface { - Init(ct *context.Context, controllerName, actionName string, app interface{}) - Prepare() - Get() - Post() - Delete() - Put() - Head() - Patch() - Options() - Trace() - Finish() - Render() error - XSRFToken() string - CheckXSRFCookie() bool - HandlerFunc(fn string) bool - URLMapping() -} - -// Init generates default values of controller operations. -func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) { - c.Layout = "" - c.TplName = "" - c.controllerName = controllerName - c.actionName = actionName - c.Ctx = ctx - c.TplExt = "tpl" - c.AppController = app - c.EnableRender = true - c.EnableXSRF = true - c.Data = ctx.Input.Data() - c.methodMapping = make(map[string]func()) -} - -// Prepare runs after Init before request function execution. -func (c *Controller) Prepare() {} - -// Finish runs after request function execution. -func (c *Controller) Finish() {} - -// Get adds a request function to handle GET request. -func (c *Controller) Get() { - http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed) -} - -// Post adds a request function to handle POST request. -func (c *Controller) Post() { - http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed) -} - -// Delete adds a request function to handle DELETE request. -func (c *Controller) Delete() { - http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed) -} - -// Put adds a request function to handle PUT request. -func (c *Controller) Put() { - http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed) -} - -// Head adds a request function to handle HEAD request. -func (c *Controller) Head() { - http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed) -} - -// Patch adds a request function to handle PATCH request. -func (c *Controller) Patch() { - http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed) -} - -// Options adds a request function to handle OPTIONS request. -func (c *Controller) Options() { - http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed) -} - -// Trace adds a request function to handle Trace request. -// this method SHOULD NOT be overridden. -// https://tools.ietf.org/html/rfc7231#section-4.3.8 -// The TRACE method requests a remote, application-level loop-back of -// the request message. The final recipient of the request SHOULD -// reflect the message received, excluding some fields described below, -// back to the client as the message body of a 200 (OK) response with a -// Content-Type of "message/http" (Section 8.3.1 of [RFC7230]). -func (c *Controller) Trace() { - ts := func(h http.Header) (hs string) { - for k, v := range h { - hs += fmt.Sprintf("\r\n%s: %s", k, v) - } - return - } - hs := fmt.Sprintf("\r\nTRACE %s %s%s\r\n", c.Ctx.Request.RequestURI, c.Ctx.Request.Proto, ts(c.Ctx.Request.Header)) - c.Ctx.Output.Header("Content-Type", "message/http") - c.Ctx.Output.Header("Content-Length", fmt.Sprint(len(hs))) - c.Ctx.Output.Header("Cache-Control", "no-cache, no-store, must-revalidate") - c.Ctx.WriteString(hs) -} - -// HandlerFunc call function with the name -func (c *Controller) HandlerFunc(fnname string) bool { - if v, ok := c.methodMapping[fnname]; ok { - v() - return true - } - return false -} - -// URLMapping register the internal Controller router. -func (c *Controller) URLMapping() {} - -// Mapping the method to function -func (c *Controller) Mapping(method string, fn func()) { - c.methodMapping[method] = fn -} - -// Render sends the response with rendered template bytes as text/html type. -func (c *Controller) Render() error { - if !c.EnableRender { - return nil - } - rb, err := c.RenderBytes() - if err != nil { - return err - } - - if c.Ctx.ResponseWriter.Header().Get("Content-Type") == "" { - c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8") - } - - return c.Ctx.Output.Body(rb) -} - -// RenderString returns the rendered template string. Do not send out response. -func (c *Controller) RenderString() (string, error) { - b, e := c.RenderBytes() - return string(b), e -} - -// RenderBytes returns the bytes of rendered template string. Do not send out response. -func (c *Controller) RenderBytes() ([]byte, error) { - buf, err := c.renderTemplate() - //if the controller has set layout, then first get the tplName's content set the content to the layout - if err == nil && c.Layout != "" { - c.Data["LayoutContent"] = template.HTML(buf.String()) - - if c.LayoutSections != nil { - for sectionName, sectionTpl := range c.LayoutSections { - if sectionTpl == "" { - c.Data[sectionName] = "" - continue - } - buf.Reset() - err = ExecuteViewPathTemplate(&buf, sectionTpl, c.viewPath(), c.Data) - if err != nil { - return nil, err - } - c.Data[sectionName] = template.HTML(buf.String()) - } - } - - buf.Reset() - ExecuteViewPathTemplate(&buf, c.Layout, c.viewPath(), c.Data) - } - return buf.Bytes(), err -} - -func (c *Controller) renderTemplate() (bytes.Buffer, error) { - var buf bytes.Buffer - if c.TplName == "" { - c.TplName = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt - } - if c.TplPrefix != "" { - c.TplName = c.TplPrefix + c.TplName - } - if BConfig.RunMode == DEV { - buildFiles := []string{c.TplName} - if c.Layout != "" { - buildFiles = append(buildFiles, c.Layout) - if c.LayoutSections != nil { - for _, sectionTpl := range c.LayoutSections { - if sectionTpl == "" { - continue - } - buildFiles = append(buildFiles, sectionTpl) - } - } - } - BuildTemplate(c.viewPath(), buildFiles...) - } - return buf, ExecuteViewPathTemplate(&buf, c.TplName, c.viewPath(), c.Data) -} - -func (c *Controller) viewPath() string { - if c.ViewPath == "" { - return BConfig.WebConfig.ViewsPath - } - return c.ViewPath -} - -// Redirect sends the redirection response to url with status code. -func (c *Controller) Redirect(url string, code int) { - LogAccess(c.Ctx, nil, code) - c.Ctx.Redirect(code, url) -} - -// SetData set the data depending on the accepted -func (c *Controller) SetData(data interface{}) { - accept := c.Ctx.Input.Header("Accept") - switch accept { - case context.ApplicationYAML: - c.Data["yaml"] = data - case context.ApplicationXML, context.TextXML: - c.Data["xml"] = data - default: - c.Data["json"] = data - } -} - -// Abort stops controller handler and show the error data if code is defined in ErrorMap or code string. -func (c *Controller) Abort(code string) { - status, err := strconv.Atoi(code) - if err != nil { - status = 200 - } - c.CustomAbort(status, code) -} - -// CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body. -func (c *Controller) CustomAbort(status int, body string) { - // first panic from ErrorMaps, it is user defined error functions. - if _, ok := ErrorMaps[body]; ok { - c.Ctx.Output.Status = status - panic(body) - } - // last panic user string - c.Ctx.ResponseWriter.WriteHeader(status) - c.Ctx.ResponseWriter.Write([]byte(body)) - panic(ErrAbort) -} - -// StopRun makes panic of USERSTOPRUN error and go to recover function if defined. -func (c *Controller) StopRun() { - panic(ErrAbort) -} - -// URLFor does another controller handler in this request function. -// it goes to this controller method if endpoint is not clear. -func (c *Controller) URLFor(endpoint string, values ...interface{}) string { - if len(endpoint) == 0 { - return "" - } - if endpoint[0] == '.' { - return URLFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...) - } - return URLFor(endpoint, values...) -} - -// ServeJSON sends a json response with encoding charset. -func (c *Controller) ServeJSON(encoding ...bool) { - var ( - hasIndent = BConfig.RunMode != PROD - hasEncoding = len(encoding) > 0 && encoding[0] - ) - - c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding) -} - -// ServeJSONP sends a jsonp response. -func (c *Controller) ServeJSONP() { - hasIndent := BConfig.RunMode != PROD - c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent) -} - -// ServeXML sends xml response. -func (c *Controller) ServeXML() { - hasIndent := BConfig.RunMode != PROD - c.Ctx.Output.XML(c.Data["xml"], hasIndent) -} - -// ServeYAML sends yaml response. -func (c *Controller) ServeYAML() { - c.Ctx.Output.YAML(c.Data["yaml"]) -} - -// ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header -func (c *Controller) ServeFormatted(encoding ...bool) { - hasIndent := BConfig.RunMode != PROD - hasEncoding := len(encoding) > 0 && encoding[0] - c.Ctx.Output.ServeFormatted(c.Data, hasIndent, hasEncoding) -} - -// Input returns the input data map from POST or PUT request body and query string. -func (c *Controller) Input() url.Values { - if c.Ctx.Request.Form == nil { - c.Ctx.Request.ParseForm() - } - return c.Ctx.Request.Form -} - -// ParseForm maps input data map to obj struct. -func (c *Controller) ParseForm(obj interface{}) error { - return ParseForm(c.Input(), obj) -} - -// GetString returns the input value by key string or the default value while it's present and input is blank -func (c *Controller) GetString(key string, def ...string) string { - if v := c.Ctx.Input.Query(key); v != "" { - return v - } - if len(def) > 0 { - return def[0] - } - return "" -} - -// GetStrings returns the input string slice by key string or the default value while it's present and input is blank -// it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection. -func (c *Controller) GetStrings(key string, def ...[]string) []string { - var defv []string - if len(def) > 0 { - defv = def[0] - } - - if f := c.Input(); f == nil { - return defv - } else if vs := f[key]; len(vs) > 0 { - return vs - } - - return defv -} - -// GetInt returns input as an int or the default value while it's present and input is blank -func (c *Controller) GetInt(key string, def ...int) (int, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - return strconv.Atoi(strv) -} - -// GetInt8 return input as an int8 or the default value while it's present and input is blank -func (c *Controller) GetInt8(key string, def ...int8) (int8, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - i64, err := strconv.ParseInt(strv, 10, 8) - return int8(i64), err -} - -// GetUint8 return input as an uint8 or the default value while it's present and input is blank -func (c *Controller) GetUint8(key string, def ...uint8) (uint8, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - u64, err := strconv.ParseUint(strv, 10, 8) - return uint8(u64), err -} - -// GetInt16 returns input as an int16 or the default value while it's present and input is blank -func (c *Controller) GetInt16(key string, def ...int16) (int16, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - i64, err := strconv.ParseInt(strv, 10, 16) - return int16(i64), err -} - -// GetUint16 returns input as an uint16 or the default value while it's present and input is blank -func (c *Controller) GetUint16(key string, def ...uint16) (uint16, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - u64, err := strconv.ParseUint(strv, 10, 16) - return uint16(u64), err -} - -// GetInt32 returns input as an int32 or the default value while it's present and input is blank -func (c *Controller) GetInt32(key string, def ...int32) (int32, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - i64, err := strconv.ParseInt(strv, 10, 32) - return int32(i64), err -} - -// GetUint32 returns input as an uint32 or the default value while it's present and input is blank -func (c *Controller) GetUint32(key string, def ...uint32) (uint32, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - u64, err := strconv.ParseUint(strv, 10, 32) - return uint32(u64), err -} - -// GetInt64 returns input value as int64 or the default value while it's present and input is blank. -func (c *Controller) GetInt64(key string, def ...int64) (int64, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - return strconv.ParseInt(strv, 10, 64) -} - -// GetUint64 returns input value as uint64 or the default value while it's present and input is blank. -func (c *Controller) GetUint64(key string, def ...uint64) (uint64, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - return strconv.ParseUint(strv, 10, 64) -} - -// GetBool returns input value as bool or the default value while it's present and input is blank. -func (c *Controller) GetBool(key string, def ...bool) (bool, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - return strconv.ParseBool(strv) -} - -// GetFloat returns input value as float64 or the default value while it's present and input is blank. -func (c *Controller) GetFloat(key string, def ...float64) (float64, error) { - strv := c.Ctx.Input.Query(key) - if len(strv) == 0 && len(def) > 0 { - return def[0], nil - } - return strconv.ParseFloat(strv, 64) -} - -// GetFile returns the file data in file upload field named as key. -// it returns the first one of multi-uploaded files. -func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) { - return c.Ctx.Request.FormFile(key) -} - -// GetFiles return multi-upload files -// files, err:=c.GetFiles("myfiles") -// if err != nil { -// http.Error(w, err.Error(), http.StatusNoContent) -// return -// } -// for i, _ := range files { -// //for each fileheader, get a handle to the actual file -// file, err := files[i].Open() -// defer file.Close() -// if err != nil { -// http.Error(w, err.Error(), http.StatusInternalServerError) -// return -// } -// //create destination file making sure the path is writeable. -// dst, err := os.Create("upload/" + files[i].Filename) -// defer dst.Close() -// if err != nil { -// http.Error(w, err.Error(), http.StatusInternalServerError) -// return -// } -// //copy the uploaded file to the destination file -// if _, err := io.Copy(dst, file); err != nil { -// http.Error(w, err.Error(), http.StatusInternalServerError) -// return -// } -// } -func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error) { - if files, ok := c.Ctx.Request.MultipartForm.File[key]; ok { - return files, nil - } - return nil, http.ErrMissingFile -} - -// SaveToFile saves uploaded file to new path. -// it only operates the first one of mutil-upload form file field. -func (c *Controller) SaveToFile(fromfile, tofile string) error { - file, _, err := c.Ctx.Request.FormFile(fromfile) - if err != nil { - return err - } - defer file.Close() - f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) - if err != nil { - return err - } - defer f.Close() - io.Copy(f, file) - return nil -} - -// StartSession starts session and load old session data info this controller. -func (c *Controller) StartSession() session.Store { - if c.CruSession == nil { - c.CruSession = c.Ctx.Input.CruSession - } - return c.CruSession -} - -// SetSession puts value into session. -func (c *Controller) SetSession(name interface{}, value interface{}) { - if c.CruSession == nil { - c.StartSession() - } - c.CruSession.Set(name, value) -} - -// GetSession gets value from session. -func (c *Controller) GetSession(name interface{}) interface{} { - if c.CruSession == nil { - c.StartSession() - } - return c.CruSession.Get(name) -} - -// DelSession removes value from session. -func (c *Controller) DelSession(name interface{}) { - if c.CruSession == nil { - c.StartSession() - } - c.CruSession.Delete(name) -} - -// SessionRegenerateID regenerates session id for this session. -// the session data have no changes. -func (c *Controller) SessionRegenerateID() { - if c.CruSession != nil { - c.CruSession.SessionRelease(c.Ctx.ResponseWriter) - } - c.CruSession = GlobalSessions.SessionRegenerateID(c.Ctx.ResponseWriter, c.Ctx.Request) - c.Ctx.Input.CruSession = c.CruSession -} - -// DestroySession cleans session data and session cookie. -func (c *Controller) DestroySession() { - c.Ctx.Input.CruSession.Flush() - c.Ctx.Input.CruSession = nil - GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request) -} - -// IsAjax returns this request is ajax or not. -func (c *Controller) IsAjax() bool { - return c.Ctx.Input.IsAjax() -} - -// GetSecureCookie returns decoded cookie value from encoded browser cookie values. -func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) { - return c.Ctx.GetSecureCookie(Secret, key) -} - -// SetSecureCookie puts value into cookie after encoded the value. -func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) { - c.Ctx.SetSecureCookie(Secret, name, value, others...) -} - -// XSRFToken creates a CSRF token string and returns. -func (c *Controller) XSRFToken() string { - if c._xsrfToken == "" { - expire := int64(BConfig.WebConfig.XSRFExpire) - if c.XSRFExpire > 0 { - expire = int64(c.XSRFExpire) - } - c._xsrfToken = c.Ctx.XSRFToken(BConfig.WebConfig.XSRFKey, expire) - } - return c._xsrfToken -} - -// CheckXSRFCookie checks xsrf token in this request is valid or not. -// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken" -// or in form field value named as "_xsrf". -func (c *Controller) CheckXSRFCookie() bool { - if !c.EnableXSRF { - return true - } - return c.Ctx.CheckXSRFCookie() -} - -// XSRFFormHTML writes an input field contains xsrf token value. -func (c *Controller) XSRFFormHTML() string { - return `` -} - -// GetControllerAndAction gets the executing controller name and action name. -func (c *Controller) GetControllerAndAction() (string, string) { - return c.controllerName, c.actionName -} diff --git a/vendor/github.com/astaxie/beego/doc.go b/vendor/github.com/astaxie/beego/doc.go deleted file mode 100644 index 8825bd29..00000000 --- a/vendor/github.com/astaxie/beego/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -/* -Package beego provide a MVC framework -beego: an open-source, high-performance, modular, full-stack web framework - -It is used for rapid development of RESTful APIs, web apps and backend services in Go. -beego is inspired by Tornado, Sinatra and Flask with the added benefit of some Go-specific features such as interfaces and struct embedding. - - package main - import "github.com/astaxie/beego" - - func main() { - beego.Run() - } - -more information: http://beego.me -*/ -package beego diff --git a/vendor/github.com/astaxie/beego/error.go b/vendor/github.com/astaxie/beego/error.go deleted file mode 100644 index f268f723..00000000 --- a/vendor/github.com/astaxie/beego/error.go +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "fmt" - "html/template" - "net/http" - "reflect" - "runtime" - "strconv" - "strings" - - "github.com/astaxie/beego/context" - "github.com/astaxie/beego/utils" -) - -const ( - errorTypeHandler = iota - errorTypeController -) - -var tpl = ` - - - - - beego application error - - - - - -
- - - - - - - - - - -
Request Method: {{.RequestMethod}}
Request URL: {{.RequestURL}}
RemoteAddr: {{.RemoteAddr }}
-
- Stack -
{{.Stack}}
-
-
- - - -` - -// render default application error page with error and stack string. -func showErr(err interface{}, ctx *context.Context, stack string) { - t, _ := template.New("beegoerrortemp").Parse(tpl) - data := map[string]string{ - "AppError": fmt.Sprintf("%s:%v", BConfig.AppName, err), - "RequestMethod": ctx.Input.Method(), - "RequestURL": ctx.Input.URI(), - "RemoteAddr": ctx.Input.IP(), - "Stack": stack, - "BeegoVersion": VERSION, - "GoVersion": runtime.Version(), - } - t.Execute(ctx.ResponseWriter, data) -} - -var errtpl = ` - - - - - {{.Title}} - - - -
-
- -
- {{.Content}} - Go Home
- -
Powered by beego {{.BeegoVersion}} -
-
-
- - -` - -type errorInfo struct { - controllerType reflect.Type - handler http.HandlerFunc - method string - errorType int -} - -// ErrorMaps holds map of http handlers for each error string. -// there is 10 kinds default error(40x and 50x) -var ErrorMaps = make(map[string]*errorInfo, 10) - -// show 401 unauthorized error. -func unauthorized(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 401, - "
The page you have requested can't be authorized."+ - "
Perhaps you are here because:"+ - "

    "+ - "
    The credentials you supplied are incorrect"+ - "
    There are errors in the website address"+ - "
", - ) -} - -// show 402 Payment Required -func paymentRequired(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 402, - "
The page you have requested Payment Required."+ - "
Perhaps you are here because:"+ - "

    "+ - "
    The credentials you supplied are incorrect"+ - "
    There are errors in the website address"+ - "
", - ) -} - -// show 403 forbidden error. -func forbidden(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 403, - "
The page you have requested is forbidden."+ - "
Perhaps you are here because:"+ - "

    "+ - "
    Your address may be blocked"+ - "
    The site may be disabled"+ - "
    You need to log in"+ - "
", - ) -} - -// show 422 missing xsrf token -func missingxsrf(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 422, - "
The page you have requested is forbidden."+ - "
Perhaps you are here because:"+ - "

    "+ - "
    '_xsrf' argument missing from POST"+ - "
", - ) -} - -// show 417 invalid xsrf token -func invalidxsrf(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 417, - "
The page you have requested is forbidden."+ - "
Perhaps you are here because:"+ - "

    "+ - "
    expected XSRF not found"+ - "
", - ) -} - -// show 404 not found error. -func notFound(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 404, - "
The page you have requested has flown the coop."+ - "
Perhaps you are here because:"+ - "

    "+ - "
    The page has moved"+ - "
    The page no longer exists"+ - "
    You were looking for your puppy and got lost"+ - "
    You like 404 pages"+ - "
", - ) -} - -// show 405 Method Not Allowed -func methodNotAllowed(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 405, - "
The method you have requested Not Allowed."+ - "
Perhaps you are here because:"+ - "

    "+ - "
    The method specified in the Request-Line is not allowed for the resource identified by the Request-URI"+ - "
    The response MUST include an Allow header containing a list of valid methods for the requested resource."+ - "
", - ) -} - -// show 500 internal server error. -func internalServerError(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 500, - "
The page you have requested is down right now."+ - "

    "+ - "
    Please try again later and report the error to the website administrator"+ - "
", - ) -} - -// show 501 Not Implemented. -func notImplemented(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 501, - "
The page you have requested is Not Implemented."+ - "

    "+ - "
    Please try again later and report the error to the website administrator"+ - "
", - ) -} - -// show 502 Bad Gateway. -func badGateway(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 502, - "
The page you have requested is down right now."+ - "

    "+ - "
    The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request."+ - "
    Please try again later and report the error to the website administrator"+ - "
", - ) -} - -// show 503 service unavailable error. -func serviceUnavailable(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 503, - "
The page you have requested is unavailable."+ - "
Perhaps you are here because:"+ - "

    "+ - "

    The page is overloaded"+ - "
    Please try again later."+ - "
", - ) -} - -// show 504 Gateway Timeout. -func gatewayTimeout(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 504, - "
The page you have requested is unavailable"+ - "
Perhaps you are here because:"+ - "

    "+ - "

    The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI."+ - "
    Please try again later."+ - "
", - ) -} - -// show 413 Payload Too Large -func payloadTooLarge(rw http.ResponseWriter, r *http.Request) { - responseError(rw, r, - 413, - `
The page you have requested is unavailable. -
Perhaps you are here because:

-
    -
    The request entity is larger than limits defined by server. -
    Please change the request entity and try again. -
- `, - ) -} - -func responseError(rw http.ResponseWriter, r *http.Request, errCode int, errContent string) { - t, _ := template.New("beegoerrortemp").Parse(errtpl) - data := M{ - "Title": http.StatusText(errCode), - "BeegoVersion": VERSION, - "Content": template.HTML(errContent), - } - t.Execute(rw, data) -} - -// ErrorHandler registers http.HandlerFunc to each http err code string. -// usage: -// beego.ErrorHandler("404",NotFound) -// beego.ErrorHandler("500",InternalServerError) -func ErrorHandler(code string, h http.HandlerFunc) *App { - ErrorMaps[code] = &errorInfo{ - errorType: errorTypeHandler, - handler: h, - method: code, - } - return BeeApp -} - -// ErrorController registers ControllerInterface to each http err code string. -// usage: -// beego.ErrorController(&controllers.ErrorController{}) -func ErrorController(c ControllerInterface) *App { - reflectVal := reflect.ValueOf(c) - rt := reflectVal.Type() - ct := reflect.Indirect(reflectVal).Type() - for i := 0; i < rt.NumMethod(); i++ { - methodName := rt.Method(i).Name - if !utils.InSlice(methodName, exceptMethod) && strings.HasPrefix(methodName, "Error") { - errName := strings.TrimPrefix(methodName, "Error") - ErrorMaps[errName] = &errorInfo{ - errorType: errorTypeController, - controllerType: ct, - method: methodName, - } - } - } - return BeeApp -} - -// Exception Write HttpStatus with errCode and Exec error handler if exist. -func Exception(errCode uint64, ctx *context.Context) { - exception(strconv.FormatUint(errCode, 10), ctx) -} - -// show error string as simple text message. -// if error string is empty, show 503 or 500 error as default. -func exception(errCode string, ctx *context.Context) { - atoi := func(code string) int { - v, err := strconv.Atoi(code) - if err == nil { - return v - } - if ctx.Output.Status == 0 { - return 503 - } - return ctx.Output.Status - } - - for _, ec := range []string{errCode, "503", "500"} { - if h, ok := ErrorMaps[ec]; ok { - executeError(h, ctx, atoi(ec)) - return - } - } - //if 50x error has been removed from errorMap - ctx.ResponseWriter.WriteHeader(atoi(errCode)) - ctx.WriteString(errCode) -} - -func executeError(err *errorInfo, ctx *context.Context, code int) { - //make sure to log the error in the access log - LogAccess(ctx, nil, code) - - if err.errorType == errorTypeHandler { - ctx.ResponseWriter.WriteHeader(code) - err.handler(ctx.ResponseWriter, ctx.Request) - return - } - if err.errorType == errorTypeController { - ctx.Output.SetStatus(code) - //Invoke the request handler - vc := reflect.New(err.controllerType) - execController, ok := vc.Interface().(ControllerInterface) - if !ok { - panic("controller is not ControllerInterface") - } - //call the controller init function - execController.Init(ctx, err.controllerType.Name(), err.method, vc.Interface()) - - //call prepare function - execController.Prepare() - - execController.URLMapping() - - method := vc.MethodByName(err.method) - method.Call([]reflect.Value{}) - - //render template - if BConfig.WebConfig.AutoRender { - if err := execController.Render(); err != nil { - panic(err) - } - } - - // finish all runrouter. release resource - execController.Finish() - } -} diff --git a/vendor/github.com/astaxie/beego/filter.go b/vendor/github.com/astaxie/beego/filter.go deleted file mode 100644 index 9cc6e913..00000000 --- a/vendor/github.com/astaxie/beego/filter.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import "github.com/astaxie/beego/context" - -// FilterFunc defines a filter function which is invoked before the controller handler is executed. -type FilterFunc func(*context.Context) - -// FilterRouter defines a filter operation which is invoked before the controller handler is executed. -// It can match the URL against a pattern, and execute a filter function -// when a request with a matching URL arrives. -type FilterRouter struct { - filterFunc FilterFunc - tree *Tree - pattern string - returnOnOutput bool - resetParams bool -} - -// ValidRouter checks if the current request is matched by this filter. -// If the request is matched, the values of the URL parameters defined -// by the filter pattern are also returned. -func (f *FilterRouter) ValidRouter(url string, ctx *context.Context) bool { - isOk := f.tree.Match(url, ctx) - if isOk != nil { - if b, ok := isOk.(bool); ok { - return b - } - } - return false -} diff --git a/vendor/github.com/astaxie/beego/flash.go b/vendor/github.com/astaxie/beego/flash.go deleted file mode 100644 index a6485a17..00000000 --- a/vendor/github.com/astaxie/beego/flash.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "fmt" - "net/url" - "strings" -) - -// FlashData is a tools to maintain data when using across request. -type FlashData struct { - Data map[string]string -} - -// NewFlash return a new empty FlashData struct. -func NewFlash() *FlashData { - return &FlashData{ - Data: make(map[string]string), - } -} - -// Set message to flash -func (fd *FlashData) Set(key string, msg string, args ...interface{}) { - if len(args) == 0 { - fd.Data[key] = msg - } else { - fd.Data[key] = fmt.Sprintf(msg, args...) - } -} - -// Success writes success message to flash. -func (fd *FlashData) Success(msg string, args ...interface{}) { - if len(args) == 0 { - fd.Data["success"] = msg - } else { - fd.Data["success"] = fmt.Sprintf(msg, args...) - } -} - -// Notice writes notice message to flash. -func (fd *FlashData) Notice(msg string, args ...interface{}) { - if len(args) == 0 { - fd.Data["notice"] = msg - } else { - fd.Data["notice"] = fmt.Sprintf(msg, args...) - } -} - -// Warning writes warning message to flash. -func (fd *FlashData) Warning(msg string, args ...interface{}) { - if len(args) == 0 { - fd.Data["warning"] = msg - } else { - fd.Data["warning"] = fmt.Sprintf(msg, args...) - } -} - -// Error writes error message to flash. -func (fd *FlashData) Error(msg string, args ...interface{}) { - if len(args) == 0 { - fd.Data["error"] = msg - } else { - fd.Data["error"] = fmt.Sprintf(msg, args...) - } -} - -// Store does the saving operation of flash data. -// the data are encoded and saved in cookie. -func (fd *FlashData) Store(c *Controller) { - c.Data["flash"] = fd.Data - var flashValue string - for key, value := range fd.Data { - flashValue += "\x00" + key + "\x23" + BConfig.WebConfig.FlashSeparator + "\x23" + value + "\x00" - } - c.Ctx.SetCookie(BConfig.WebConfig.FlashName, url.QueryEscape(flashValue), 0, "/") -} - -// ReadFromRequest parsed flash data from encoded values in cookie. -func ReadFromRequest(c *Controller) *FlashData { - flash := NewFlash() - if cookie, err := c.Ctx.Request.Cookie(BConfig.WebConfig.FlashName); err == nil { - v, _ := url.QueryUnescape(cookie.Value) - vals := strings.Split(v, "\x00") - for _, v := range vals { - if len(v) > 0 { - kv := strings.Split(v, "\x23"+BConfig.WebConfig.FlashSeparator+"\x23") - if len(kv) == 2 { - flash.Data[kv[0]] = kv[1] - } - } - } - //read one time then delete it - c.Ctx.SetCookie(BConfig.WebConfig.FlashName, "", -1, "/") - } - c.Data["flash"] = flash.Data - return flash -} diff --git a/vendor/github.com/astaxie/beego/fs.go b/vendor/github.com/astaxie/beego/fs.go deleted file mode 100644 index 41cc6f6e..00000000 --- a/vendor/github.com/astaxie/beego/fs.go +++ /dev/null @@ -1,74 +0,0 @@ -package beego - -import ( - "net/http" - "os" - "path/filepath" -) - -type FileSystem struct { -} - -func (d FileSystem) Open(name string) (http.File, error) { - return os.Open(name) -} - -// Walk walks the file tree rooted at root in filesystem, calling walkFn for each file or -// directory in the tree, including root. All errors that arise visiting files -// and directories are filtered by walkFn. -func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error { - - f, err := fs.Open(root) - if err != nil { - return err - } - info, err := f.Stat() - if err != nil { - err = walkFn(root, nil, err) - } else { - err = walk(fs, root, info, walkFn) - } - if err == filepath.SkipDir { - return nil - } - return err -} - -// walk recursively descends path, calling walkFn. -func walk(fs http.FileSystem, path string, info os.FileInfo, walkFn filepath.WalkFunc) error { - var err error - if !info.IsDir() { - return walkFn(path, info, nil) - } - - dir, err := fs.Open(path) - if err != nil { - if err1 := walkFn(path, info, err); err1 != nil { - return err1 - } - return err - } - defer dir.Close() - dirs, err := dir.Readdir(-1) - err1 := walkFn(path, info, err) - // If err != nil, walk can't walk into this directory. - // err1 != nil means walkFn want walk to skip this directory or stop walking. - // Therefore, if one of err and err1 isn't nil, walk will return. - if err != nil || err1 != nil { - // The caller's behavior is controlled by the return value, which is decided - // by walkFn. walkFn may ignore err and return nil. - // If walkFn returns SkipDir, it will be handled by the caller. - // So walk should return whatever walkFn returns. - return err1 - } - - for _, fileInfo := range dirs { - filename := filepath.Join(path, fileInfo.Name()) - if err = walk(fs, filename, fileInfo, walkFn); err != nil { - if !fileInfo.IsDir() || err != filepath.SkipDir { - return err - } - } - } - return nil -} diff --git a/vendor/github.com/astaxie/beego/go.mod b/vendor/github.com/astaxie/beego/go.mod deleted file mode 100644 index 6d4da958..00000000 --- a/vendor/github.com/astaxie/beego/go.mod +++ /dev/null @@ -1,41 +0,0 @@ -module github.com/astaxie/beego - -require ( - github.com/Knetic/govaluate v3.0.0+incompatible // indirect - github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd - github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542 - github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737 - github.com/casbin/casbin v1.7.0 - github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 - github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d - github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808 // indirect - github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a // indirect - github.com/elastic/go-elasticsearch/v6 v6.8.5 - github.com/elazarl/go-bindata-assetfs v1.0.0 - github.com/go-redis/redis v6.14.2+incompatible - github.com/go-sql-driver/mysql v1.5.0 - github.com/gogo/protobuf v1.1.1 - github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect - github.com/gomodule/redigo v2.0.0+incompatible - github.com/hashicorp/golang-lru v0.5.4 - github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6 - github.com/lib/pq v1.0.0 - github.com/mattn/go-sqlite3 v2.0.3+incompatible - github.com/pelletier/go-toml v1.2.0 // indirect - github.com/pkg/errors v0.9.1 - github.com/prometheus/client_golang v1.7.0 - github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 - github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec - github.com/stretchr/testify v1.4.0 - github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c // indirect - github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b // indirect - golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 - golang.org/x/net v0.0.0-20190620200207-3b0461eec859 // indirect - gopkg.in/yaml.v2 v2.2.8 -) - -replace golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85 => github.com/golang/crypto v0.0.0-20181127143415-eb0de9b17e85 - -replace gopkg.in/yaml.v2 v2.2.1 => github.com/go-yaml/yaml v0.0.0-20180328195020-5420a8b6744d - -go 1.13 diff --git a/vendor/github.com/astaxie/beego/go.sum b/vendor/github.com/astaxie/beego/go.sum deleted file mode 100644 index 55c926cf..00000000 --- a/vendor/github.com/astaxie/beego/go.sum +++ /dev/null @@ -1,210 +0,0 @@ -github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/Knetic/govaluate v3.0.0+incompatible h1:7o6+MAPhYTCF0+fdvoz1xDedhRb4f6s9Tn1Tt7/WTEg= -github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= -github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= -github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd h1:jZtX5jh5IOMu0fpOTC3ayh6QGSPJ/KWOv1lgPvbRw1M= -github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= -github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542 h1:nYXb+3jF6Oq/j8R/y90XrKpreCxIalBWfeyeKymgOPk= -github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737 h1:rRISKWyXfVxvoa702s91Zl5oREZTrR3yv+tXrrX7G/g= -github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= -github.com/casbin/casbin v1.7.0 h1:PuzlE8w0JBg/DhIqnkF1Dewf3z+qmUZMVN07PonvVUQ= -github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= -github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 h1:F1EaeKL/ta07PY/k9Os/UFtwERei2/XzGemhpGnBKNg= -github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= -github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d h1:OMrhQqj1QCyDT2sxHCDjE+k8aMdn2ngTCGG7g4wrdLo= -github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= -github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808 h1:8s2l8TVUwMXl6tZMe3+hPCRJ25nQXiA3d1x622JtOqc= -github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= -github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a h1:Y5XsLCEhtEI8qbD9RP3Qlv5FXdTDHxZM9UPUnMRgBp8= -github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= -github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76 h1:Lgdd/Qp96Qj8jqLpq2cI1I1X7BJnu06efS+XkhRoLUQ= -github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712 h1:aaQcKT9WumO6JEJcRyTqFVq4XUZiUcKR2/GI31TOcz8= -github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= -github.com/elastic/go-elasticsearch/v6 v6.8.5 h1:U2HtkBseC1FNBmDr0TR2tKltL6FxoY+niDAlj5M8TK8= -github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= -github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= -github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-redis/redis v6.14.2+incompatible h1:UE9pLhzmWf+xHNmZsoccjXosPicuiNaInPgym8nzfg0= -github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= -github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= -github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-yaml/yaml v0.0.0-20180328195020-5420a8b6744d/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -github.com/gogo/protobuf v1.1.1 h1:72R+M5VuhED/KujmZVcIquuo8mBgX4oVda//DQb3PXo= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w= -github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0= -github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= -github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6 h1:wxyqOzKxsRJ6vVRL9sXQ64Z45wmBuQ+OTH9sLsC5rKc= -github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= -github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A= -github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= -github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= -github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= -github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= -github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= -github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= -github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= -github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= -github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= -github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= -github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0 h1:QIF48X1cihydXibm+4wfAc0r/qyPyuFiPFRNphdMpEE= -github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= -github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= -github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d h1:NVwnfyR3rENtlz62bcrkXME3INVUa4lcdGt+opvxExs= -github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec h1:q6XVwXmKvCRHRqesF3cSv6lNqqHi0QWOvgDlSohg8UA= -github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= -github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c h1:3eGShk3EQf5gJCYW+WzA0TEJQd37HLOmlYF7N0YJwv0= -github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= -github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= -github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b h1:0Ve0/CCjiAiyKddUMUn3RwIGlq2iTW4GuVzyoKBYO/8= -github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= -github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM/fAoGlaiiHYiFYdm80= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/astaxie/beego/grace/grace.go b/vendor/github.com/astaxie/beego/grace/grace.go deleted file mode 100644 index fb0cb7bb..00000000 --- a/vendor/github.com/astaxie/beego/grace/grace.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package grace use to hot reload -// Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/ -// -// Usage: -// -// import( -// "log" -// "net/http" -// "os" -// -// "github.com/astaxie/beego/grace" -// ) -// -// func handler(w http.ResponseWriter, r *http.Request) { -// w.Write([]byte("WORLD!")) -// } -// -// func main() { -// mux := http.NewServeMux() -// mux.HandleFunc("/hello", handler) -// -// err := grace.ListenAndServe("localhost:8080", mux) -// if err != nil { -// log.Println(err) -// } -// log.Println("Server on 8080 stopped") -// os.Exit(0) -// } -package grace - -import ( - "flag" - "net/http" - "os" - "strings" - "sync" - "syscall" - "time" -) - -const ( - // PreSignal is the position to add filter before signal - PreSignal = iota - // PostSignal is the position to add filter after signal - PostSignal - // StateInit represent the application inited - StateInit - // StateRunning represent the application is running - StateRunning - // StateShuttingDown represent the application is shutting down - StateShuttingDown - // StateTerminate represent the application is killed - StateTerminate -) - -var ( - regLock *sync.Mutex - runningServers map[string]*Server - runningServersOrder []string - socketPtrOffsetMap map[string]uint - runningServersForked bool - - // DefaultReadTimeOut is the HTTP read timeout - DefaultReadTimeOut time.Duration - // DefaultWriteTimeOut is the HTTP Write timeout - DefaultWriteTimeOut time.Duration - // DefaultMaxHeaderBytes is the Max HTTP Header size, default is 0, no limit - DefaultMaxHeaderBytes int - // DefaultTimeout is the shutdown server's timeout. default is 60s - DefaultTimeout = 60 * time.Second - - isChild bool - socketOrder string - - hookableSignals []os.Signal -) - -func init() { - flag.BoolVar(&isChild, "graceful", false, "listen on open fd (after forking)") - flag.StringVar(&socketOrder, "socketorder", "", "previous initialization order - used when more than one listener was started") - - regLock = &sync.Mutex{} - runningServers = make(map[string]*Server) - runningServersOrder = []string{} - socketPtrOffsetMap = make(map[string]uint) - - hookableSignals = []os.Signal{ - syscall.SIGHUP, - syscall.SIGINT, - syscall.SIGTERM, - } -} - -// NewServer returns a new graceServer. -func NewServer(addr string, handler http.Handler) (srv *Server) { - regLock.Lock() - defer regLock.Unlock() - - if !flag.Parsed() { - flag.Parse() - } - if len(socketOrder) > 0 { - for i, addr := range strings.Split(socketOrder, ",") { - socketPtrOffsetMap[addr] = uint(i) - } - } else { - socketPtrOffsetMap[addr] = uint(len(runningServersOrder)) - } - - srv = &Server{ - sigChan: make(chan os.Signal), - isChild: isChild, - SignalHooks: map[int]map[os.Signal][]func(){ - PreSignal: { - syscall.SIGHUP: {}, - syscall.SIGINT: {}, - syscall.SIGTERM: {}, - }, - PostSignal: { - syscall.SIGHUP: {}, - syscall.SIGINT: {}, - syscall.SIGTERM: {}, - }, - }, - state: StateInit, - Network: "tcp", - terminalChan: make(chan error), //no cache channel - } - srv.Server = &http.Server{ - Addr: addr, - ReadTimeout: DefaultReadTimeOut, - WriteTimeout: DefaultWriteTimeOut, - MaxHeaderBytes: DefaultMaxHeaderBytes, - Handler: handler, - } - - runningServersOrder = append(runningServersOrder, addr) - runningServers[addr] = srv - return srv -} - -// ListenAndServe refer http.ListenAndServe -func ListenAndServe(addr string, handler http.Handler) error { - server := NewServer(addr, handler) - return server.ListenAndServe() -} - -// ListenAndServeTLS refer http.ListenAndServeTLS -func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error { - server := NewServer(addr, handler) - return server.ListenAndServeTLS(certFile, keyFile) -} diff --git a/vendor/github.com/astaxie/beego/grace/server.go b/vendor/github.com/astaxie/beego/grace/server.go deleted file mode 100644 index 008a6171..00000000 --- a/vendor/github.com/astaxie/beego/grace/server.go +++ /dev/null @@ -1,356 +0,0 @@ -package grace - -import ( - "context" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "log" - "net" - "net/http" - "os" - "os/exec" - "os/signal" - "strings" - "syscall" - "time" -) - -// Server embedded http.Server -type Server struct { - *http.Server - ln net.Listener - SignalHooks map[int]map[os.Signal][]func() - sigChan chan os.Signal - isChild bool - state uint8 - Network string - terminalChan chan error -} - -// Serve accepts incoming connections on the Listener l, -// creating a new service goroutine for each. -// The service goroutines read requests and then call srv.Handler to reply to them. -func (srv *Server) Serve() (err error) { - srv.state = StateRunning - defer func() { srv.state = StateTerminate }() - - // When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS - // immediately return ErrServerClosed. Make sure the program doesn't exit - // and waits instead for Shutdown to return. - if err = srv.Server.Serve(srv.ln); err != nil && err != http.ErrServerClosed { - log.Println(syscall.Getpid(), "Server.Serve() error:", err) - return err - } - - log.Println(syscall.Getpid(), srv.ln.Addr(), "Listener closed.") - // wait for Shutdown to return - if shutdownErr := <-srv.terminalChan; shutdownErr != nil { - return shutdownErr - } - return -} - -// ListenAndServe listens on the TCP network address srv.Addr and then calls Serve -// to handle requests on incoming connections. If srv.Addr is blank, ":http" is -// used. -func (srv *Server) ListenAndServe() (err error) { - addr := srv.Addr - if addr == "" { - addr = ":http" - } - - go srv.handleSignals() - - srv.ln, err = srv.getListener(addr) - if err != nil { - log.Println(err) - return err - } - - if srv.isChild { - process, err := os.FindProcess(os.Getppid()) - if err != nil { - log.Println(err) - return err - } - err = process.Signal(syscall.SIGTERM) - if err != nil { - return err - } - } - - log.Println(os.Getpid(), srv.Addr) - return srv.Serve() -} - -// ListenAndServeTLS listens on the TCP network address srv.Addr and then calls -// Serve to handle requests on incoming TLS connections. -// -// Filenames containing a certificate and matching private key for the server must -// be provided. If the certificate is signed by a certificate authority, the -// certFile should be the concatenation of the server's certificate followed by the -// CA's certificate. -// -// If srv.Addr is blank, ":https" is used. -func (srv *Server) ListenAndServeTLS(certFile, keyFile string) (err error) { - addr := srv.Addr - if addr == "" { - addr = ":https" - } - - if srv.TLSConfig == nil { - srv.TLSConfig = &tls.Config{} - } - if srv.TLSConfig.NextProtos == nil { - srv.TLSConfig.NextProtos = []string{"http/1.1"} - } - - srv.TLSConfig.Certificates = make([]tls.Certificate, 1) - srv.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return - } - - go srv.handleSignals() - - ln, err := srv.getListener(addr) - if err != nil { - log.Println(err) - return err - } - srv.ln = tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig) - - if srv.isChild { - process, err := os.FindProcess(os.Getppid()) - if err != nil { - log.Println(err) - return err - } - err = process.Signal(syscall.SIGTERM) - if err != nil { - return err - } - } - - log.Println(os.Getpid(), srv.Addr) - return srv.Serve() -} - -// ListenAndServeMutualTLS listens on the TCP network address srv.Addr and then calls -// Serve to handle requests on incoming mutual TLS connections. -func (srv *Server) ListenAndServeMutualTLS(certFile, keyFile, trustFile string) (err error) { - addr := srv.Addr - if addr == "" { - addr = ":https" - } - - if srv.TLSConfig == nil { - srv.TLSConfig = &tls.Config{} - } - if srv.TLSConfig.NextProtos == nil { - srv.TLSConfig.NextProtos = []string{"http/1.1"} - } - - srv.TLSConfig.Certificates = make([]tls.Certificate, 1) - srv.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return - } - srv.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert - pool := x509.NewCertPool() - data, err := ioutil.ReadFile(trustFile) - if err != nil { - log.Println(err) - return err - } - pool.AppendCertsFromPEM(data) - srv.TLSConfig.ClientCAs = pool - log.Println("Mutual HTTPS") - go srv.handleSignals() - - ln, err := srv.getListener(addr) - if err != nil { - log.Println(err) - return err - } - srv.ln = tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig) - - if srv.isChild { - process, err := os.FindProcess(os.Getppid()) - if err != nil { - log.Println(err) - return err - } - err = process.Signal(syscall.SIGTERM) - if err != nil { - return err - } - } - - log.Println(os.Getpid(), srv.Addr) - return srv.Serve() -} - -// getListener either opens a new socket to listen on, or takes the acceptor socket -// it got passed when restarted. -func (srv *Server) getListener(laddr string) (l net.Listener, err error) { - if srv.isChild { - var ptrOffset uint - if len(socketPtrOffsetMap) > 0 { - ptrOffset = socketPtrOffsetMap[laddr] - log.Println("laddr", laddr, "ptr offset", socketPtrOffsetMap[laddr]) - } - - f := os.NewFile(uintptr(3+ptrOffset), "") - l, err = net.FileListener(f) - if err != nil { - err = fmt.Errorf("net.FileListener error: %v", err) - return - } - } else { - l, err = net.Listen(srv.Network, laddr) - if err != nil { - err = fmt.Errorf("net.Listen error: %v", err) - return - } - } - return -} - -type tcpKeepAliveListener struct { - *net.TCPListener -} - -func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { - tc, err := ln.AcceptTCP() - if err != nil { - return - } - tc.SetKeepAlive(true) - tc.SetKeepAlivePeriod(3 * time.Minute) - return tc, nil -} - -// handleSignals listens for os Signals and calls any hooked in function that the -// user had registered with the signal. -func (srv *Server) handleSignals() { - var sig os.Signal - - signal.Notify( - srv.sigChan, - hookableSignals..., - ) - - pid := syscall.Getpid() - for { - sig = <-srv.sigChan - srv.signalHooks(PreSignal, sig) - switch sig { - case syscall.SIGHUP: - log.Println(pid, "Received SIGHUP. forking.") - err := srv.fork() - if err != nil { - log.Println("Fork err:", err) - } - case syscall.SIGINT: - log.Println(pid, "Received SIGINT.") - srv.shutdown() - case syscall.SIGTERM: - log.Println(pid, "Received SIGTERM.") - srv.shutdown() - default: - log.Printf("Received %v: nothing i care about...\n", sig) - } - srv.signalHooks(PostSignal, sig) - } -} - -func (srv *Server) signalHooks(ppFlag int, sig os.Signal) { - if _, notSet := srv.SignalHooks[ppFlag][sig]; !notSet { - return - } - for _, f := range srv.SignalHooks[ppFlag][sig] { - f() - } -} - -// shutdown closes the listener so that no new connections are accepted. it also -// starts a goroutine that will serverTimeout (stop all running requests) the server -// after DefaultTimeout. -func (srv *Server) shutdown() { - if srv.state != StateRunning { - return - } - - srv.state = StateShuttingDown - log.Println(syscall.Getpid(), "Waiting for connections to finish...") - ctx := context.Background() - if DefaultTimeout >= 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(context.Background(), DefaultTimeout) - defer cancel() - } - srv.terminalChan <- srv.Server.Shutdown(ctx) -} - -func (srv *Server) fork() (err error) { - regLock.Lock() - defer regLock.Unlock() - if runningServersForked { - return - } - runningServersForked = true - - var files = make([]*os.File, len(runningServers)) - var orderArgs = make([]string, len(runningServers)) - for _, srvPtr := range runningServers { - f, _ := srvPtr.ln.(*net.TCPListener).File() - files[socketPtrOffsetMap[srvPtr.Server.Addr]] = f - orderArgs[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.Server.Addr - } - - log.Println(files) - path := os.Args[0] - var args []string - if len(os.Args) > 1 { - for _, arg := range os.Args[1:] { - if arg == "-graceful" { - break - } - args = append(args, arg) - } - } - args = append(args, "-graceful") - if len(runningServers) > 1 { - args = append(args, fmt.Sprintf(`-socketorder=%s`, strings.Join(orderArgs, ","))) - log.Println(args) - } - cmd := exec.Command(path, args...) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - cmd.ExtraFiles = files - err = cmd.Start() - if err != nil { - log.Fatalf("Restart: Failed to launch, error: %v", err) - } - - return -} - -// RegisterSignalHook registers a function to be run PreSignal or PostSignal for a given signal. -func (srv *Server) RegisterSignalHook(ppFlag int, sig os.Signal, f func()) (err error) { - if ppFlag != PreSignal && ppFlag != PostSignal { - err = fmt.Errorf("Invalid ppFlag argument. Must be either grace.PreSignal or grace.PostSignal") - return - } - for _, s := range hookableSignals { - if s == sig { - srv.SignalHooks[ppFlag][sig] = append(srv.SignalHooks[ppFlag][sig], f) - return - } - } - err = fmt.Errorf("Signal '%v' is not supported", sig) - return -} diff --git a/vendor/github.com/astaxie/beego/hooks.go b/vendor/github.com/astaxie/beego/hooks.go deleted file mode 100644 index 0a51e0da..00000000 --- a/vendor/github.com/astaxie/beego/hooks.go +++ /dev/null @@ -1,105 +0,0 @@ -package beego - -import ( - "encoding/json" - "mime" - "net/http" - "path/filepath" - - "github.com/astaxie/beego/context" - "github.com/astaxie/beego/logs" - "github.com/astaxie/beego/session" -) - -// register MIME type with content type -func registerMime() error { - for k, v := range mimemaps { - mime.AddExtensionType(k, v) - } - return nil -} - -// register default error http handlers, 404,401,403,500 and 503. -func registerDefaultErrorHandler() error { - m := map[string]func(http.ResponseWriter, *http.Request){ - "401": unauthorized, - "402": paymentRequired, - "403": forbidden, - "404": notFound, - "405": methodNotAllowed, - "500": internalServerError, - "501": notImplemented, - "502": badGateway, - "503": serviceUnavailable, - "504": gatewayTimeout, - "417": invalidxsrf, - "422": missingxsrf, - "413": payloadTooLarge, - } - for e, h := range m { - if _, ok := ErrorMaps[e]; !ok { - ErrorHandler(e, h) - } - } - return nil -} - -func registerSession() error { - if BConfig.WebConfig.Session.SessionOn { - var err error - sessionConfig := AppConfig.String("sessionConfig") - conf := new(session.ManagerConfig) - if sessionConfig == "" { - conf.CookieName = BConfig.WebConfig.Session.SessionName - conf.EnableSetCookie = BConfig.WebConfig.Session.SessionAutoSetCookie - conf.Gclifetime = BConfig.WebConfig.Session.SessionGCMaxLifetime - conf.Secure = BConfig.Listen.EnableHTTPS - conf.CookieLifeTime = BConfig.WebConfig.Session.SessionCookieLifeTime - conf.ProviderConfig = filepath.ToSlash(BConfig.WebConfig.Session.SessionProviderConfig) - conf.DisableHTTPOnly = BConfig.WebConfig.Session.SessionDisableHTTPOnly - conf.Domain = BConfig.WebConfig.Session.SessionDomain - conf.EnableSidInHTTPHeader = BConfig.WebConfig.Session.SessionEnableSidInHTTPHeader - conf.SessionNameInHTTPHeader = BConfig.WebConfig.Session.SessionNameInHTTPHeader - conf.EnableSidInURLQuery = BConfig.WebConfig.Session.SessionEnableSidInURLQuery - conf.CookieSameSite = BConfig.WebConfig.Session.SessionCookieSameSite - } else { - if err = json.Unmarshal([]byte(sessionConfig), conf); err != nil { - return err - } - } - if GlobalSessions, err = session.NewManager(BConfig.WebConfig.Session.SessionProvider, conf); err != nil { - return err - } - go GlobalSessions.GC() - } - return nil -} - -func registerTemplate() error { - defer lockViewPaths() - if err := AddViewPath(BConfig.WebConfig.ViewsPath); err != nil { - if BConfig.RunMode == DEV { - logs.Warn(err) - } - return err - } - return nil -} - -func registerAdmin() error { - if BConfig.Listen.EnableAdmin { - go beeAdminApp.Run() - } - return nil -} - -func registerGzip() error { - if BConfig.EnableGzip { - context.InitGzip( - AppConfig.DefaultInt("gzipMinLength", -1), - AppConfig.DefaultInt("gzipCompressLevel", -1), - AppConfig.DefaultStrings("includedMethods", []string{"GET"}), - ) - } - return nil -} diff --git a/vendor/github.com/astaxie/beego/log.go b/vendor/github.com/astaxie/beego/log.go deleted file mode 100644 index cc4c0f81..00000000 --- a/vendor/github.com/astaxie/beego/log.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "strings" - - "github.com/astaxie/beego/logs" -) - -// Log levels to control the logging output. -// Deprecated: use github.com/astaxie/beego/logs instead. -const ( - LevelEmergency = iota - LevelAlert - LevelCritical - LevelError - LevelWarning - LevelNotice - LevelInformational - LevelDebug -) - -// BeeLogger references the used application logger. -// Deprecated: use github.com/astaxie/beego/logs instead. -var BeeLogger = logs.GetBeeLogger() - -// SetLevel sets the global log level used by the simple logger. -// Deprecated: use github.com/astaxie/beego/logs instead. -func SetLevel(l int) { - logs.SetLevel(l) -} - -// SetLogFuncCall set the CallDepth, default is 3 -// Deprecated: use github.com/astaxie/beego/logs instead. -func SetLogFuncCall(b bool) { - logs.SetLogFuncCall(b) -} - -// SetLogger sets a new logger. -// Deprecated: use github.com/astaxie/beego/logs instead. -func SetLogger(adaptername string, config string) error { - return logs.SetLogger(adaptername, config) -} - -// Emergency logs a message at emergency level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Emergency(v ...interface{}) { - logs.Emergency(generateFmtStr(len(v)), v...) -} - -// Alert logs a message at alert level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Alert(v ...interface{}) { - logs.Alert(generateFmtStr(len(v)), v...) -} - -// Critical logs a message at critical level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Critical(v ...interface{}) { - logs.Critical(generateFmtStr(len(v)), v...) -} - -// Error logs a message at error level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Error(v ...interface{}) { - logs.Error(generateFmtStr(len(v)), v...) -} - -// Warning logs a message at warning level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Warning(v ...interface{}) { - logs.Warning(generateFmtStr(len(v)), v...) -} - -// Warn compatibility alias for Warning() -// Deprecated: use github.com/astaxie/beego/logs instead. -func Warn(v ...interface{}) { - logs.Warn(generateFmtStr(len(v)), v...) -} - -// Notice logs a message at notice level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Notice(v ...interface{}) { - logs.Notice(generateFmtStr(len(v)), v...) -} - -// Informational logs a message at info level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Informational(v ...interface{}) { - logs.Informational(generateFmtStr(len(v)), v...) -} - -// Info compatibility alias for Warning() -// Deprecated: use github.com/astaxie/beego/logs instead. -func Info(v ...interface{}) { - logs.Info(generateFmtStr(len(v)), v...) -} - -// Debug logs a message at debug level. -// Deprecated: use github.com/astaxie/beego/logs instead. -func Debug(v ...interface{}) { - logs.Debug(generateFmtStr(len(v)), v...) -} - -// Trace logs a message at trace level. -// compatibility alias for Warning() -// Deprecated: use github.com/astaxie/beego/logs instead. -func Trace(v ...interface{}) { - logs.Trace(generateFmtStr(len(v)), v...) -} - -func generateFmtStr(n int) string { - return strings.Repeat("%v ", n) -} diff --git a/vendor/github.com/astaxie/beego/logs/README.md b/vendor/github.com/astaxie/beego/logs/README.md deleted file mode 100644 index c05bcc04..00000000 --- a/vendor/github.com/astaxie/beego/logs/README.md +++ /dev/null @@ -1,72 +0,0 @@ -## logs -logs is a Go logs manager. It can use many logs adapters. The repo is inspired by `database/sql` . - - -## How to install? - - go get github.com/astaxie/beego/logs - - -## What adapters are supported? - -As of now this logs support console, file,smtp and conn. - - -## How to use it? - -First you must import it - -```golang -import ( - "github.com/astaxie/beego/logs" -) -``` - -Then init a Log (example with console adapter) - -```golang -log := logs.NewLogger(10000) -log.SetLogger("console", "") -``` - -> the first params stand for how many channel - -Use it like this: - -```golang -log.Trace("trace") -log.Info("info") -log.Warn("warning") -log.Debug("debug") -log.Critical("critical") -``` - -## File adapter - -Configure file adapter like this: - -```golang -log := NewLogger(10000) -log.SetLogger("file", `{"filename":"test.log"}`) -``` - -## Conn adapter - -Configure like this: - -```golang -log := NewLogger(1000) -log.SetLogger("conn", `{"net":"tcp","addr":":7020"}`) -log.Info("info") -``` - -## Smtp adapter - -Configure like this: - -```golang -log := NewLogger(10000) -log.SetLogger("smtp", `{"username":"beegotest@gmail.com","password":"xxxxxxxx","host":"smtp.gmail.com:587","sendTos":["xiemengjun@gmail.com"]}`) -log.Critical("sendmail critical") -time.Sleep(time.Second * 30) -``` diff --git a/vendor/github.com/astaxie/beego/logs/accesslog.go b/vendor/github.com/astaxie/beego/logs/accesslog.go deleted file mode 100644 index 9011b602..00000000 --- a/vendor/github.com/astaxie/beego/logs/accesslog.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - "time" -) - -const ( - apacheFormatPattern = "%s - - [%s] \"%s %d %d\" %f %s %s" - apacheFormat = "APACHE_FORMAT" - jsonFormat = "JSON_FORMAT" -) - -// AccessLogRecord struct for holding access log data. -type AccessLogRecord struct { - RemoteAddr string `json:"remote_addr"` - RequestTime time.Time `json:"request_time"` - RequestMethod string `json:"request_method"` - Request string `json:"request"` - ServerProtocol string `json:"server_protocol"` - Host string `json:"host"` - Status int `json:"status"` - BodyBytesSent int64 `json:"body_bytes_sent"` - ElapsedTime time.Duration `json:"elapsed_time"` - HTTPReferrer string `json:"http_referrer"` - HTTPUserAgent string `json:"http_user_agent"` - RemoteUser string `json:"remote_user"` -} - -func (r *AccessLogRecord) json() ([]byte, error) { - buffer := &bytes.Buffer{} - encoder := json.NewEncoder(buffer) - disableEscapeHTML(encoder) - - err := encoder.Encode(r) - return buffer.Bytes(), err -} - -func disableEscapeHTML(i interface{}) { - if e, ok := i.(interface { - SetEscapeHTML(bool) - }); ok { - e.SetEscapeHTML(false) - } -} - -// AccessLog - Format and print access log. -func AccessLog(r *AccessLogRecord, format string) { - var msg string - switch format { - case apacheFormat: - timeFormatted := r.RequestTime.Format("02/Jan/2006 03:04:05") - msg = fmt.Sprintf(apacheFormatPattern, r.RemoteAddr, timeFormatted, r.Request, r.Status, r.BodyBytesSent, - r.ElapsedTime.Seconds(), r.HTTPReferrer, r.HTTPUserAgent) - case jsonFormat: - fallthrough - default: - jsonData, err := r.json() - if err != nil { - msg = fmt.Sprintf(`{"Error": "%s"}`, err) - } else { - msg = string(jsonData) - } - } - beeLogger.writeMsg(levelLoggerImpl, strings.TrimSpace(msg)) -} diff --git a/vendor/github.com/astaxie/beego/logs/conn.go b/vendor/github.com/astaxie/beego/logs/conn.go deleted file mode 100644 index 74c458ab..00000000 --- a/vendor/github.com/astaxie/beego/logs/conn.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "encoding/json" - "io" - "net" - "time" -) - -// connWriter implements LoggerInterface. -// it writes messages in keep-live tcp connection. -type connWriter struct { - lg *logWriter - innerWriter io.WriteCloser - ReconnectOnMsg bool `json:"reconnectOnMsg"` - Reconnect bool `json:"reconnect"` - Net string `json:"net"` - Addr string `json:"addr"` - Level int `json:"level"` -} - -// NewConn create new ConnWrite returning as LoggerInterface. -func NewConn() Logger { - conn := new(connWriter) - conn.Level = LevelTrace - return conn -} - -// Init init connection writer with json config. -// json config only need key "level". -func (c *connWriter) Init(jsonConfig string) error { - return json.Unmarshal([]byte(jsonConfig), c) -} - -// WriteMsg write message in connection. -// if connection is down, try to re-connect. -func (c *connWriter) WriteMsg(when time.Time, msg string, level int) error { - if level > c.Level { - return nil - } - if c.needToConnectOnMsg() { - err := c.connect() - if err != nil { - return err - } - } - - if c.ReconnectOnMsg { - defer c.innerWriter.Close() - } - - _, err := c.lg.writeln(when, msg) - if err != nil { - return err - } - return nil -} - -// Flush implementing method. empty. -func (c *connWriter) Flush() { - -} - -// Destroy destroy connection writer and close tcp listener. -func (c *connWriter) Destroy() { - if c.innerWriter != nil { - c.innerWriter.Close() - } -} - -func (c *connWriter) connect() error { - if c.innerWriter != nil { - c.innerWriter.Close() - c.innerWriter = nil - } - - conn, err := net.Dial(c.Net, c.Addr) - if err != nil { - return err - } - - if tcpConn, ok := conn.(*net.TCPConn); ok { - tcpConn.SetKeepAlive(true) - } - - c.innerWriter = conn - c.lg = newLogWriter(conn) - return nil -} - -func (c *connWriter) needToConnectOnMsg() bool { - if c.Reconnect { - return true - } - - if c.innerWriter == nil { - return true - } - - return c.ReconnectOnMsg -} - -func init() { - Register(AdapterConn, NewConn) -} diff --git a/vendor/github.com/astaxie/beego/logs/console.go b/vendor/github.com/astaxie/beego/logs/console.go deleted file mode 100644 index 3dcaee1d..00000000 --- a/vendor/github.com/astaxie/beego/logs/console.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "encoding/json" - "os" - "strings" - "time" - - "github.com/shiena/ansicolor" -) - -// brush is a color join function -type brush func(string) string - -// newBrush return a fix color Brush -func newBrush(color string) brush { - pre := "\033[" - reset := "\033[0m" - return func(text string) string { - return pre + color + "m" + text + reset - } -} - -var colors = []brush{ - newBrush("1;37"), // Emergency white - newBrush("1;36"), // Alert cyan - newBrush("1;35"), // Critical magenta - newBrush("1;31"), // Error red - newBrush("1;33"), // Warning yellow - newBrush("1;32"), // Notice green - newBrush("1;34"), // Informational blue - newBrush("1;44"), // Debug Background blue -} - -// consoleWriter implements LoggerInterface and writes messages to terminal. -type consoleWriter struct { - lg *logWriter - Level int `json:"level"` - Colorful bool `json:"color"` //this filed is useful only when system's terminal supports color -} - -// NewConsole create ConsoleWriter returning as LoggerInterface. -func NewConsole() Logger { - cw := &consoleWriter{ - lg: newLogWriter(ansicolor.NewAnsiColorWriter(os.Stdout)), - Level: LevelDebug, - Colorful: true, - } - return cw -} - -// Init init console logger. -// jsonConfig like '{"level":LevelTrace}'. -func (c *consoleWriter) Init(jsonConfig string) error { - if len(jsonConfig) == 0 { - return nil - } - return json.Unmarshal([]byte(jsonConfig), c) -} - -// WriteMsg write message in console. -func (c *consoleWriter) WriteMsg(when time.Time, msg string, level int) error { - if level > c.Level { - return nil - } - if c.Colorful { - msg = strings.Replace(msg, levelPrefix[level], colors[level](levelPrefix[level]), 1) - } - c.lg.writeln(when, msg) - return nil -} - -// Destroy implementing method. empty. -func (c *consoleWriter) Destroy() { - -} - -// Flush implementing method. empty. -func (c *consoleWriter) Flush() { - -} - -func init() { - Register(AdapterConsole, NewConsole) -} diff --git a/vendor/github.com/astaxie/beego/logs/file.go b/vendor/github.com/astaxie/beego/logs/file.go deleted file mode 100644 index 40a3572a..00000000 --- a/vendor/github.com/astaxie/beego/logs/file.go +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "path" - "path/filepath" - "strconv" - "strings" - "sync" - "time" -) - -// fileLogWriter implements LoggerInterface. -// It writes messages by lines limit, file size limit, or time frequency. -type fileLogWriter struct { - sync.RWMutex // write log order by order and atomic incr maxLinesCurLines and maxSizeCurSize - // The opened file - Filename string `json:"filename"` - fileWriter *os.File - - // Rotate at line - MaxLines int `json:"maxlines"` - maxLinesCurLines int - - MaxFiles int `json:"maxfiles"` - MaxFilesCurFiles int - - // Rotate at size - MaxSize int `json:"maxsize"` - maxSizeCurSize int - - // Rotate daily - Daily bool `json:"daily"` - MaxDays int64 `json:"maxdays"` - dailyOpenDate int - dailyOpenTime time.Time - - // Rotate hourly - Hourly bool `json:"hourly"` - MaxHours int64 `json:"maxhours"` - hourlyOpenDate int - hourlyOpenTime time.Time - - Rotate bool `json:"rotate"` - - Level int `json:"level"` - - Perm string `json:"perm"` - - RotatePerm string `json:"rotateperm"` - - fileNameOnly, suffix string // like "project.log", project is fileNameOnly and .log is suffix -} - -// newFileWriter create a FileLogWriter returning as LoggerInterface. -func newFileWriter() Logger { - w := &fileLogWriter{ - Daily: true, - MaxDays: 7, - Hourly: false, - MaxHours: 168, - Rotate: true, - RotatePerm: "0440", - Level: LevelTrace, - Perm: "0660", - MaxLines: 10000000, - MaxFiles: 999, - MaxSize: 1 << 28, - } - return w -} - -// Init file logger with json config. -// jsonConfig like: -// { -// "filename":"logs/beego.log", -// "maxLines":10000, -// "maxsize":1024, -// "daily":true, -// "maxDays":15, -// "rotate":true, -// "perm":"0600" -// } -func (w *fileLogWriter) Init(jsonConfig string) error { - err := json.Unmarshal([]byte(jsonConfig), w) - if err != nil { - return err - } - if len(w.Filename) == 0 { - return errors.New("jsonconfig must have filename") - } - w.suffix = filepath.Ext(w.Filename) - w.fileNameOnly = strings.TrimSuffix(w.Filename, w.suffix) - if w.suffix == "" { - w.suffix = ".log" - } - err = w.startLogger() - return err -} - -// start file logger. create log file and set to locker-inside file writer. -func (w *fileLogWriter) startLogger() error { - file, err := w.createLogFile() - if err != nil { - return err - } - if w.fileWriter != nil { - w.fileWriter.Close() - } - w.fileWriter = file - return w.initFd() -} - -func (w *fileLogWriter) needRotateDaily(size int, day int) bool { - return (w.MaxLines > 0 && w.maxLinesCurLines >= w.MaxLines) || - (w.MaxSize > 0 && w.maxSizeCurSize >= w.MaxSize) || - (w.Daily && day != w.dailyOpenDate) -} - -func (w *fileLogWriter) needRotateHourly(size int, hour int) bool { - return (w.MaxLines > 0 && w.maxLinesCurLines >= w.MaxLines) || - (w.MaxSize > 0 && w.maxSizeCurSize >= w.MaxSize) || - (w.Hourly && hour != w.hourlyOpenDate) - -} - -// WriteMsg write logger message into file. -func (w *fileLogWriter) WriteMsg(when time.Time, msg string, level int) error { - if level > w.Level { - return nil - } - hd, d, h := formatTimeHeader(when) - msg = string(hd) + msg + "\n" - if w.Rotate { - w.RLock() - if w.needRotateHourly(len(msg), h) { - w.RUnlock() - w.Lock() - if w.needRotateHourly(len(msg), h) { - if err := w.doRotate(when); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) - } - } - w.Unlock() - } else if w.needRotateDaily(len(msg), d) { - w.RUnlock() - w.Lock() - if w.needRotateDaily(len(msg), d) { - if err := w.doRotate(when); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) - } - } - w.Unlock() - } else { - w.RUnlock() - } - } - - w.Lock() - _, err := w.fileWriter.Write([]byte(msg)) - if err == nil { - w.maxLinesCurLines++ - w.maxSizeCurSize += len(msg) - } - w.Unlock() - return err -} - -func (w *fileLogWriter) createLogFile() (*os.File, error) { - // Open the log file - perm, err := strconv.ParseInt(w.Perm, 8, 64) - if err != nil { - return nil, err - } - - filepath := path.Dir(w.Filename) - os.MkdirAll(filepath, os.FileMode(perm)) - - fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(perm)) - if err == nil { - // Make sure file perm is user set perm cause of `os.OpenFile` will obey umask - os.Chmod(w.Filename, os.FileMode(perm)) - } - return fd, err -} - -func (w *fileLogWriter) initFd() error { - fd := w.fileWriter - fInfo, err := fd.Stat() - if err != nil { - return fmt.Errorf("get stat err: %s", err) - } - w.maxSizeCurSize = int(fInfo.Size()) - w.dailyOpenTime = time.Now() - w.dailyOpenDate = w.dailyOpenTime.Day() - w.hourlyOpenTime = time.Now() - w.hourlyOpenDate = w.hourlyOpenTime.Hour() - w.maxLinesCurLines = 0 - if w.Hourly { - go w.hourlyRotate(w.hourlyOpenTime) - } else if w.Daily { - go w.dailyRotate(w.dailyOpenTime) - } - if fInfo.Size() > 0 && w.MaxLines > 0 { - count, err := w.lines() - if err != nil { - return err - } - w.maxLinesCurLines = count - } - return nil -} - -func (w *fileLogWriter) dailyRotate(openTime time.Time) { - y, m, d := openTime.Add(24 * time.Hour).Date() - nextDay := time.Date(y, m, d, 0, 0, 0, 0, openTime.Location()) - tm := time.NewTimer(time.Duration(nextDay.UnixNano() - openTime.UnixNano() + 100)) - <-tm.C - w.Lock() - if w.needRotateDaily(0, time.Now().Day()) { - if err := w.doRotate(time.Now()); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) - } - } - w.Unlock() -} - -func (w *fileLogWriter) hourlyRotate(openTime time.Time) { - y, m, d := openTime.Add(1 * time.Hour).Date() - h, _, _ := openTime.Add(1 * time.Hour).Clock() - nextHour := time.Date(y, m, d, h, 0, 0, 0, openTime.Location()) - tm := time.NewTimer(time.Duration(nextHour.UnixNano() - openTime.UnixNano() + 100)) - <-tm.C - w.Lock() - if w.needRotateHourly(0, time.Now().Hour()) { - if err := w.doRotate(time.Now()); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) - } - } - w.Unlock() -} - -func (w *fileLogWriter) lines() (int, error) { - fd, err := os.Open(w.Filename) - if err != nil { - return 0, err - } - defer fd.Close() - - buf := make([]byte, 32768) // 32k - count := 0 - lineSep := []byte{'\n'} - - for { - c, err := fd.Read(buf) - if err != nil && err != io.EOF { - return count, err - } - - count += bytes.Count(buf[:c], lineSep) - - if err == io.EOF { - break - } - } - - return count, nil -} - -// DoRotate means it need to write file in new file. -// new file name like xx.2013-01-01.log (daily) or xx.001.log (by line or size) -func (w *fileLogWriter) doRotate(logTime time.Time) error { - // file exists - // Find the next available number - num := w.MaxFilesCurFiles + 1 - fName := "" - format := "" - var openTime time.Time - rotatePerm, err := strconv.ParseInt(w.RotatePerm, 8, 64) - if err != nil { - return err - } - - _, err = os.Lstat(w.Filename) - if err != nil { - //even if the file is not exist or other ,we should RESTART the logger - goto RESTART_LOGGER - } - - if w.Hourly { - format = "2006010215" - openTime = w.hourlyOpenTime - } else if w.Daily { - format = "2006-01-02" - openTime = w.dailyOpenTime - } - - // only when one of them be setted, then the file would be splited - if w.MaxLines > 0 || w.MaxSize > 0 { - for ; err == nil && num <= w.MaxFiles; num++ { - fName = w.fileNameOnly + fmt.Sprintf(".%s.%03d%s", logTime.Format(format), num, w.suffix) - _, err = os.Lstat(fName) - } - } else { - fName = w.fileNameOnly + fmt.Sprintf(".%s.%03d%s", openTime.Format(format), num, w.suffix) - _, err = os.Lstat(fName) - w.MaxFilesCurFiles = num - } - - // return error if the last file checked still existed - if err == nil { - return fmt.Errorf("Rotate: Cannot find free log number to rename %s", w.Filename) - } - - // close fileWriter before rename - w.fileWriter.Close() - - // Rename the file to its new found name - // even if occurs error,we MUST guarantee to restart new logger - err = os.Rename(w.Filename, fName) - if err != nil { - goto RESTART_LOGGER - } - - err = os.Chmod(fName, os.FileMode(rotatePerm)) - -RESTART_LOGGER: - - startLoggerErr := w.startLogger() - go w.deleteOldLog() - - if startLoggerErr != nil { - return fmt.Errorf("Rotate StartLogger: %s", startLoggerErr) - } - if err != nil { - return fmt.Errorf("Rotate: %s", err) - } - return nil -} - -func (w *fileLogWriter) deleteOldLog() { - dir := filepath.Dir(w.Filename) - absolutePath, err := filepath.EvalSymlinks(w.Filename) - if err == nil { - dir = filepath.Dir(absolutePath) - } - filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) { - defer func() { - if r := recover(); r != nil { - fmt.Fprintf(os.Stderr, "Unable to delete old log '%s', error: %v\n", path, r) - } - }() - - if info == nil { - return - } - if w.Hourly { - if !info.IsDir() && info.ModTime().Add(1*time.Hour*time.Duration(w.MaxHours)).Before(time.Now()) { - if strings.HasPrefix(filepath.Base(path), filepath.Base(w.fileNameOnly)) && - strings.HasSuffix(filepath.Base(path), w.suffix) { - os.Remove(path) - } - } - } else if w.Daily { - if !info.IsDir() && info.ModTime().Add(24*time.Hour*time.Duration(w.MaxDays)).Before(time.Now()) { - if strings.HasPrefix(filepath.Base(path), filepath.Base(w.fileNameOnly)) && - strings.HasSuffix(filepath.Base(path), w.suffix) { - os.Remove(path) - } - } - } - return - }) -} - -// Destroy close the file description, close file writer. -func (w *fileLogWriter) Destroy() { - w.fileWriter.Close() -} - -// Flush flush file logger. -// there are no buffering messages in file logger in memory. -// flush file means sync file from disk. -func (w *fileLogWriter) Flush() { - w.fileWriter.Sync() -} - -func init() { - Register(AdapterFile, newFileWriter) -} diff --git a/vendor/github.com/astaxie/beego/logs/jianliao.go b/vendor/github.com/astaxie/beego/logs/jianliao.go deleted file mode 100644 index 88ba0f9a..00000000 --- a/vendor/github.com/astaxie/beego/logs/jianliao.go +++ /dev/null @@ -1,72 +0,0 @@ -package logs - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "time" -) - -// JLWriter implements beego LoggerInterface and is used to send jiaoliao webhook -type JLWriter struct { - AuthorName string `json:"authorname"` - Title string `json:"title"` - WebhookURL string `json:"webhookurl"` - RedirectURL string `json:"redirecturl,omitempty"` - ImageURL string `json:"imageurl,omitempty"` - Level int `json:"level"` -} - -// newJLWriter create jiaoliao writer. -func newJLWriter() Logger { - return &JLWriter{Level: LevelTrace} -} - -// Init JLWriter with json config string -func (s *JLWriter) Init(jsonconfig string) error { - return json.Unmarshal([]byte(jsonconfig), s) -} - -// WriteMsg write message in smtp writer. -// it will send an email with subject and only this message. -func (s *JLWriter) WriteMsg(when time.Time, msg string, level int) error { - if level > s.Level { - return nil - } - - text := fmt.Sprintf("%s %s", when.Format("2006-01-02 15:04:05"), msg) - - form := url.Values{} - form.Add("authorName", s.AuthorName) - form.Add("title", s.Title) - form.Add("text", text) - if s.RedirectURL != "" { - form.Add("redirectUrl", s.RedirectURL) - } - if s.ImageURL != "" { - form.Add("imageUrl", s.ImageURL) - } - - resp, err := http.PostForm(s.WebhookURL, form) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("Post webhook failed %s %d", resp.Status, resp.StatusCode) - } - return nil -} - -// Flush implementing method. empty. -func (s *JLWriter) Flush() { -} - -// Destroy implementing method. empty. -func (s *JLWriter) Destroy() { -} - -func init() { - Register(AdapterJianLiao, newJLWriter) -} diff --git a/vendor/github.com/astaxie/beego/logs/log.go b/vendor/github.com/astaxie/beego/logs/log.go deleted file mode 100644 index 39c006d2..00000000 --- a/vendor/github.com/astaxie/beego/logs/log.go +++ /dev/null @@ -1,669 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package logs provide a general log interface -// Usage: -// -// import "github.com/astaxie/beego/logs" -// -// log := NewLogger(10000) -// log.SetLogger("console", "") -// -// > the first params stand for how many channel -// -// Use it like this: -// -// log.Trace("trace") -// log.Info("info") -// log.Warn("warning") -// log.Debug("debug") -// log.Critical("critical") -// -// more docs http://beego.me/docs/module/logs.md -package logs - -import ( - "fmt" - "log" - "os" - "path" - "runtime" - "strconv" - "strings" - "sync" - "time" -) - -// RFC5424 log message levels. -const ( - LevelEmergency = iota - LevelAlert - LevelCritical - LevelError - LevelWarning - LevelNotice - LevelInformational - LevelDebug -) - -// levelLogLogger is defined to implement log.Logger -// the real log level will be LevelEmergency -const levelLoggerImpl = -1 - -// Name for adapter with beego official support -const ( - AdapterConsole = "console" - AdapterFile = "file" - AdapterMultiFile = "multifile" - AdapterMail = "smtp" - AdapterConn = "conn" - AdapterEs = "es" - AdapterJianLiao = "jianliao" - AdapterSlack = "slack" - AdapterAliLS = "alils" -) - -// Legacy log level constants to ensure backwards compatibility. -const ( - LevelInfo = LevelInformational - LevelTrace = LevelDebug - LevelWarn = LevelWarning -) - -type newLoggerFunc func() Logger - -// Logger defines the behavior of a log provider. -type Logger interface { - Init(config string) error - WriteMsg(when time.Time, msg string, level int) error - Destroy() - Flush() -} - -var adapters = make(map[string]newLoggerFunc) -var levelPrefix = [LevelDebug + 1]string{"[M]", "[A]", "[C]", "[E]", "[W]", "[N]", "[I]", "[D]"} - -// Register makes a log provide available by the provided name. -// If Register is called twice with the same name or if driver is nil, -// it panics. -func Register(name string, log newLoggerFunc) { - if log == nil { - panic("logs: Register provide is nil") - } - if _, dup := adapters[name]; dup { - panic("logs: Register called twice for provider " + name) - } - adapters[name] = log -} - -// BeeLogger is default logger in beego application. -// it can contain several providers and log message into all providers. -type BeeLogger struct { - lock sync.Mutex - level int - init bool - enableFuncCallDepth bool - loggerFuncCallDepth int - asynchronous bool - prefix string - msgChanLen int64 - msgChan chan *logMsg - signalChan chan string - wg sync.WaitGroup - outputs []*nameLogger -} - -const defaultAsyncMsgLen = 1e3 - -type nameLogger struct { - Logger - name string -} - -type logMsg struct { - level int - msg string - when time.Time -} - -var logMsgPool *sync.Pool - -// NewLogger returns a new BeeLogger. -// channelLen means the number of messages in chan(used where asynchronous is true). -// if the buffering chan is full, logger adapters write to file or other way. -func NewLogger(channelLens ...int64) *BeeLogger { - bl := new(BeeLogger) - bl.level = LevelDebug - bl.loggerFuncCallDepth = 2 - bl.msgChanLen = append(channelLens, 0)[0] - if bl.msgChanLen <= 0 { - bl.msgChanLen = defaultAsyncMsgLen - } - bl.signalChan = make(chan string, 1) - bl.setLogger(AdapterConsole) - return bl -} - -// Async set the log to asynchronous and start the goroutine -func (bl *BeeLogger) Async(msgLen ...int64) *BeeLogger { - bl.lock.Lock() - defer bl.lock.Unlock() - if bl.asynchronous { - return bl - } - bl.asynchronous = true - if len(msgLen) > 0 && msgLen[0] > 0 { - bl.msgChanLen = msgLen[0] - } - bl.msgChan = make(chan *logMsg, bl.msgChanLen) - logMsgPool = &sync.Pool{ - New: func() interface{} { - return &logMsg{} - }, - } - bl.wg.Add(1) - go bl.startLogger() - return bl -} - -// SetLogger provides a given logger adapter into BeeLogger with config string. -// config need to be correct JSON as string: {"interval":360}. -func (bl *BeeLogger) setLogger(adapterName string, configs ...string) error { - config := append(configs, "{}")[0] - for _, l := range bl.outputs { - if l.name == adapterName { - return fmt.Errorf("logs: duplicate adaptername %q (you have set this logger before)", adapterName) - } - } - - logAdapter, ok := adapters[adapterName] - if !ok { - return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adapterName) - } - - lg := logAdapter() - err := lg.Init(config) - if err != nil { - fmt.Fprintln(os.Stderr, "logs.BeeLogger.SetLogger: "+err.Error()) - return err - } - bl.outputs = append(bl.outputs, &nameLogger{name: adapterName, Logger: lg}) - return nil -} - -// SetLogger provides a given logger adapter into BeeLogger with config string. -// config need to be correct JSON as string: {"interval":360}. -func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error { - bl.lock.Lock() - defer bl.lock.Unlock() - if !bl.init { - bl.outputs = []*nameLogger{} - bl.init = true - } - return bl.setLogger(adapterName, configs...) -} - -// DelLogger remove a logger adapter in BeeLogger. -func (bl *BeeLogger) DelLogger(adapterName string) error { - bl.lock.Lock() - defer bl.lock.Unlock() - outputs := []*nameLogger{} - for _, lg := range bl.outputs { - if lg.name == adapterName { - lg.Destroy() - } else { - outputs = append(outputs, lg) - } - } - if len(outputs) == len(bl.outputs) { - return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adapterName) - } - bl.outputs = outputs - return nil -} - -func (bl *BeeLogger) writeToLoggers(when time.Time, msg string, level int) { - for _, l := range bl.outputs { - err := l.WriteMsg(when, msg, level) - if err != nil { - fmt.Fprintf(os.Stderr, "unable to WriteMsg to adapter:%v,error:%v\n", l.name, err) - } - } -} - -func (bl *BeeLogger) Write(p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - // writeMsg will always add a '\n' character - if p[len(p)-1] == '\n' { - p = p[0 : len(p)-1] - } - // set levelLoggerImpl to ensure all log message will be write out - err = bl.writeMsg(levelLoggerImpl, string(p)) - if err == nil { - return len(p), err - } - return 0, err -} - -func (bl *BeeLogger) writeMsg(logLevel int, msg string, v ...interface{}) error { - if !bl.init { - bl.lock.Lock() - bl.setLogger(AdapterConsole) - bl.lock.Unlock() - } - - if len(v) > 0 { - msg = fmt.Sprintf(msg, v...) - } - - msg = bl.prefix + " " + msg - - when := time.Now() - if bl.enableFuncCallDepth { - _, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth) - if !ok { - file = "???" - line = 0 - } - _, filename := path.Split(file) - msg = "[" + filename + ":" + strconv.Itoa(line) + "] " + msg - } - - //set level info in front of filename info - if logLevel == levelLoggerImpl { - // set to emergency to ensure all log will be print out correctly - logLevel = LevelEmergency - } else { - msg = levelPrefix[logLevel] + " " + msg - } - - if bl.asynchronous { - lm := logMsgPool.Get().(*logMsg) - lm.level = logLevel - lm.msg = msg - lm.when = when - if bl.outputs != nil { - bl.msgChan <- lm - } else { - logMsgPool.Put(lm) - } - } else { - bl.writeToLoggers(when, msg, logLevel) - } - return nil -} - -// SetLevel Set log message level. -// If message level (such as LevelDebug) is higher than logger level (such as LevelWarning), -// log providers will not even be sent the message. -func (bl *BeeLogger) SetLevel(l int) { - bl.level = l -} - -// GetLevel Get Current log message level. -func (bl *BeeLogger) GetLevel() int { - return bl.level -} - -// SetLogFuncCallDepth set log funcCallDepth -func (bl *BeeLogger) SetLogFuncCallDepth(d int) { - bl.loggerFuncCallDepth = d -} - -// GetLogFuncCallDepth return log funcCallDepth for wrapper -func (bl *BeeLogger) GetLogFuncCallDepth() int { - return bl.loggerFuncCallDepth -} - -// EnableFuncCallDepth enable log funcCallDepth -func (bl *BeeLogger) EnableFuncCallDepth(b bool) { - bl.enableFuncCallDepth = b -} - -// set prefix -func (bl *BeeLogger) SetPrefix(s string) { - bl.prefix = s -} - -// start logger chan reading. -// when chan is not empty, write logs. -func (bl *BeeLogger) startLogger() { - gameOver := false - for { - select { - case bm := <-bl.msgChan: - bl.writeToLoggers(bm.when, bm.msg, bm.level) - logMsgPool.Put(bm) - case sg := <-bl.signalChan: - // Now should only send "flush" or "close" to bl.signalChan - bl.flush() - if sg == "close" { - for _, l := range bl.outputs { - l.Destroy() - } - bl.outputs = nil - gameOver = true - } - bl.wg.Done() - } - if gameOver { - break - } - } -} - -// Emergency Log EMERGENCY level message. -func (bl *BeeLogger) Emergency(format string, v ...interface{}) { - if LevelEmergency > bl.level { - return - } - bl.writeMsg(LevelEmergency, format, v...) -} - -// Alert Log ALERT level message. -func (bl *BeeLogger) Alert(format string, v ...interface{}) { - if LevelAlert > bl.level { - return - } - bl.writeMsg(LevelAlert, format, v...) -} - -// Critical Log CRITICAL level message. -func (bl *BeeLogger) Critical(format string, v ...interface{}) { - if LevelCritical > bl.level { - return - } - bl.writeMsg(LevelCritical, format, v...) -} - -// Error Log ERROR level message. -func (bl *BeeLogger) Error(format string, v ...interface{}) { - if LevelError > bl.level { - return - } - bl.writeMsg(LevelError, format, v...) -} - -// Warning Log WARNING level message. -func (bl *BeeLogger) Warning(format string, v ...interface{}) { - if LevelWarn > bl.level { - return - } - bl.writeMsg(LevelWarn, format, v...) -} - -// Notice Log NOTICE level message. -func (bl *BeeLogger) Notice(format string, v ...interface{}) { - if LevelNotice > bl.level { - return - } - bl.writeMsg(LevelNotice, format, v...) -} - -// Informational Log INFORMATIONAL level message. -func (bl *BeeLogger) Informational(format string, v ...interface{}) { - if LevelInfo > bl.level { - return - } - bl.writeMsg(LevelInfo, format, v...) -} - -// Debug Log DEBUG level message. -func (bl *BeeLogger) Debug(format string, v ...interface{}) { - if LevelDebug > bl.level { - return - } - bl.writeMsg(LevelDebug, format, v...) -} - -// Warn Log WARN level message. -// compatibility alias for Warning() -func (bl *BeeLogger) Warn(format string, v ...interface{}) { - if LevelWarn > bl.level { - return - } - bl.writeMsg(LevelWarn, format, v...) -} - -// Info Log INFO level message. -// compatibility alias for Informational() -func (bl *BeeLogger) Info(format string, v ...interface{}) { - if LevelInfo > bl.level { - return - } - bl.writeMsg(LevelInfo, format, v...) -} - -// Trace Log TRACE level message. -// compatibility alias for Debug() -func (bl *BeeLogger) Trace(format string, v ...interface{}) { - if LevelDebug > bl.level { - return - } - bl.writeMsg(LevelDebug, format, v...) -} - -// Flush flush all chan data. -func (bl *BeeLogger) Flush() { - if bl.asynchronous { - bl.signalChan <- "flush" - bl.wg.Wait() - bl.wg.Add(1) - return - } - bl.flush() -} - -// Close close logger, flush all chan data and destroy all adapters in BeeLogger. -func (bl *BeeLogger) Close() { - if bl.asynchronous { - bl.signalChan <- "close" - bl.wg.Wait() - close(bl.msgChan) - } else { - bl.flush() - for _, l := range bl.outputs { - l.Destroy() - } - bl.outputs = nil - } - close(bl.signalChan) -} - -// Reset close all outputs, and set bl.outputs to nil -func (bl *BeeLogger) Reset() { - bl.Flush() - for _, l := range bl.outputs { - l.Destroy() - } - bl.outputs = nil -} - -func (bl *BeeLogger) flush() { - if bl.asynchronous { - for { - if len(bl.msgChan) > 0 { - bm := <-bl.msgChan - bl.writeToLoggers(bm.when, bm.msg, bm.level) - logMsgPool.Put(bm) - continue - } - break - } - } - for _, l := range bl.outputs { - l.Flush() - } -} - -// beeLogger references the used application logger. -var beeLogger = NewLogger() - -// GetBeeLogger returns the default BeeLogger -func GetBeeLogger() *BeeLogger { - return beeLogger -} - -var beeLoggerMap = struct { - sync.RWMutex - logs map[string]*log.Logger -}{ - logs: map[string]*log.Logger{}, -} - -// GetLogger returns the default BeeLogger -func GetLogger(prefixes ...string) *log.Logger { - prefix := append(prefixes, "")[0] - if prefix != "" { - prefix = fmt.Sprintf(`[%s] `, strings.ToUpper(prefix)) - } - beeLoggerMap.RLock() - l, ok := beeLoggerMap.logs[prefix] - if ok { - beeLoggerMap.RUnlock() - return l - } - beeLoggerMap.RUnlock() - beeLoggerMap.Lock() - defer beeLoggerMap.Unlock() - l, ok = beeLoggerMap.logs[prefix] - if !ok { - l = log.New(beeLogger, prefix, 0) - beeLoggerMap.logs[prefix] = l - } - return l -} - -// Reset will remove all the adapter -func Reset() { - beeLogger.Reset() -} - -// Async set the beelogger with Async mode and hold msglen messages -func Async(msgLen ...int64) *BeeLogger { - return beeLogger.Async(msgLen...) -} - -// SetLevel sets the global log level used by the simple logger. -func SetLevel(l int) { - beeLogger.SetLevel(l) -} - -// SetPrefix sets the prefix -func SetPrefix(s string) { - beeLogger.SetPrefix(s) -} - -// EnableFuncCallDepth enable log funcCallDepth -func EnableFuncCallDepth(b bool) { - beeLogger.enableFuncCallDepth = b -} - -// SetLogFuncCall set the CallDepth, default is 4 -func SetLogFuncCall(b bool) { - beeLogger.EnableFuncCallDepth(b) - beeLogger.SetLogFuncCallDepth(4) -} - -// SetLogFuncCallDepth set log funcCallDepth -func SetLogFuncCallDepth(d int) { - beeLogger.loggerFuncCallDepth = d -} - -// SetLogger sets a new logger. -func SetLogger(adapter string, config ...string) error { - return beeLogger.SetLogger(adapter, config...) -} - -// Emergency logs a message at emergency level. -func Emergency(f interface{}, v ...interface{}) { - beeLogger.Emergency(formatLog(f, v...)) -} - -// Alert logs a message at alert level. -func Alert(f interface{}, v ...interface{}) { - beeLogger.Alert(formatLog(f, v...)) -} - -// Critical logs a message at critical level. -func Critical(f interface{}, v ...interface{}) { - beeLogger.Critical(formatLog(f, v...)) -} - -// Error logs a message at error level. -func Error(f interface{}, v ...interface{}) { - beeLogger.Error(formatLog(f, v...)) -} - -// Warning logs a message at warning level. -func Warning(f interface{}, v ...interface{}) { - beeLogger.Warn(formatLog(f, v...)) -} - -// Warn compatibility alias for Warning() -func Warn(f interface{}, v ...interface{}) { - beeLogger.Warn(formatLog(f, v...)) -} - -// Notice logs a message at notice level. -func Notice(f interface{}, v ...interface{}) { - beeLogger.Notice(formatLog(f, v...)) -} - -// Informational logs a message at info level. -func Informational(f interface{}, v ...interface{}) { - beeLogger.Info(formatLog(f, v...)) -} - -// Info compatibility alias for Warning() -func Info(f interface{}, v ...interface{}) { - beeLogger.Info(formatLog(f, v...)) -} - -// Debug logs a message at debug level. -func Debug(f interface{}, v ...interface{}) { - beeLogger.Debug(formatLog(f, v...)) -} - -// Trace logs a message at trace level. -// compatibility alias for Warning() -func Trace(f interface{}, v ...interface{}) { - beeLogger.Trace(formatLog(f, v...)) -} - -func formatLog(f interface{}, v ...interface{}) string { - var msg string - switch f.(type) { - case string: - msg = f.(string) - if len(v) == 0 { - return msg - } - if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") { - //format string - } else { - //do not contain format char - msg += strings.Repeat(" %v", len(v)) - } - default: - msg = fmt.Sprint(f) - if len(v) == 0 { - return msg - } - msg += strings.Repeat(" %v", len(v)) - } - return fmt.Sprintf(msg, v...) -} diff --git a/vendor/github.com/astaxie/beego/logs/logger.go b/vendor/github.com/astaxie/beego/logs/logger.go deleted file mode 100644 index a28bff6f..00000000 --- a/vendor/github.com/astaxie/beego/logs/logger.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "io" - "runtime" - "sync" - "time" -) - -type logWriter struct { - sync.Mutex - writer io.Writer -} - -func newLogWriter(wr io.Writer) *logWriter { - return &logWriter{writer: wr} -} - -func (lg *logWriter) writeln(when time.Time, msg string) (int, error) { - lg.Lock() - h, _, _ := formatTimeHeader(when) - n, err := lg.writer.Write(append(append(h, msg...), '\n')) - lg.Unlock() - return n, err -} - -const ( - y1 = `0123456789` - y2 = `0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789` - y3 = `0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999` - y4 = `0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789` - mo1 = `000000000111` - mo2 = `123456789012` - d1 = `0000000001111111111222222222233` - d2 = `1234567890123456789012345678901` - h1 = `000000000011111111112222` - h2 = `012345678901234567890123` - mi1 = `000000000011111111112222222222333333333344444444445555555555` - mi2 = `012345678901234567890123456789012345678901234567890123456789` - s1 = `000000000011111111112222222222333333333344444444445555555555` - s2 = `012345678901234567890123456789012345678901234567890123456789` - ns1 = `0123456789` -) - -func formatTimeHeader(when time.Time) ([]byte, int, int) { - y, mo, d := when.Date() - h, mi, s := when.Clock() - ns := when.Nanosecond() / 1000000 - //len("2006/01/02 15:04:05.123 ")==24 - var buf [24]byte - - buf[0] = y1[y/1000%10] - buf[1] = y2[y/100] - buf[2] = y3[y-y/100*100] - buf[3] = y4[y-y/100*100] - buf[4] = '/' - buf[5] = mo1[mo-1] - buf[6] = mo2[mo-1] - buf[7] = '/' - buf[8] = d1[d-1] - buf[9] = d2[d-1] - buf[10] = ' ' - buf[11] = h1[h] - buf[12] = h2[h] - buf[13] = ':' - buf[14] = mi1[mi] - buf[15] = mi2[mi] - buf[16] = ':' - buf[17] = s1[s] - buf[18] = s2[s] - buf[19] = '.' - buf[20] = ns1[ns/100] - buf[21] = ns1[ns%100/10] - buf[22] = ns1[ns%10] - - buf[23] = ' ' - - return buf[0:], d, h -} - -var ( - green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109}) - white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109}) - yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109}) - red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109}) - blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109}) - magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109}) - cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109}) - - w32Green = string([]byte{27, 91, 52, 50, 109}) - w32White = string([]byte{27, 91, 52, 55, 109}) - w32Yellow = string([]byte{27, 91, 52, 51, 109}) - w32Red = string([]byte{27, 91, 52, 49, 109}) - w32Blue = string([]byte{27, 91, 52, 52, 109}) - w32Magenta = string([]byte{27, 91, 52, 53, 109}) - w32Cyan = string([]byte{27, 91, 52, 54, 109}) - - reset = string([]byte{27, 91, 48, 109}) -) - -var once sync.Once -var colorMap map[string]string - -func initColor() { - if runtime.GOOS == "windows" { - green = w32Green - white = w32White - yellow = w32Yellow - red = w32Red - blue = w32Blue - magenta = w32Magenta - cyan = w32Cyan - } - colorMap = map[string]string{ - //by color - "green": green, - "white": white, - "yellow": yellow, - "red": red, - //by method - "GET": blue, - "POST": cyan, - "PUT": yellow, - "DELETE": red, - "PATCH": green, - "HEAD": magenta, - "OPTIONS": white, - } -} - -// ColorByStatus return color by http code -// 2xx return Green -// 3xx return White -// 4xx return Yellow -// 5xx return Red -func ColorByStatus(code int) string { - once.Do(initColor) - switch { - case code >= 200 && code < 300: - return colorMap["green"] - case code >= 300 && code < 400: - return colorMap["white"] - case code >= 400 && code < 500: - return colorMap["yellow"] - default: - return colorMap["red"] - } -} - -// ColorByMethod return color by http code -func ColorByMethod(method string) string { - once.Do(initColor) - if c := colorMap[method]; c != "" { - return c - } - return reset -} - -// ResetColor return reset color -func ResetColor() string { - return reset -} diff --git a/vendor/github.com/astaxie/beego/logs/multifile.go b/vendor/github.com/astaxie/beego/logs/multifile.go deleted file mode 100644 index 90168274..00000000 --- a/vendor/github.com/astaxie/beego/logs/multifile.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "encoding/json" - "time" -) - -// A filesLogWriter manages several fileLogWriter -// filesLogWriter will write logs to the file in json configuration and write the same level log to correspond file -// means if the file name in configuration is project.log filesLogWriter will create project.error.log/project.debug.log -// and write the error-level logs to project.error.log and write the debug-level logs to project.debug.log -// the rotate attribute also acts like fileLogWriter -type multiFileLogWriter struct { - writers [LevelDebug + 1 + 1]*fileLogWriter // the last one for fullLogWriter - fullLogWriter *fileLogWriter - Separate []string `json:"separate"` -} - -var levelNames = [...]string{"emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"} - -// Init file logger with json config. -// jsonConfig like: -// { -// "filename":"logs/beego.log", -// "maxLines":0, -// "maxsize":0, -// "daily":true, -// "maxDays":15, -// "rotate":true, -// "perm":0600, -// "separate":["emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"], -// } - -func (f *multiFileLogWriter) Init(config string) error { - writer := newFileWriter().(*fileLogWriter) - err := writer.Init(config) - if err != nil { - return err - } - f.fullLogWriter = writer - f.writers[LevelDebug+1] = writer - - //unmarshal "separate" field to f.Separate - json.Unmarshal([]byte(config), f) - - jsonMap := map[string]interface{}{} - json.Unmarshal([]byte(config), &jsonMap) - - for i := LevelEmergency; i < LevelDebug+1; i++ { - for _, v := range f.Separate { - if v == levelNames[i] { - jsonMap["filename"] = f.fullLogWriter.fileNameOnly + "." + levelNames[i] + f.fullLogWriter.suffix - jsonMap["level"] = i - bs, _ := json.Marshal(jsonMap) - writer = newFileWriter().(*fileLogWriter) - err := writer.Init(string(bs)) - if err != nil { - return err - } - f.writers[i] = writer - } - } - } - - return nil -} - -func (f *multiFileLogWriter) Destroy() { - for i := 0; i < len(f.writers); i++ { - if f.writers[i] != nil { - f.writers[i].Destroy() - } - } -} - -func (f *multiFileLogWriter) WriteMsg(when time.Time, msg string, level int) error { - if f.fullLogWriter != nil { - f.fullLogWriter.WriteMsg(when, msg, level) - } - for i := 0; i < len(f.writers)-1; i++ { - if f.writers[i] != nil { - if level == f.writers[i].Level { - f.writers[i].WriteMsg(when, msg, level) - } - } - } - return nil -} - -func (f *multiFileLogWriter) Flush() { - for i := 0; i < len(f.writers); i++ { - if f.writers[i] != nil { - f.writers[i].Flush() - } - } -} - -// newFilesWriter create a FileLogWriter returning as LoggerInterface. -func newFilesWriter() Logger { - return &multiFileLogWriter{} -} - -func init() { - Register(AdapterMultiFile, newFilesWriter) -} diff --git a/vendor/github.com/astaxie/beego/logs/slack.go b/vendor/github.com/astaxie/beego/logs/slack.go deleted file mode 100644 index 1cd2e5ae..00000000 --- a/vendor/github.com/astaxie/beego/logs/slack.go +++ /dev/null @@ -1,60 +0,0 @@ -package logs - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "time" -) - -// SLACKWriter implements beego LoggerInterface and is used to send jiaoliao webhook -type SLACKWriter struct { - WebhookURL string `json:"webhookurl"` - Level int `json:"level"` -} - -// newSLACKWriter create jiaoliao writer. -func newSLACKWriter() Logger { - return &SLACKWriter{Level: LevelTrace} -} - -// Init SLACKWriter with json config string -func (s *SLACKWriter) Init(jsonconfig string) error { - return json.Unmarshal([]byte(jsonconfig), s) -} - -// WriteMsg write message in smtp writer. -// it will send an email with subject and only this message. -func (s *SLACKWriter) WriteMsg(when time.Time, msg string, level int) error { - if level > s.Level { - return nil - } - - text := fmt.Sprintf("{\"text\": \"%s %s\"}", when.Format("2006-01-02 15:04:05"), msg) - - form := url.Values{} - form.Add("payload", text) - - resp, err := http.PostForm(s.WebhookURL, form) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("Post webhook failed %s %d", resp.Status, resp.StatusCode) - } - return nil -} - -// Flush implementing method. empty. -func (s *SLACKWriter) Flush() { -} - -// Destroy implementing method. empty. -func (s *SLACKWriter) Destroy() { -} - -func init() { - Register(AdapterSlack, newSLACKWriter) -} diff --git a/vendor/github.com/astaxie/beego/logs/smtp.go b/vendor/github.com/astaxie/beego/logs/smtp.go deleted file mode 100644 index 6208d7b8..00000000 --- a/vendor/github.com/astaxie/beego/logs/smtp.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "crypto/tls" - "encoding/json" - "fmt" - "net" - "net/smtp" - "strings" - "time" -) - -// SMTPWriter implements LoggerInterface and is used to send emails via given SMTP-server. -type SMTPWriter struct { - Username string `json:"username"` - Password string `json:"password"` - Host string `json:"host"` - Subject string `json:"subject"` - FromAddress string `json:"fromAddress"` - RecipientAddresses []string `json:"sendTos"` - Level int `json:"level"` -} - -// NewSMTPWriter create smtp writer. -func newSMTPWriter() Logger { - return &SMTPWriter{Level: LevelTrace} -} - -// Init smtp writer with json config. -// config like: -// { -// "username":"example@gmail.com", -// "password:"password", -// "host":"smtp.gmail.com:465", -// "subject":"email title", -// "fromAddress":"from@example.com", -// "sendTos":["email1","email2"], -// "level":LevelError -// } -func (s *SMTPWriter) Init(jsonconfig string) error { - return json.Unmarshal([]byte(jsonconfig), s) -} - -func (s *SMTPWriter) getSMTPAuth(host string) smtp.Auth { - if len(strings.Trim(s.Username, " ")) == 0 && len(strings.Trim(s.Password, " ")) == 0 { - return nil - } - return smtp.PlainAuth( - "", - s.Username, - s.Password, - host, - ) -} - -func (s *SMTPWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAddress string, recipients []string, msgContent []byte) error { - client, err := smtp.Dial(hostAddressWithPort) - if err != nil { - return err - } - - host, _, _ := net.SplitHostPort(hostAddressWithPort) - tlsConn := &tls.Config{ - InsecureSkipVerify: true, - ServerName: host, - } - if err = client.StartTLS(tlsConn); err != nil { - return err - } - - if auth != nil { - if err = client.Auth(auth); err != nil { - return err - } - } - - if err = client.Mail(fromAddress); err != nil { - return err - } - - for _, rec := range recipients { - if err = client.Rcpt(rec); err != nil { - return err - } - } - - w, err := client.Data() - if err != nil { - return err - } - _, err = w.Write(msgContent) - if err != nil { - return err - } - - err = w.Close() - if err != nil { - return err - } - - return client.Quit() -} - -// WriteMsg write message in smtp writer. -// it will send an email with subject and only this message. -func (s *SMTPWriter) WriteMsg(when time.Time, msg string, level int) error { - if level > s.Level { - return nil - } - - hp := strings.Split(s.Host, ":") - - // Set up authentication information. - auth := s.getSMTPAuth(hp[0]) - - // Connect to the server, authenticate, set the sender and recipient, - // and send the email all in one step. - contentType := "Content-Type: text/plain" + "; charset=UTF-8" - mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress + - ">\r\nSubject: " + s.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", when.Format("2006-01-02 15:04:05")) + msg) - - return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg) -} - -// Flush implementing method. empty. -func (s *SMTPWriter) Flush() { -} - -// Destroy implementing method. empty. -func (s *SMTPWriter) Destroy() { -} - -func init() { - Register(AdapterMail, newSMTPWriter) -} diff --git a/vendor/github.com/astaxie/beego/mime.go b/vendor/github.com/astaxie/beego/mime.go deleted file mode 100644 index ca2878ab..00000000 --- a/vendor/github.com/astaxie/beego/mime.go +++ /dev/null @@ -1,556 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -var mimemaps = map[string]string{ - ".3dm": "x-world/x-3dmf", - ".3dmf": "x-world/x-3dmf", - ".7z": "application/x-7z-compressed", - ".a": "application/octet-stream", - ".aab": "application/x-authorware-bin", - ".aam": "application/x-authorware-map", - ".aas": "application/x-authorware-seg", - ".abc": "text/vndabc", - ".ace": "application/x-ace-compressed", - ".acgi": "text/html", - ".afl": "video/animaflex", - ".ai": "application/postscript", - ".aif": "audio/aiff", - ".aifc": "audio/aiff", - ".aiff": "audio/aiff", - ".aim": "application/x-aim", - ".aip": "text/x-audiosoft-intra", - ".alz": "application/x-alz-compressed", - ".ani": "application/x-navi-animation", - ".aos": "application/x-nokia-9000-communicator-add-on-software", - ".aps": "application/mime", - ".apk": "application/vnd.android.package-archive", - ".arc": "application/x-arc-compressed", - ".arj": "application/arj", - ".art": "image/x-jg", - ".asf": "video/x-ms-asf", - ".asm": "text/x-asm", - ".asp": "text/asp", - ".asx": "application/x-mplayer2", - ".au": "audio/basic", - ".avi": "video/x-msvideo", - ".avs": "video/avs-video", - ".bcpio": "application/x-bcpio", - ".bin": "application/mac-binary", - ".bmp": "image/bmp", - ".boo": "application/book", - ".book": "application/book", - ".boz": "application/x-bzip2", - ".bsh": "application/x-bsh", - ".bz2": "application/x-bzip2", - ".bz": "application/x-bzip", - ".c++": "text/plain", - ".c": "text/x-c", - ".cab": "application/vnd.ms-cab-compressed", - ".cat": "application/vndms-pkiseccat", - ".cc": "text/x-c", - ".ccad": "application/clariscad", - ".cco": "application/x-cocoa", - ".cdf": "application/cdf", - ".cer": "application/pkix-cert", - ".cha": "application/x-chat", - ".chat": "application/x-chat", - ".chrt": "application/vnd.kde.kchart", - ".class": "application/java", - ".com": "text/plain", - ".conf": "text/plain", - ".cpio": "application/x-cpio", - ".cpp": "text/x-c", - ".cpt": "application/mac-compactpro", - ".crl": "application/pkcs-crl", - ".crt": "application/pkix-cert", - ".crx": "application/x-chrome-extension", - ".csh": "text/x-scriptcsh", - ".css": "text/css", - ".csv": "text/csv", - ".cxx": "text/plain", - ".dar": "application/x-dar", - ".dcr": "application/x-director", - ".deb": "application/x-debian-package", - ".deepv": "application/x-deepv", - ".def": "text/plain", - ".der": "application/x-x509-ca-cert", - ".dif": "video/x-dv", - ".dir": "application/x-director", - ".divx": "video/divx", - ".dl": "video/dl", - ".dmg": "application/x-apple-diskimage", - ".doc": "application/msword", - ".dot": "application/msword", - ".dp": "application/commonground", - ".drw": "application/drafting", - ".dump": "application/octet-stream", - ".dv": "video/x-dv", - ".dvi": "application/x-dvi", - ".dwf": "drawing/x-dwf=(old)", - ".dwg": "application/acad", - ".dxf": "application/dxf", - ".dxr": "application/x-director", - ".el": "text/x-scriptelisp", - ".elc": "application/x-bytecodeelisp=(compiled=elisp)", - ".eml": "message/rfc822", - ".env": "application/x-envoy", - ".eps": "application/postscript", - ".es": "application/x-esrehber", - ".etx": "text/x-setext", - ".evy": "application/envoy", - ".exe": "application/octet-stream", - ".f77": "text/x-fortran", - ".f90": "text/x-fortran", - ".f": "text/x-fortran", - ".fdf": "application/vndfdf", - ".fif": "application/fractals", - ".fli": "video/fli", - ".flo": "image/florian", - ".flv": "video/x-flv", - ".flx": "text/vndfmiflexstor", - ".fmf": "video/x-atomic3d-feature", - ".for": "text/x-fortran", - ".fpx": "image/vndfpx", - ".frl": "application/freeloader", - ".funk": "audio/make", - ".g3": "image/g3fax", - ".g": "text/plain", - ".gif": "image/gif", - ".gl": "video/gl", - ".gsd": "audio/x-gsm", - ".gsm": "audio/x-gsm", - ".gsp": "application/x-gsp", - ".gss": "application/x-gss", - ".gtar": "application/x-gtar", - ".gz": "application/x-compressed", - ".gzip": "application/x-gzip", - ".h": "text/x-h", - ".hdf": "application/x-hdf", - ".help": "application/x-helpfile", - ".hgl": "application/vndhp-hpgl", - ".hh": "text/x-h", - ".hlb": "text/x-script", - ".hlp": "application/hlp", - ".hpg": "application/vndhp-hpgl", - ".hpgl": "application/vndhp-hpgl", - ".hqx": "application/binhex", - ".hta": "application/hta", - ".htc": "text/x-component", - ".htm": "text/html", - ".html": "text/html", - ".htmls": "text/html", - ".htt": "text/webviewhtml", - ".htx": "text/html", - ".ice": "x-conference/x-cooltalk", - ".ico": "image/x-icon", - ".ics": "text/calendar", - ".icz": "text/calendar", - ".idc": "text/plain", - ".ief": "image/ief", - ".iefs": "image/ief", - ".iges": "application/iges", - ".igs": "application/iges", - ".ima": "application/x-ima", - ".imap": "application/x-httpd-imap", - ".inf": "application/inf", - ".ins": "application/x-internett-signup", - ".ip": "application/x-ip2", - ".isu": "video/x-isvideo", - ".it": "audio/it", - ".iv": "application/x-inventor", - ".ivr": "i-world/i-vrml", - ".ivy": "application/x-livescreen", - ".jam": "audio/x-jam", - ".jav": "text/x-java-source", - ".java": "text/x-java-source", - ".jcm": "application/x-java-commerce", - ".jfif-tbnl": "image/jpeg", - ".jfif": "image/jpeg", - ".jnlp": "application/x-java-jnlp-file", - ".jpe": "image/jpeg", - ".jpeg": "image/jpeg", - ".jpg": "image/jpeg", - ".jps": "image/x-jps", - ".js": "application/javascript", - ".json": "application/json", - ".jut": "image/jutvision", - ".kar": "audio/midi", - ".karbon": "application/vnd.kde.karbon", - ".kfo": "application/vnd.kde.kformula", - ".flw": "application/vnd.kde.kivio", - ".kml": "application/vnd.google-earth.kml+xml", - ".kmz": "application/vnd.google-earth.kmz", - ".kon": "application/vnd.kde.kontour", - ".kpr": "application/vnd.kde.kpresenter", - ".kpt": "application/vnd.kde.kpresenter", - ".ksp": "application/vnd.kde.kspread", - ".kwd": "application/vnd.kde.kword", - ".kwt": "application/vnd.kde.kword", - ".ksh": "text/x-scriptksh", - ".la": "audio/nspaudio", - ".lam": "audio/x-liveaudio", - ".latex": "application/x-latex", - ".lha": "application/lha", - ".lhx": "application/octet-stream", - ".list": "text/plain", - ".lma": "audio/nspaudio", - ".log": "text/plain", - ".lsp": "text/x-scriptlisp", - ".lst": "text/plain", - ".lsx": "text/x-la-asf", - ".ltx": "application/x-latex", - ".lzh": "application/octet-stream", - ".lzx": "application/lzx", - ".m1v": "video/mpeg", - ".m2a": "audio/mpeg", - ".m2v": "video/mpeg", - ".m3u": "audio/x-mpegurl", - ".m": "text/x-m", - ".man": "application/x-troff-man", - ".manifest": "text/cache-manifest", - ".map": "application/x-navimap", - ".mar": "text/plain", - ".mbd": "application/mbedlet", - ".mc$": "application/x-magic-cap-package-10", - ".mcd": "application/mcad", - ".mcf": "text/mcf", - ".mcp": "application/netmc", - ".me": "application/x-troff-me", - ".mht": "message/rfc822", - ".mhtml": "message/rfc822", - ".mid": "application/x-midi", - ".midi": "application/x-midi", - ".mif": "application/x-frame", - ".mime": "message/rfc822", - ".mjf": "audio/x-vndaudioexplosionmjuicemediafile", - ".mjpg": "video/x-motion-jpeg", - ".mm": "application/base64", - ".mme": "application/base64", - ".mod": "audio/mod", - ".moov": "video/quicktime", - ".mov": "video/quicktime", - ".movie": "video/x-sgi-movie", - ".mp2": "audio/mpeg", - ".mp3": "audio/mpeg3", - ".mp4": "video/mp4", - ".mpa": "audio/mpeg", - ".mpc": "application/x-project", - ".mpe": "video/mpeg", - ".mpeg": "video/mpeg", - ".mpg": "video/mpeg", - ".mpga": "audio/mpeg", - ".mpp": "application/vndms-project", - ".mpt": "application/x-project", - ".mpv": "application/x-project", - ".mpx": "application/x-project", - ".mrc": "application/marc", - ".ms": "application/x-troff-ms", - ".mv": "video/x-sgi-movie", - ".my": "audio/make", - ".mzz": "application/x-vndaudioexplosionmzz", - ".nap": "image/naplps", - ".naplps": "image/naplps", - ".nc": "application/x-netcdf", - ".ncm": "application/vndnokiaconfiguration-message", - ".nif": "image/x-niff", - ".niff": "image/x-niff", - ".nix": "application/x-mix-transfer", - ".nsc": "application/x-conference", - ".nvd": "application/x-navidoc", - ".o": "application/octet-stream", - ".oda": "application/oda", - ".odb": "application/vnd.oasis.opendocument.database", - ".odc": "application/vnd.oasis.opendocument.chart", - ".odf": "application/vnd.oasis.opendocument.formula", - ".odg": "application/vnd.oasis.opendocument.graphics", - ".odi": "application/vnd.oasis.opendocument.image", - ".odm": "application/vnd.oasis.opendocument.text-master", - ".odp": "application/vnd.oasis.opendocument.presentation", - ".ods": "application/vnd.oasis.opendocument.spreadsheet", - ".odt": "application/vnd.oasis.opendocument.text", - ".oga": "audio/ogg", - ".ogg": "audio/ogg", - ".ogv": "video/ogg", - ".omc": "application/x-omc", - ".omcd": "application/x-omcdatamaker", - ".omcr": "application/x-omcregerator", - ".otc": "application/vnd.oasis.opendocument.chart-template", - ".otf": "application/vnd.oasis.opendocument.formula-template", - ".otg": "application/vnd.oasis.opendocument.graphics-template", - ".oth": "application/vnd.oasis.opendocument.text-web", - ".oti": "application/vnd.oasis.opendocument.image-template", - ".otm": "application/vnd.oasis.opendocument.text-master", - ".otp": "application/vnd.oasis.opendocument.presentation-template", - ".ots": "application/vnd.oasis.opendocument.spreadsheet-template", - ".ott": "application/vnd.oasis.opendocument.text-template", - ".p10": "application/pkcs10", - ".p12": "application/pkcs-12", - ".p7a": "application/x-pkcs7-signature", - ".p7c": "application/pkcs7-mime", - ".p7m": "application/pkcs7-mime", - ".p7r": "application/x-pkcs7-certreqresp", - ".p7s": "application/pkcs7-signature", - ".p": "text/x-pascal", - ".part": "application/pro_eng", - ".pas": "text/pascal", - ".pbm": "image/x-portable-bitmap", - ".pcl": "application/vndhp-pcl", - ".pct": "image/x-pict", - ".pcx": "image/x-pcx", - ".pdb": "chemical/x-pdb", - ".pdf": "application/pdf", - ".pfunk": "audio/make", - ".pgm": "image/x-portable-graymap", - ".pic": "image/pict", - ".pict": "image/pict", - ".pkg": "application/x-newton-compatible-pkg", - ".pko": "application/vndms-pkipko", - ".pl": "text/x-scriptperl", - ".plx": "application/x-pixclscript", - ".pm4": "application/x-pagemaker", - ".pm5": "application/x-pagemaker", - ".pm": "text/x-scriptperl-module", - ".png": "image/png", - ".pnm": "application/x-portable-anymap", - ".pot": "application/mspowerpoint", - ".pov": "model/x-pov", - ".ppa": "application/vndms-powerpoint", - ".ppm": "image/x-portable-pixmap", - ".pps": "application/mspowerpoint", - ".ppt": "application/mspowerpoint", - ".ppz": "application/mspowerpoint", - ".pre": "application/x-freelance", - ".prt": "application/pro_eng", - ".ps": "application/postscript", - ".psd": "application/octet-stream", - ".pvu": "paleovu/x-pv", - ".pwz": "application/vndms-powerpoint", - ".py": "text/x-scriptphyton", - ".pyc": "application/x-bytecodepython", - ".qcp": "audio/vndqcelp", - ".qd3": "x-world/x-3dmf", - ".qd3d": "x-world/x-3dmf", - ".qif": "image/x-quicktime", - ".qt": "video/quicktime", - ".qtc": "video/x-qtc", - ".qti": "image/x-quicktime", - ".qtif": "image/x-quicktime", - ".ra": "audio/x-pn-realaudio", - ".ram": "audio/x-pn-realaudio", - ".rar": "application/x-rar-compressed", - ".ras": "application/x-cmu-raster", - ".rast": "image/cmu-raster", - ".rexx": "text/x-scriptrexx", - ".rf": "image/vndrn-realflash", - ".rgb": "image/x-rgb", - ".rm": "application/vndrn-realmedia", - ".rmi": "audio/mid", - ".rmm": "audio/x-pn-realaudio", - ".rmp": "audio/x-pn-realaudio", - ".rng": "application/ringing-tones", - ".rnx": "application/vndrn-realplayer", - ".roff": "application/x-troff", - ".rp": "image/vndrn-realpix", - ".rpm": "audio/x-pn-realaudio-plugin", - ".rt": "text/vndrn-realtext", - ".rtf": "text/richtext", - ".rtx": "text/richtext", - ".rv": "video/vndrn-realvideo", - ".s": "text/x-asm", - ".s3m": "audio/s3m", - ".s7z": "application/x-7z-compressed", - ".saveme": "application/octet-stream", - ".sbk": "application/x-tbook", - ".scm": "text/x-scriptscheme", - ".sdml": "text/plain", - ".sdp": "application/sdp", - ".sdr": "application/sounder", - ".sea": "application/sea", - ".set": "application/set", - ".sgm": "text/x-sgml", - ".sgml": "text/x-sgml", - ".sh": "text/x-scriptsh", - ".shar": "application/x-bsh", - ".shtml": "text/x-server-parsed-html", - ".sid": "audio/x-psid", - ".skd": "application/x-koan", - ".skm": "application/x-koan", - ".skp": "application/x-koan", - ".skt": "application/x-koan", - ".sit": "application/x-stuffit", - ".sitx": "application/x-stuffitx", - ".sl": "application/x-seelogo", - ".smi": "application/smil", - ".smil": "application/smil", - ".snd": "audio/basic", - ".sol": "application/solids", - ".spc": "text/x-speech", - ".spl": "application/futuresplash", - ".spr": "application/x-sprite", - ".sprite": "application/x-sprite", - ".spx": "audio/ogg", - ".src": "application/x-wais-source", - ".ssi": "text/x-server-parsed-html", - ".ssm": "application/streamingmedia", - ".sst": "application/vndms-pkicertstore", - ".step": "application/step", - ".stl": "application/sla", - ".stp": "application/step", - ".sv4cpio": "application/x-sv4cpio", - ".sv4crc": "application/x-sv4crc", - ".svf": "image/vnddwg", - ".svg": "image/svg+xml", - ".svr": "application/x-world", - ".swf": "application/x-shockwave-flash", - ".t": "application/x-troff", - ".talk": "text/x-speech", - ".tar": "application/x-tar", - ".tbk": "application/toolbook", - ".tcl": "text/x-scripttcl", - ".tcsh": "text/x-scripttcsh", - ".tex": "application/x-tex", - ".texi": "application/x-texinfo", - ".texinfo": "application/x-texinfo", - ".text": "text/plain", - ".tgz": "application/gnutar", - ".tif": "image/tiff", - ".tiff": "image/tiff", - ".tr": "application/x-troff", - ".tsi": "audio/tsp-audio", - ".tsp": "application/dsptype", - ".tsv": "text/tab-separated-values", - ".turbot": "image/florian", - ".txt": "text/plain", - ".uil": "text/x-uil", - ".uni": "text/uri-list", - ".unis": "text/uri-list", - ".unv": "application/i-deas", - ".uri": "text/uri-list", - ".uris": "text/uri-list", - ".ustar": "application/x-ustar", - ".uu": "text/x-uuencode", - ".uue": "text/x-uuencode", - ".vcd": "application/x-cdlink", - ".vcf": "text/x-vcard", - ".vcard": "text/x-vcard", - ".vcs": "text/x-vcalendar", - ".vda": "application/vda", - ".vdo": "video/vdo", - ".vew": "application/groupwise", - ".viv": "video/vivo", - ".vivo": "video/vivo", - ".vmd": "application/vocaltec-media-desc", - ".vmf": "application/vocaltec-media-file", - ".voc": "audio/voc", - ".vos": "video/vosaic", - ".vox": "audio/voxware", - ".vqe": "audio/x-twinvq-plugin", - ".vqf": "audio/x-twinvq", - ".vql": "audio/x-twinvq-plugin", - ".vrml": "application/x-vrml", - ".vrt": "x-world/x-vrt", - ".vsd": "application/x-visio", - ".vst": "application/x-visio", - ".vsw": "application/x-visio", - ".w60": "application/wordperfect60", - ".w61": "application/wordperfect61", - ".w6w": "application/msword", - ".wav": "audio/wav", - ".wb1": "application/x-qpro", - ".wbmp": "image/vnd.wap.wbmp", - ".web": "application/vndxara", - ".wiz": "application/msword", - ".wk1": "application/x-123", - ".wmf": "windows/metafile", - ".wml": "text/vnd.wap.wml", - ".wmlc": "application/vnd.wap.wmlc", - ".wmls": "text/vnd.wap.wmlscript", - ".wmlsc": "application/vnd.wap.wmlscriptc", - ".word": "application/msword", - ".wp5": "application/wordperfect", - ".wp6": "application/wordperfect", - ".wp": "application/wordperfect", - ".wpd": "application/wordperfect", - ".wq1": "application/x-lotus", - ".wri": "application/mswrite", - ".wrl": "application/x-world", - ".wrz": "model/vrml", - ".wsc": "text/scriplet", - ".wsrc": "application/x-wais-source", - ".wtk": "application/x-wintalk", - ".x-png": "image/png", - ".xbm": "image/x-xbitmap", - ".xdr": "video/x-amt-demorun", - ".xgz": "xgl/drawing", - ".xif": "image/vndxiff", - ".xl": "application/excel", - ".xla": "application/excel", - ".xlb": "application/excel", - ".xlc": "application/excel", - ".xld": "application/excel", - ".xlk": "application/excel", - ".xll": "application/excel", - ".xlm": "application/excel", - ".xls": "application/excel", - ".xlt": "application/excel", - ".xlv": "application/excel", - ".xlw": "application/excel", - ".xm": "audio/xm", - ".xml": "text/xml", - ".xmz": "xgl/movie", - ".xpix": "application/x-vndls-xpix", - ".xpm": "image/x-xpixmap", - ".xsr": "video/x-amt-showrun", - ".xwd": "image/x-xwd", - ".xyz": "chemical/x-pdb", - ".z": "application/x-compress", - ".zip": "application/zip", - ".zoo": "application/octet-stream", - ".zsh": "text/x-scriptzsh", - ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - ".docm": "application/vnd.ms-word.document.macroEnabled.12", - ".dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", - ".dotm": "application/vnd.ms-word.template.macroEnabled.12", - ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - ".xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12", - ".xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", - ".xltm": "application/vnd.ms-excel.template.macroEnabled.12", - ".xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12", - ".xlam": "application/vnd.ms-excel.addin.macroEnabled.12", - ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", - ".pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12", - ".ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", - ".ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", - ".potx": "application/vnd.openxmlformats-officedocument.presentationml.template", - ".potm": "application/vnd.ms-powerpoint.template.macroEnabled.12", - ".ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12", - ".sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", - ".sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12", - ".thmx": "application/vnd.ms-officetheme", - ".onetoc": "application/onenote", - ".onetoc2": "application/onenote", - ".onetmp": "application/onenote", - ".onepkg": "application/onenote", - ".key": "application/x-iwork-keynote-sffkey", - ".kth": "application/x-iwork-keynote-sffkth", - ".nmbtemplate": "application/x-iwork-numbers-sfftemplate", - ".numbers": "application/x-iwork-numbers-sffnumbers", - ".pages": "application/x-iwork-pages-sffpages", - ".template": "application/x-iwork-pages-sfftemplate", - ".xpi": "application/x-xpinstall", - ".oex": "application/x-opera-extension", - ".mustache": "text/html", -} diff --git a/vendor/github.com/astaxie/beego/namespace.go b/vendor/github.com/astaxie/beego/namespace.go deleted file mode 100644 index 4952c9d5..00000000 --- a/vendor/github.com/astaxie/beego/namespace.go +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "net/http" - "strings" - - beecontext "github.com/astaxie/beego/context" -) - -type namespaceCond func(*beecontext.Context) bool - -// LinkNamespace used as link action -type LinkNamespace func(*Namespace) - -// Namespace is store all the info -type Namespace struct { - prefix string - handlers *ControllerRegister -} - -// NewNamespace get new Namespace -func NewNamespace(prefix string, params ...LinkNamespace) *Namespace { - ns := &Namespace{ - prefix: prefix, - handlers: NewControllerRegister(), - } - for _, p := range params { - p(ns) - } - return ns -} - -// Cond set condition function -// if cond return true can run this namespace, else can't -// usage: -// ns.Cond(func (ctx *context.Context) bool{ -// if ctx.Input.Domain() == "api.beego.me" { -// return true -// } -// return false -// }) -// Cond as the first filter -func (n *Namespace) Cond(cond namespaceCond) *Namespace { - fn := func(ctx *beecontext.Context) { - if !cond(ctx) { - exception("405", ctx) - } - } - if v := n.handlers.filters[BeforeRouter]; len(v) > 0 { - mr := new(FilterRouter) - mr.tree = NewTree() - mr.pattern = "*" - mr.filterFunc = fn - mr.tree.AddRouter("*", true) - n.handlers.filters[BeforeRouter] = append([]*FilterRouter{mr}, v...) - } else { - n.handlers.InsertFilter("*", BeforeRouter, fn) - } - return n -} - -// Filter add filter in the Namespace -// action has before & after -// FilterFunc -// usage: -// Filter("before", func (ctx *context.Context){ -// _, ok := ctx.Input.Session("uid").(int) -// if !ok && ctx.Request.RequestURI != "/login" { -// ctx.Redirect(302, "/login") -// } -// }) -func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace { - var a int - if action == "before" { - a = BeforeRouter - } else if action == "after" { - a = FinishRouter - } - for _, f := range filter { - n.handlers.InsertFilter("*", a, f) - } - return n -} - -// Router same as beego.Rourer -// refer: https://godoc.org/github.com/astaxie/beego#Router -func (n *Namespace) Router(rootpath string, c ControllerInterface, mappingMethods ...string) *Namespace { - n.handlers.Add(rootpath, c, mappingMethods...) - return n -} - -// AutoRouter same as beego.AutoRouter -// refer: https://godoc.org/github.com/astaxie/beego#AutoRouter -func (n *Namespace) AutoRouter(c ControllerInterface) *Namespace { - n.handlers.AddAuto(c) - return n -} - -// AutoPrefix same as beego.AutoPrefix -// refer: https://godoc.org/github.com/astaxie/beego#AutoPrefix -func (n *Namespace) AutoPrefix(prefix string, c ControllerInterface) *Namespace { - n.handlers.AddAutoPrefix(prefix, c) - return n -} - -// Get same as beego.Get -// refer: https://godoc.org/github.com/astaxie/beego#Get -func (n *Namespace) Get(rootpath string, f FilterFunc) *Namespace { - n.handlers.Get(rootpath, f) - return n -} - -// Post same as beego.Post -// refer: https://godoc.org/github.com/astaxie/beego#Post -func (n *Namespace) Post(rootpath string, f FilterFunc) *Namespace { - n.handlers.Post(rootpath, f) - return n -} - -// Delete same as beego.Delete -// refer: https://godoc.org/github.com/astaxie/beego#Delete -func (n *Namespace) Delete(rootpath string, f FilterFunc) *Namespace { - n.handlers.Delete(rootpath, f) - return n -} - -// Put same as beego.Put -// refer: https://godoc.org/github.com/astaxie/beego#Put -func (n *Namespace) Put(rootpath string, f FilterFunc) *Namespace { - n.handlers.Put(rootpath, f) - return n -} - -// Head same as beego.Head -// refer: https://godoc.org/github.com/astaxie/beego#Head -func (n *Namespace) Head(rootpath string, f FilterFunc) *Namespace { - n.handlers.Head(rootpath, f) - return n -} - -// Options same as beego.Options -// refer: https://godoc.org/github.com/astaxie/beego#Options -func (n *Namespace) Options(rootpath string, f FilterFunc) *Namespace { - n.handlers.Options(rootpath, f) - return n -} - -// Patch same as beego.Patch -// refer: https://godoc.org/github.com/astaxie/beego#Patch -func (n *Namespace) Patch(rootpath string, f FilterFunc) *Namespace { - n.handlers.Patch(rootpath, f) - return n -} - -// Any same as beego.Any -// refer: https://godoc.org/github.com/astaxie/beego#Any -func (n *Namespace) Any(rootpath string, f FilterFunc) *Namespace { - n.handlers.Any(rootpath, f) - return n -} - -// Handler same as beego.Handler -// refer: https://godoc.org/github.com/astaxie/beego#Handler -func (n *Namespace) Handler(rootpath string, h http.Handler) *Namespace { - n.handlers.Handler(rootpath, h) - return n -} - -// Include add include class -// refer: https://godoc.org/github.com/astaxie/beego#Include -func (n *Namespace) Include(cList ...ControllerInterface) *Namespace { - n.handlers.Include(cList...) - return n -} - -// Namespace add nest Namespace -// usage: -//ns := beego.NewNamespace(“/v1”). -//Namespace( -// beego.NewNamespace("/shop"). -// Get("/:id", func(ctx *context.Context) { -// ctx.Output.Body([]byte("shopinfo")) -// }), -// beego.NewNamespace("/order"). -// Get("/:id", func(ctx *context.Context) { -// ctx.Output.Body([]byte("orderinfo")) -// }), -// beego.NewNamespace("/crm"). -// Get("/:id", func(ctx *context.Context) { -// ctx.Output.Body([]byte("crminfo")) -// }), -//) -func (n *Namespace) Namespace(ns ...*Namespace) *Namespace { - for _, ni := range ns { - for k, v := range ni.handlers.routers { - if _, ok := n.handlers.routers[k]; ok { - addPrefix(v, ni.prefix) - n.handlers.routers[k].AddTree(ni.prefix, v) - } else { - t := NewTree() - t.AddTree(ni.prefix, v) - addPrefix(t, ni.prefix) - n.handlers.routers[k] = t - } - } - if ni.handlers.enableFilter { - for pos, filterList := range ni.handlers.filters { - for _, mr := range filterList { - t := NewTree() - t.AddTree(ni.prefix, mr.tree) - mr.tree = t - n.handlers.insertFilterRouter(pos, mr) - } - } - } - } - return n -} - -// AddNamespace register Namespace into beego.Handler -// support multi Namespace -func AddNamespace(nl ...*Namespace) { - for _, n := range nl { - for k, v := range n.handlers.routers { - if _, ok := BeeApp.Handlers.routers[k]; ok { - addPrefix(v, n.prefix) - BeeApp.Handlers.routers[k].AddTree(n.prefix, v) - } else { - t := NewTree() - t.AddTree(n.prefix, v) - addPrefix(t, n.prefix) - BeeApp.Handlers.routers[k] = t - } - } - if n.handlers.enableFilter { - for pos, filterList := range n.handlers.filters { - for _, mr := range filterList { - t := NewTree() - t.AddTree(n.prefix, mr.tree) - mr.tree = t - BeeApp.Handlers.insertFilterRouter(pos, mr) - } - } - } - } -} - -func addPrefix(t *Tree, prefix string) { - for _, v := range t.fixrouters { - addPrefix(v, prefix) - } - if t.wildcard != nil { - addPrefix(t.wildcard, prefix) - } - for _, l := range t.leaves { - if c, ok := l.runObject.(*ControllerInfo); ok { - if !strings.HasPrefix(c.pattern, prefix) { - c.pattern = prefix + c.pattern - } - } - } -} - -// NSCond is Namespace Condition -func NSCond(cond namespaceCond) LinkNamespace { - return func(ns *Namespace) { - ns.Cond(cond) - } -} - -// NSBefore Namespace BeforeRouter filter -func NSBefore(filterList ...FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Filter("before", filterList...) - } -} - -// NSAfter add Namespace FinishRouter filter -func NSAfter(filterList ...FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Filter("after", filterList...) - } -} - -// NSInclude Namespace Include ControllerInterface -func NSInclude(cList ...ControllerInterface) LinkNamespace { - return func(ns *Namespace) { - ns.Include(cList...) - } -} - -// NSRouter call Namespace Router -func NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string) LinkNamespace { - return func(ns *Namespace) { - ns.Router(rootpath, c, mappingMethods...) - } -} - -// NSGet call Namespace Get -func NSGet(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Get(rootpath, f) - } -} - -// NSPost call Namespace Post -func NSPost(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Post(rootpath, f) - } -} - -// NSHead call Namespace Head -func NSHead(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Head(rootpath, f) - } -} - -// NSPut call Namespace Put -func NSPut(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Put(rootpath, f) - } -} - -// NSDelete call Namespace Delete -func NSDelete(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Delete(rootpath, f) - } -} - -// NSAny call Namespace Any -func NSAny(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Any(rootpath, f) - } -} - -// NSOptions call Namespace Options -func NSOptions(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Options(rootpath, f) - } -} - -// NSPatch call Namespace Patch -func NSPatch(rootpath string, f FilterFunc) LinkNamespace { - return func(ns *Namespace) { - ns.Patch(rootpath, f) - } -} - -// NSAutoRouter call Namespace AutoRouter -func NSAutoRouter(c ControllerInterface) LinkNamespace { - return func(ns *Namespace) { - ns.AutoRouter(c) - } -} - -// NSAutoPrefix call Namespace AutoPrefix -func NSAutoPrefix(prefix string, c ControllerInterface) LinkNamespace { - return func(ns *Namespace) { - ns.AutoPrefix(prefix, c) - } -} - -// NSNamespace add sub Namespace -func NSNamespace(prefix string, params ...LinkNamespace) LinkNamespace { - return func(ns *Namespace) { - n := NewNamespace(prefix, params...) - ns.Namespace(n) - } -} - -// NSHandler add handler -func NSHandler(rootpath string, h http.Handler) LinkNamespace { - return func(ns *Namespace) { - ns.Handler(rootpath, h) - } -} diff --git a/vendor/github.com/astaxie/beego/orm/README.md b/vendor/github.com/astaxie/beego/orm/README.md deleted file mode 100644 index 6e808d2a..00000000 --- a/vendor/github.com/astaxie/beego/orm/README.md +++ /dev/null @@ -1,159 +0,0 @@ -# beego orm - -[![Build Status](https://drone.io/github.com/astaxie/beego/status.png)](https://drone.io/github.com/astaxie/beego/latest) - -A powerful orm framework for go. - -It is heavily influenced by Django ORM, SQLAlchemy. - -**Support Database:** - -* MySQL: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql) -* PostgreSQL: [github.com/lib/pq](https://github.com/lib/pq) -* Sqlite3: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3) - -Passed all test, but need more feedback. - -**Features:** - -* full go type support -* easy for usage, simple CRUD operation -* auto join with relation table -* cross DataBase compatible query -* Raw SQL query / mapper without orm model -* full test keep stable and strong - -more features please read the docs - -**Install:** - - go get github.com/astaxie/beego/orm - -## Changelog - -* 2013-08-19: support table auto create -* 2013-08-13: update test for database types -* 2013-08-13: go type support, such as int8, uint8, byte, rune -* 2013-08-13: date / datetime timezone support very well - -## Quick Start - -#### Simple Usage - -```go -package main - -import ( - "fmt" - "github.com/astaxie/beego/orm" - _ "github.com/go-sql-driver/mysql" // import your used driver -) - -// Model Struct -type User struct { - Id int `orm:"auto"` - Name string `orm:"size(100)"` -} - -func init() { - // register model - orm.RegisterModel(new(User)) - - // set default database - orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30) - - // create table - orm.RunSyncdb("default", false, true) -} - -func main() { - o := orm.NewOrm() - - user := User{Name: "slene"} - - // insert - id, err := o.Insert(&user) - - // update - user.Name = "astaxie" - num, err := o.Update(&user) - - // read one - u := User{Id: user.Id} - err = o.Read(&u) - - // delete - num, err = o.Delete(&u) -} -``` - -#### Next with relation - -```go -type Post struct { - Id int `orm:"auto"` - Title string `orm:"size(100)"` - User *User `orm:"rel(fk)"` -} - -var posts []*Post -qs := o.QueryTable("post") -num, err := qs.Filter("User__Name", "slene").All(&posts) -``` - -#### Use Raw sql - -If you don't like ORM,use Raw SQL to query / mapping without ORM setting - -```go -var maps []Params -num, err := o.Raw("SELECT id FROM user WHERE name = ?", "slene").Values(&maps) -if num > 0 { - fmt.Println(maps[0]["id"]) -} -``` - -#### Transaction - -```go -o.Begin() -... -user := User{Name: "slene"} -id, err := o.Insert(&user) -if err == nil { - o.Commit() -} else { - o.Rollback() -} - -``` - -#### Debug Log Queries - -In development env, you can simple use - -```go -func main() { - orm.Debug = true -... -``` - -enable log queries. - -output include all queries, such as exec / prepare / transaction. - -like this: - -```go -[ORM] - 2013-08-09 13:18:16 - [Queries/default] - [ db.Exec / 0.4ms] - [INSERT INTO `user` (`name`) VALUES (?)] - `slene` -... -``` - -note: not recommend use this in product env. - -## Docs - -more details and examples in docs and test - -[documents](http://beego.me/docs/mvc/model/overview.md) - diff --git a/vendor/github.com/astaxie/beego/orm/cmd.go b/vendor/github.com/astaxie/beego/orm/cmd.go deleted file mode 100644 index 0ff4dc40..00000000 --- a/vendor/github.com/astaxie/beego/orm/cmd.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "flag" - "fmt" - "os" - "strings" -) - -type commander interface { - Parse([]string) - Run() error -} - -var ( - commands = make(map[string]commander) -) - -// print help. -func printHelp(errs ...string) { - content := `orm command usage: - - syncdb - auto create tables - sqlall - print sql of create tables - help - print this help -` - - if len(errs) > 0 { - fmt.Println(errs[0]) - } - fmt.Println(content) - os.Exit(2) -} - -// RunCommand listen for orm command and then run it if command arguments passed. -func RunCommand() { - if len(os.Args) < 2 || os.Args[1] != "orm" { - return - } - - BootStrap() - - args := argString(os.Args[2:]) - name := args.Get(0) - - if name == "help" { - printHelp() - } - - if cmd, ok := commands[name]; ok { - cmd.Parse(os.Args[3:]) - cmd.Run() - os.Exit(0) - } else { - if name == "" { - printHelp() - } else { - printHelp(fmt.Sprintf("unknown command %s", name)) - } - } -} - -// sync database struct command interface. -type commandSyncDb struct { - al *alias - force bool - verbose bool - noInfo bool - rtOnError bool -} - -// parse orm command line arguments. -func (d *commandSyncDb) Parse(args []string) { - var name string - - flagSet := flag.NewFlagSet("orm command: syncdb", flag.ExitOnError) - flagSet.StringVar(&name, "db", "default", "DataBase alias name") - flagSet.BoolVar(&d.force, "force", false, "drop tables before create") - flagSet.BoolVar(&d.verbose, "v", false, "verbose info") - flagSet.Parse(args) - - d.al = getDbAlias(name) -} - -// run orm line command. -func (d *commandSyncDb) Run() error { - var drops []string - if d.force { - drops = getDbDropSQL(d.al) - } - - db := d.al.DB - - if d.force { - for i, mi := range modelCache.allOrdered() { - query := drops[i] - if !d.noInfo { - fmt.Printf("drop table `%s`\n", mi.table) - } - _, err := db.Exec(query) - if d.verbose { - fmt.Printf(" %s\n\n", query) - } - if err != nil { - if d.rtOnError { - return err - } - fmt.Printf(" %s\n", err.Error()) - } - } - } - - sqls, indexes := getDbCreateSQL(d.al) - - tables, err := d.al.DbBaser.GetTables(db) - if err != nil { - if d.rtOnError { - return err - } - fmt.Printf(" %s\n", err.Error()) - } - - for i, mi := range modelCache.allOrdered() { - if tables[mi.table] { - if !d.noInfo { - fmt.Printf("table `%s` already exists, skip\n", mi.table) - } - - var fields []*fieldInfo - columns, err := d.al.DbBaser.GetColumns(db, mi.table) - if err != nil { - if d.rtOnError { - return err - } - fmt.Printf(" %s\n", err.Error()) - } - - for _, fi := range mi.fields.fieldsDB { - if _, ok := columns[fi.column]; !ok { - fields = append(fields, fi) - } - } - - for _, fi := range fields { - query := getColumnAddQuery(d.al, fi) - - if !d.noInfo { - fmt.Printf("add column `%s` for table `%s`\n", fi.fullName, mi.table) - } - - _, err := db.Exec(query) - if d.verbose { - fmt.Printf(" %s\n", query) - } - if err != nil { - if d.rtOnError { - return err - } - fmt.Printf(" %s\n", err.Error()) - } - } - - for _, idx := range indexes[mi.table] { - if !d.al.DbBaser.IndexExists(db, idx.Table, idx.Name) { - if !d.noInfo { - fmt.Printf("create index `%s` for table `%s`\n", idx.Name, idx.Table) - } - - query := idx.SQL - _, err := db.Exec(query) - if d.verbose { - fmt.Printf(" %s\n", query) - } - if err != nil { - if d.rtOnError { - return err - } - fmt.Printf(" %s\n", err.Error()) - } - } - } - - continue - } - - if !d.noInfo { - fmt.Printf("create table `%s` \n", mi.table) - } - - queries := []string{sqls[i]} - for _, idx := range indexes[mi.table] { - queries = append(queries, idx.SQL) - } - - for _, query := range queries { - _, err := db.Exec(query) - if d.verbose { - query = " " + strings.Join(strings.Split(query, "\n"), "\n ") - fmt.Println(query) - } - if err != nil { - if d.rtOnError { - return err - } - fmt.Printf(" %s\n", err.Error()) - } - } - if d.verbose { - fmt.Println("") - } - } - - return nil -} - -// database creation commander interface implement. -type commandSQLAll struct { - al *alias -} - -// parse orm command line arguments. -func (d *commandSQLAll) Parse(args []string) { - var name string - - flagSet := flag.NewFlagSet("orm command: sqlall", flag.ExitOnError) - flagSet.StringVar(&name, "db", "default", "DataBase alias name") - flagSet.Parse(args) - - d.al = getDbAlias(name) -} - -// run orm line command. -func (d *commandSQLAll) Run() error { - sqls, indexes := getDbCreateSQL(d.al) - var all []string - for i, mi := range modelCache.allOrdered() { - queries := []string{sqls[i]} - for _, idx := range indexes[mi.table] { - queries = append(queries, idx.SQL) - } - sql := strings.Join(queries, "\n") - all = append(all, sql) - } - fmt.Println(strings.Join(all, "\n\n")) - - return nil -} - -func init() { - commands["syncdb"] = new(commandSyncDb) - commands["sqlall"] = new(commandSQLAll) -} - -// RunSyncdb run syncdb command line. -// name means table's alias name. default is "default". -// force means run next sql if the current is error. -// verbose means show all info when running command or not. -func RunSyncdb(name string, force bool, verbose bool) error { - BootStrap() - - al := getDbAlias(name) - cmd := new(commandSyncDb) - cmd.al = al - cmd.force = force - cmd.noInfo = !verbose - cmd.verbose = verbose - cmd.rtOnError = true - return cmd.Run() -} diff --git a/vendor/github.com/astaxie/beego/orm/cmd_utils.go b/vendor/github.com/astaxie/beego/orm/cmd_utils.go deleted file mode 100644 index 692a079f..00000000 --- a/vendor/github.com/astaxie/beego/orm/cmd_utils.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "os" - "strings" -) - -type dbIndex struct { - Table string - Name string - SQL string -} - -// create database drop sql. -func getDbDropSQL(al *alias) (sqls []string) { - if len(modelCache.cache) == 0 { - fmt.Println("no Model found, need register your model") - os.Exit(2) - } - - Q := al.DbBaser.TableQuote() - - for _, mi := range modelCache.allOrdered() { - sqls = append(sqls, fmt.Sprintf(`DROP TABLE IF EXISTS %s%s%s`, Q, mi.table, Q)) - } - return sqls -} - -// get database column type string. -func getColumnTyp(al *alias, fi *fieldInfo) (col string) { - T := al.DbBaser.DbTypes() - fieldType := fi.fieldType - fieldSize := fi.size - -checkColumn: - switch fieldType { - case TypeBooleanField: - col = T["bool"] - case TypeVarCharField: - if al.Driver == DRPostgres && fi.toText { - col = T["string-text"] - } else { - col = fmt.Sprintf(T["string"], fieldSize) - } - case TypeCharField: - col = fmt.Sprintf(T["string-char"], fieldSize) - case TypeTextField: - col = T["string-text"] - case TypeTimeField: - col = T["time.Time-clock"] - case TypeDateField: - col = T["time.Time-date"] - case TypeDateTimeField: - col = T["time.Time"] - case TypeBitField: - col = T["int8"] - case TypeSmallIntegerField: - col = T["int16"] - case TypeIntegerField: - col = T["int32"] - case TypeBigIntegerField: - if al.Driver == DRSqlite { - fieldType = TypeIntegerField - goto checkColumn - } - col = T["int64"] - case TypePositiveBitField: - col = T["uint8"] - case TypePositiveSmallIntegerField: - col = T["uint16"] - case TypePositiveIntegerField: - col = T["uint32"] - case TypePositiveBigIntegerField: - col = T["uint64"] - case TypeFloatField: - col = T["float64"] - case TypeDecimalField: - s := T["float64-decimal"] - if !strings.Contains(s, "%d") { - col = s - } else { - col = fmt.Sprintf(s, fi.digits, fi.decimals) - } - case TypeJSONField: - if al.Driver != DRPostgres { - fieldType = TypeVarCharField - goto checkColumn - } - col = T["json"] - case TypeJsonbField: - if al.Driver != DRPostgres { - fieldType = TypeVarCharField - goto checkColumn - } - col = T["jsonb"] - case RelForeignKey, RelOneToOne: - fieldType = fi.relModelInfo.fields.pk.fieldType - fieldSize = fi.relModelInfo.fields.pk.size - goto checkColumn - } - - return -} - -// create alter sql string. -func getColumnAddQuery(al *alias, fi *fieldInfo) string { - Q := al.DbBaser.TableQuote() - typ := getColumnTyp(al, fi) - - if !fi.null { - typ += " " + "NOT NULL" - } - - return fmt.Sprintf("ALTER TABLE %s%s%s ADD COLUMN %s%s%s %s %s", - Q, fi.mi.table, Q, - Q, fi.column, Q, - typ, getColumnDefault(fi), - ) -} - -// create database creation string. -func getDbCreateSQL(al *alias) (sqls []string, tableIndexes map[string][]dbIndex) { - if len(modelCache.cache) == 0 { - fmt.Println("no Model found, need register your model") - os.Exit(2) - } - - Q := al.DbBaser.TableQuote() - T := al.DbBaser.DbTypes() - sep := fmt.Sprintf("%s, %s", Q, Q) - - tableIndexes = make(map[string][]dbIndex) - - for _, mi := range modelCache.allOrdered() { - sql := fmt.Sprintf("-- %s\n", strings.Repeat("-", 50)) - sql += fmt.Sprintf("-- Table Structure for `%s`\n", mi.fullName) - sql += fmt.Sprintf("-- %s\n", strings.Repeat("-", 50)) - - sql += fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s%s%s (\n", Q, mi.table, Q) - - columns := make([]string, 0, len(mi.fields.fieldsDB)) - - sqlIndexes := [][]string{} - - for _, fi := range mi.fields.fieldsDB { - - column := fmt.Sprintf(" %s%s%s ", Q, fi.column, Q) - col := getColumnTyp(al, fi) - - if fi.auto { - switch al.Driver { - case DRSqlite, DRPostgres: - column += T["auto"] - default: - column += col + " " + T["auto"] - } - } else if fi.pk { - column += col + " " + T["pk"] - } else { - column += col - - if !fi.null { - column += " " + "NOT NULL" - } - - //if fi.initial.String() != "" { - // column += " DEFAULT " + fi.initial.String() - //} - - // Append attribute DEFAULT - column += getColumnDefault(fi) - - if fi.unique { - column += " " + "UNIQUE" - } - - if fi.index { - sqlIndexes = append(sqlIndexes, []string{fi.column}) - } - } - - if strings.Contains(column, "%COL%") { - column = strings.Replace(column, "%COL%", fi.column, -1) - } - - if fi.description != "" && al.Driver != DRSqlite { - column += " " + fmt.Sprintf("COMMENT '%s'", fi.description) - } - - columns = append(columns, column) - } - - if mi.model != nil { - allnames := getTableUnique(mi.addrField) - if !mi.manual && len(mi.uniques) > 0 { - allnames = append(allnames, mi.uniques) - } - for _, names := range allnames { - cols := make([]string, 0, len(names)) - for _, name := range names { - if fi, ok := mi.fields.GetByAny(name); ok && fi.dbcol { - cols = append(cols, fi.column) - } else { - panic(fmt.Errorf("cannot found column `%s` when parse UNIQUE in `%s.TableUnique`", name, mi.fullName)) - } - } - column := fmt.Sprintf(" UNIQUE (%s%s%s)", Q, strings.Join(cols, sep), Q) - columns = append(columns, column) - } - } - - sql += strings.Join(columns, ",\n") - sql += "\n)" - - if al.Driver == DRMySQL { - var engine string - if mi.model != nil { - engine = getTableEngine(mi.addrField) - } - if engine == "" { - engine = al.Engine - } - sql += " ENGINE=" + engine - } - - sql += ";" - sqls = append(sqls, sql) - - if mi.model != nil { - for _, names := range getTableIndex(mi.addrField) { - cols := make([]string, 0, len(names)) - for _, name := range names { - if fi, ok := mi.fields.GetByAny(name); ok && fi.dbcol { - cols = append(cols, fi.column) - } else { - panic(fmt.Errorf("cannot found column `%s` when parse INDEX in `%s.TableIndex`", name, mi.fullName)) - } - } - sqlIndexes = append(sqlIndexes, cols) - } - } - - for _, names := range sqlIndexes { - name := mi.table + "_" + strings.Join(names, "_") - cols := strings.Join(names, sep) - sql := fmt.Sprintf("CREATE INDEX %s%s%s ON %s%s%s (%s%s%s);", Q, name, Q, Q, mi.table, Q, Q, cols, Q) - - index := dbIndex{} - index.Table = mi.table - index.Name = name - index.SQL = sql - - tableIndexes[mi.table] = append(tableIndexes[mi.table], index) - } - - } - - return -} - -// Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands -func getColumnDefault(fi *fieldInfo) string { - var ( - v, t, d string - ) - - // Skip default attribute if field is in relations - if fi.rel || fi.reverse { - return v - } - - t = " DEFAULT '%s' " - - // These defaults will be useful if there no config value orm:"default" and NOT NULL is on - switch fi.fieldType { - case TypeTimeField, TypeDateField, TypeDateTimeField, TypeTextField: - return v - - case TypeBitField, TypeSmallIntegerField, TypeIntegerField, - TypeBigIntegerField, TypePositiveBitField, TypePositiveSmallIntegerField, - TypePositiveIntegerField, TypePositiveBigIntegerField, TypeFloatField, - TypeDecimalField: - t = " DEFAULT %s " - d = "0" - case TypeBooleanField: - t = " DEFAULT %s " - d = "FALSE" - case TypeJSONField, TypeJsonbField: - d = "{}" - } - - if fi.colDefault { - if !fi.initial.Exist() { - v = fmt.Sprintf(t, "") - } else { - v = fmt.Sprintf(t, fi.initial.String()) - } - } else { - if !fi.null { - v = fmt.Sprintf(t, d) - } - } - - return v -} diff --git a/vendor/github.com/astaxie/beego/orm/db.go b/vendor/github.com/astaxie/beego/orm/db.go deleted file mode 100644 index 7536a422..00000000 --- a/vendor/github.com/astaxie/beego/orm/db.go +++ /dev/null @@ -1,1903 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "database/sql" - "errors" - "fmt" - "reflect" - "strings" - "time" -) - -const ( - formatTime = "15:04:05" - formatDate = "2006-01-02" - formatDateTime = "2006-01-02 15:04:05" -) - -var ( - // ErrMissPK missing pk error - ErrMissPK = errors.New("missed pk value") -) - -var ( - operators = map[string]bool{ - "exact": true, - "iexact": true, - "strictexact": true, - "contains": true, - "icontains": true, - // "regex": true, - // "iregex": true, - "gt": true, - "gte": true, - "lt": true, - "lte": true, - "eq": true, - "nq": true, - "ne": true, - "startswith": true, - "endswith": true, - "istartswith": true, - "iendswith": true, - "in": true, - "between": true, - // "year": true, - // "month": true, - // "day": true, - // "week_day": true, - "isnull": true, - // "search": true, - } -) - -// an instance of dbBaser interface/ -type dbBase struct { - ins dbBaser -} - -// check dbBase implements dbBaser interface. -var _ dbBaser = new(dbBase) - -// get struct columns values as interface slice. -func (d *dbBase) collectValues(mi *modelInfo, ind reflect.Value, cols []string, skipAuto bool, insert bool, names *[]string, tz *time.Location) (values []interface{}, autoFields []string, err error) { - if names == nil { - ns := make([]string, 0, len(cols)) - names = &ns - } - values = make([]interface{}, 0, len(cols)) - - for _, column := range cols { - var fi *fieldInfo - if fi, _ = mi.fields.GetByAny(column); fi != nil { - column = fi.column - } else { - panic(fmt.Errorf("wrong db field/column name `%s` for model `%s`", column, mi.fullName)) - } - if !fi.dbcol || fi.auto && skipAuto { - continue - } - value, err := d.collectFieldValue(mi, fi, ind, insert, tz) - if err != nil { - return nil, nil, err - } - - // ignore empty value auto field - if insert && fi.auto { - if fi.fieldType&IsPositiveIntegerField > 0 { - if vu, ok := value.(uint64); !ok || vu == 0 { - continue - } - } else { - if vu, ok := value.(int64); !ok || vu == 0 { - continue - } - } - autoFields = append(autoFields, fi.column) - } - - *names, values = append(*names, column), append(values, value) - } - - return -} - -// get one field value in struct column as interface. -func (d *dbBase) collectFieldValue(mi *modelInfo, fi *fieldInfo, ind reflect.Value, insert bool, tz *time.Location) (interface{}, error) { - var value interface{} - if fi.pk { - _, value, _ = getExistPk(mi, ind) - } else { - field := ind.FieldByIndex(fi.fieldIndex) - if fi.isFielder { - f := field.Addr().Interface().(Fielder) - value = f.RawValue() - } else { - switch fi.fieldType { - case TypeBooleanField: - if nb, ok := field.Interface().(sql.NullBool); ok { - value = nil - if nb.Valid { - value = nb.Bool - } - } else if field.Kind() == reflect.Ptr { - if field.IsNil() { - value = nil - } else { - value = field.Elem().Bool() - } - } else { - value = field.Bool() - } - case TypeVarCharField, TypeCharField, TypeTextField, TypeJSONField, TypeJsonbField: - if ns, ok := field.Interface().(sql.NullString); ok { - value = nil - if ns.Valid { - value = ns.String - } - } else if field.Kind() == reflect.Ptr { - if field.IsNil() { - value = nil - } else { - value = field.Elem().String() - } - } else { - value = field.String() - } - case TypeFloatField, TypeDecimalField: - if nf, ok := field.Interface().(sql.NullFloat64); ok { - value = nil - if nf.Valid { - value = nf.Float64 - } - } else if field.Kind() == reflect.Ptr { - if field.IsNil() { - value = nil - } else { - value = field.Elem().Float() - } - } else { - vu := field.Interface() - if _, ok := vu.(float32); ok { - value, _ = StrTo(ToStr(vu)).Float64() - } else { - value = field.Float() - } - } - case TypeTimeField, TypeDateField, TypeDateTimeField: - value = field.Interface() - if t, ok := value.(time.Time); ok { - d.ins.TimeToDB(&t, tz) - if t.IsZero() { - value = nil - } else { - value = t - } - } - default: - switch { - case fi.fieldType&IsPositiveIntegerField > 0: - if field.Kind() == reflect.Ptr { - if field.IsNil() { - value = nil - } else { - value = field.Elem().Uint() - } - } else { - value = field.Uint() - } - case fi.fieldType&IsIntegerField > 0: - if ni, ok := field.Interface().(sql.NullInt64); ok { - value = nil - if ni.Valid { - value = ni.Int64 - } - } else if field.Kind() == reflect.Ptr { - if field.IsNil() { - value = nil - } else { - value = field.Elem().Int() - } - } else { - value = field.Int() - } - case fi.fieldType&IsRelField > 0: - if field.IsNil() { - value = nil - } else { - if _, vu, ok := getExistPk(fi.relModelInfo, reflect.Indirect(field)); ok { - value = vu - } else { - value = nil - } - } - if !fi.null && value == nil { - return nil, fmt.Errorf("field `%s` cannot be NULL", fi.fullName) - } - } - } - } - switch fi.fieldType { - case TypeTimeField, TypeDateField, TypeDateTimeField: - if fi.autoNow || fi.autoNowAdd && insert { - if insert { - if t, ok := value.(time.Time); ok && !t.IsZero() { - break - } - } - tnow := time.Now() - d.ins.TimeToDB(&tnow, tz) - value = tnow - if fi.isFielder { - f := field.Addr().Interface().(Fielder) - f.SetRaw(tnow.In(DefaultTimeLoc)) - } else if field.Kind() == reflect.Ptr { - v := tnow.In(DefaultTimeLoc) - field.Set(reflect.ValueOf(&v)) - } else { - field.Set(reflect.ValueOf(tnow.In(DefaultTimeLoc))) - } - } - case TypeJSONField, TypeJsonbField: - if s, ok := value.(string); (ok && len(s) == 0) || value == nil { - if fi.colDefault && fi.initial.Exist() { - value = fi.initial.String() - } else { - value = nil - } - } - } - } - return value, nil -} - -// create insert sql preparation statement object. -func (d *dbBase) PrepareInsert(q dbQuerier, mi *modelInfo) (stmtQuerier, string, error) { - Q := d.ins.TableQuote() - - dbcols := make([]string, 0, len(mi.fields.dbcols)) - marks := make([]string, 0, len(mi.fields.dbcols)) - for _, fi := range mi.fields.fieldsDB { - if !fi.auto { - dbcols = append(dbcols, fi.column) - marks = append(marks, "?") - } - } - qmarks := strings.Join(marks, ", ") - sep := fmt.Sprintf("%s, %s", Q, Q) - columns := strings.Join(dbcols, sep) - - query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks) - - d.ins.ReplaceMarks(&query) - - d.ins.HasReturningID(mi, &query) - - stmt, err := q.Prepare(query) - return stmt, query, err -} - -// insert struct with prepared statement and given struct reflect value. -func (d *dbBase) InsertStmt(stmt stmtQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location) (int64, error) { - values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, nil, tz) - if err != nil { - return 0, err - } - - if d.ins.HasReturningID(mi, nil) { - row := stmt.QueryRow(values...) - var id int64 - err := row.Scan(&id) - return id, err - } - res, err := stmt.Exec(values...) - if err == nil { - return res.LastInsertId() - } - return 0, err -} - -// query sql ,read records and persist in dbBaser. -func (d *dbBase) Read(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string, isForUpdate bool) error { - var whereCols []string - var args []interface{} - - // if specify cols length > 0, then use it for where condition. - if len(cols) > 0 { - var err error - whereCols = make([]string, 0, len(cols)) - args, _, err = d.collectValues(mi, ind, cols, false, false, &whereCols, tz) - if err != nil { - return err - } - } else { - // default use pk value as where condtion. - pkColumn, pkValue, ok := getExistPk(mi, ind) - if !ok { - return ErrMissPK - } - whereCols = []string{pkColumn} - args = append(args, pkValue) - } - - Q := d.ins.TableQuote() - - sep := fmt.Sprintf("%s, %s", Q, Q) - sels := strings.Join(mi.fields.dbcols, sep) - colsNum := len(mi.fields.dbcols) - - sep = fmt.Sprintf("%s = ? AND %s", Q, Q) - wheres := strings.Join(whereCols, sep) - - forUpdate := "" - if isForUpdate { - forUpdate = "FOR UPDATE" - } - - query := fmt.Sprintf("SELECT %s%s%s FROM %s%s%s WHERE %s%s%s = ? %s", Q, sels, Q, Q, mi.table, Q, Q, wheres, Q, forUpdate) - - refs := make([]interface{}, colsNum) - for i := range refs { - var ref interface{} - refs[i] = &ref - } - - d.ins.ReplaceMarks(&query) - - row := q.QueryRow(query, args...) - if err := row.Scan(refs...); err != nil { - if err == sql.ErrNoRows { - return ErrNoRows - } - return err - } - elm := reflect.New(mi.addrField.Elem().Type()) - mind := reflect.Indirect(elm) - d.setColsValues(mi, &mind, mi.fields.dbcols, refs, tz) - ind.Set(mind) - return nil -} - -// execute insert sql dbQuerier with given struct reflect.Value. -func (d *dbBase) Insert(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location) (int64, error) { - names := make([]string, 0, len(mi.fields.dbcols)) - values, autoFields, err := d.collectValues(mi, ind, mi.fields.dbcols, false, true, &names, tz) - if err != nil { - return 0, err - } - - id, err := d.InsertValue(q, mi, false, names, values) - if err != nil { - return 0, err - } - - if len(autoFields) > 0 { - err = d.ins.setval(q, mi, autoFields) - } - return id, err -} - -// multi-insert sql with given slice struct reflect.Value. -func (d *dbBase) InsertMulti(q dbQuerier, mi *modelInfo, sind reflect.Value, bulk int, tz *time.Location) (int64, error) { - var ( - cnt int64 - nums int - values []interface{} - names []string - ) - - // typ := reflect.Indirect(mi.addrField).Type() - - length, autoFields := sind.Len(), make([]string, 0, 1) - - for i := 1; i <= length; i++ { - - ind := reflect.Indirect(sind.Index(i - 1)) - - // Is this needed ? - // if !ind.Type().AssignableTo(typ) { - // return cnt, ErrArgs - // } - - if i == 1 { - var ( - vus []interface{} - err error - ) - vus, autoFields, err = d.collectValues(mi, ind, mi.fields.dbcols, false, true, &names, tz) - if err != nil { - return cnt, err - } - values = make([]interface{}, bulk*len(vus)) - nums += copy(values, vus) - } else { - vus, _, err := d.collectValues(mi, ind, mi.fields.dbcols, false, true, nil, tz) - if err != nil { - return cnt, err - } - - if len(vus) != len(names) { - return cnt, ErrArgs - } - - nums += copy(values[nums:], vus) - } - - if i > 1 && i%bulk == 0 || length == i { - num, err := d.InsertValue(q, mi, true, names, values[:nums]) - if err != nil { - return cnt, err - } - cnt += num - nums = 0 - } - } - - var err error - if len(autoFields) > 0 { - err = d.ins.setval(q, mi, autoFields) - } - - return cnt, err -} - -// execute insert sql with given struct and given values. -// insert the given values, not the field values in struct. -func (d *dbBase) InsertValue(q dbQuerier, mi *modelInfo, isMulti bool, names []string, values []interface{}) (int64, error) { - Q := d.ins.TableQuote() - - marks := make([]string, len(names)) - for i := range marks { - marks[i] = "?" - } - - sep := fmt.Sprintf("%s, %s", Q, Q) - qmarks := strings.Join(marks, ", ") - columns := strings.Join(names, sep) - - multi := len(values) / len(names) - - if isMulti && multi > 1 { - qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks - } - - query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks) - - d.ins.ReplaceMarks(&query) - - if isMulti || !d.ins.HasReturningID(mi, &query) { - res, err := q.Exec(query, values...) - if err == nil { - if isMulti { - return res.RowsAffected() - } - return res.LastInsertId() - } - return 0, err - } - row := q.QueryRow(query, values...) - var id int64 - err := row.Scan(&id) - return id, err -} - -// InsertOrUpdate a row -// If your primary key or unique column conflict will update -// If no will insert -func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a *alias, args ...string) (int64, error) { - args0 := "" - iouStr := "" - argsMap := map[string]string{} - switch a.Driver { - case DRMySQL: - iouStr = "ON DUPLICATE KEY UPDATE" - case DRPostgres: - if len(args) == 0 { - return 0, fmt.Errorf("`%s` use InsertOrUpdate must have a conflict column", a.DriverName) - } - args0 = strings.ToLower(args[0]) - iouStr = fmt.Sprintf("ON CONFLICT (%s) DO UPDATE SET", args0) - default: - return 0, fmt.Errorf("`%s` nonsupport InsertOrUpdate in beego", a.DriverName) - } - - //Get on the key-value pairs - for _, v := range args { - kv := strings.Split(v, "=") - if len(kv) == 2 { - argsMap[strings.ToLower(kv[0])] = kv[1] - } - } - - isMulti := false - names := make([]string, 0, len(mi.fields.dbcols)-1) - Q := d.ins.TableQuote() - values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ) - - if err != nil { - return 0, err - } - - marks := make([]string, len(names)) - updateValues := make([]interface{}, 0) - updates := make([]string, len(names)) - var conflitValue interface{} - for i, v := range names { - // identifier in database may not be case-sensitive, so quote it - v = fmt.Sprintf("%s%s%s", Q, v, Q) - marks[i] = "?" - valueStr := argsMap[strings.ToLower(v)] - if v == args0 { - conflitValue = values[i] - } - if valueStr != "" { - switch a.Driver { - case DRMySQL: - updates[i] = v + "=" + valueStr - case DRPostgres: - if conflitValue != nil { - //postgres ON CONFLICT DO UPDATE SET can`t use colu=colu+values - updates[i] = fmt.Sprintf("%s=(select %s from %s where %s = ? )", v, valueStr, mi.table, args0) - updateValues = append(updateValues, conflitValue) - } else { - return 0, fmt.Errorf("`%s` must be in front of `%s` in your struct", args0, v) - } - } - } else { - updates[i] = v + "=?" - updateValues = append(updateValues, values[i]) - } - } - - values = append(values, updateValues...) - - sep := fmt.Sprintf("%s, %s", Q, Q) - qmarks := strings.Join(marks, ", ") - qupdates := strings.Join(updates, ", ") - columns := strings.Join(names, sep) - - multi := len(values) / len(names) - - if isMulti { - qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks - } - //conflitValue maybe is a int,can`t use fmt.Sprintf - query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s) %s "+qupdates, Q, mi.table, Q, Q, columns, Q, qmarks, iouStr) - - d.ins.ReplaceMarks(&query) - - if isMulti || !d.ins.HasReturningID(mi, &query) { - res, err := q.Exec(query, values...) - if err == nil { - if isMulti { - return res.RowsAffected() - } - return res.LastInsertId() - } - return 0, err - } - - row := q.QueryRow(query, values...) - var id int64 - err = row.Scan(&id) - if err != nil && err.Error() == `pq: syntax error at or near "ON"` { - err = fmt.Errorf("postgres version must 9.5 or higher") - } - return id, err -} - -// execute update sql dbQuerier with given struct reflect.Value. -func (d *dbBase) Update(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string) (int64, error) { - pkName, pkValue, ok := getExistPk(mi, ind) - if !ok { - return 0, ErrMissPK - } - - var setNames []string - - // if specify cols length is zero, then commit all columns. - if len(cols) == 0 { - cols = mi.fields.dbcols - setNames = make([]string, 0, len(mi.fields.dbcols)-1) - } else { - setNames = make([]string, 0, len(cols)) - } - - setValues, _, err := d.collectValues(mi, ind, cols, true, false, &setNames, tz) - if err != nil { - return 0, err - } - - var findAutoNowAdd, findAutoNow bool - var index int - for i, col := range setNames { - if mi.fields.GetByColumn(col).autoNowAdd { - index = i - findAutoNowAdd = true - } - if mi.fields.GetByColumn(col).autoNow { - findAutoNow = true - } - } - if findAutoNowAdd { - setNames = append(setNames[0:index], setNames[index+1:]...) - setValues = append(setValues[0:index], setValues[index+1:]...) - } - - if !findAutoNow { - for col, info := range mi.fields.columns { - if info.autoNow { - setNames = append(setNames, col) - setValues = append(setValues, time.Now()) - } - } - } - - setValues = append(setValues, pkValue) - - Q := d.ins.TableQuote() - - sep := fmt.Sprintf("%s = ?, %s", Q, Q) - setColumns := strings.Join(setNames, sep) - - query := fmt.Sprintf("UPDATE %s%s%s SET %s%s%s = ? WHERE %s%s%s = ?", Q, mi.table, Q, Q, setColumns, Q, Q, pkName, Q) - - d.ins.ReplaceMarks(&query) - - res, err := q.Exec(query, setValues...) - if err == nil { - return res.RowsAffected() - } - return 0, err -} - -// execute delete sql dbQuerier with given struct reflect.Value. -// delete index is pk. -func (d *dbBase) Delete(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string) (int64, error) { - var whereCols []string - var args []interface{} - // if specify cols length > 0, then use it for where condition. - if len(cols) > 0 { - var err error - whereCols = make([]string, 0, len(cols)) - args, _, err = d.collectValues(mi, ind, cols, false, false, &whereCols, tz) - if err != nil { - return 0, err - } - } else { - // default use pk value as where condtion. - pkColumn, pkValue, ok := getExistPk(mi, ind) - if !ok { - return 0, ErrMissPK - } - whereCols = []string{pkColumn} - args = append(args, pkValue) - } - - Q := d.ins.TableQuote() - - sep := fmt.Sprintf("%s = ? AND %s", Q, Q) - wheres := strings.Join(whereCols, sep) - - query := fmt.Sprintf("DELETE FROM %s%s%s WHERE %s%s%s = ?", Q, mi.table, Q, Q, wheres, Q) - - d.ins.ReplaceMarks(&query) - res, err := q.Exec(query, args...) - if err == nil { - num, err := res.RowsAffected() - if err != nil { - return 0, err - } - if num > 0 { - if mi.fields.pk.auto { - if mi.fields.pk.fieldType&IsPositiveIntegerField > 0 { - ind.FieldByIndex(mi.fields.pk.fieldIndex).SetUint(0) - } else { - ind.FieldByIndex(mi.fields.pk.fieldIndex).SetInt(0) - } - } - err := d.deleteRels(q, mi, args, tz) - if err != nil { - return num, err - } - } - return num, err - } - return 0, err -} - -// update table-related record by querySet. -// need querySet not struct reflect.Value to update related records. -func (d *dbBase) UpdateBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, params Params, tz *time.Location) (int64, error) { - columns := make([]string, 0, len(params)) - values := make([]interface{}, 0, len(params)) - for col, val := range params { - if fi, ok := mi.fields.GetByAny(col); !ok || !fi.dbcol { - panic(fmt.Errorf("wrong field/column name `%s`", col)) - } else { - columns = append(columns, fi.column) - values = append(values, val) - } - } - - if len(columns) == 0 { - panic(fmt.Errorf("update params cannot empty")) - } - - tables := newDbTables(mi, d.ins) - if qs != nil { - tables.parseRelated(qs.related, qs.relDepth) - } - - where, args := tables.getCondSQL(cond, false, tz) - - values = append(values, args...) - - join := tables.getJoinSQL() - - var query, T string - - Q := d.ins.TableQuote() - - if d.ins.SupportUpdateJoin() { - T = "T0." - } - - cols := make([]string, 0, len(columns)) - - for i, v := range columns { - col := fmt.Sprintf("%s%s%s%s", T, Q, v, Q) - if c, ok := values[i].(colValue); ok { - switch c.opt { - case ColAdd: - cols = append(cols, col+" = "+col+" + ?") - case ColMinus: - cols = append(cols, col+" = "+col+" - ?") - case ColMultiply: - cols = append(cols, col+" = "+col+" * ?") - case ColExcept: - cols = append(cols, col+" = "+col+" / ?") - case ColBitAnd: - cols = append(cols, col+" = "+col+" & ?") - case ColBitRShift: - cols = append(cols, col+" = "+col+" >> ?") - case ColBitLShift: - cols = append(cols, col+" = "+col+" << ?") - case ColBitXOR: - cols = append(cols, col+" = "+col+" ^ ?") - case ColBitOr: - cols = append(cols, col+" = "+col+" | ?") - } - values[i] = c.value - } else { - cols = append(cols, col+" = ?") - } - } - - sets := strings.Join(cols, ", ") + " " - - if d.ins.SupportUpdateJoin() { - query = fmt.Sprintf("UPDATE %s%s%s T0 %sSET %s%s", Q, mi.table, Q, join, sets, where) - } else { - supQuery := fmt.Sprintf("SELECT T0.%s%s%s FROM %s%s%s T0 %s%s", Q, mi.fields.pk.column, Q, Q, mi.table, Q, join, where) - query = fmt.Sprintf("UPDATE %s%s%s SET %sWHERE %s%s%s IN ( %s )", Q, mi.table, Q, sets, Q, mi.fields.pk.column, Q, supQuery) - } - - d.ins.ReplaceMarks(&query) - var err error - var res sql.Result - if qs != nil && qs.forContext { - res, err = q.ExecContext(qs.ctx, query, values...) - } else { - res, err = q.Exec(query, values...) - } - if err == nil { - return res.RowsAffected() - } - return 0, err -} - -// delete related records. -// do UpdateBanch or DeleteBanch by condition of tables' relationship. -func (d *dbBase) deleteRels(q dbQuerier, mi *modelInfo, args []interface{}, tz *time.Location) error { - for _, fi := range mi.fields.fieldsReverse { - fi = fi.reverseFieldInfo - switch fi.onDelete { - case odCascade: - cond := NewCondition().And(fmt.Sprintf("%s__in", fi.name), args...) - _, err := d.DeleteBatch(q, nil, fi.mi, cond, tz) - if err != nil { - return err - } - case odSetDefault, odSetNULL: - cond := NewCondition().And(fmt.Sprintf("%s__in", fi.name), args...) - params := Params{fi.column: nil} - if fi.onDelete == odSetDefault { - params[fi.column] = fi.initial.String() - } - _, err := d.UpdateBatch(q, nil, fi.mi, cond, params, tz) - if err != nil { - return err - } - case odDoNothing: - } - } - return nil -} - -// delete table-related records. -func (d *dbBase) DeleteBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, tz *time.Location) (int64, error) { - tables := newDbTables(mi, d.ins) - tables.skipEnd = true - - if qs != nil { - tables.parseRelated(qs.related, qs.relDepth) - } - - if cond == nil || cond.IsEmpty() { - panic(fmt.Errorf("delete operation cannot execute without condition")) - } - - Q := d.ins.TableQuote() - - where, args := tables.getCondSQL(cond, false, tz) - join := tables.getJoinSQL() - - cols := fmt.Sprintf("T0.%s%s%s", Q, mi.fields.pk.column, Q) - query := fmt.Sprintf("SELECT %s FROM %s%s%s T0 %s%s", cols, Q, mi.table, Q, join, where) - - d.ins.ReplaceMarks(&query) - - var rs *sql.Rows - r, err := q.Query(query, args...) - if err != nil { - return 0, err - } - rs = r - defer rs.Close() - - var ref interface{} - args = make([]interface{}, 0) - cnt := 0 - for rs.Next() { - if err := rs.Scan(&ref); err != nil { - return 0, err - } - pkValue, err := d.convertValueFromDB(mi.fields.pk, reflect.ValueOf(ref).Interface(), tz) - if err != nil { - return 0, err - } - args = append(args, pkValue) - cnt++ - } - - if cnt == 0 { - return 0, nil - } - - marks := make([]string, len(args)) - for i := range marks { - marks[i] = "?" - } - sqlIn := fmt.Sprintf("IN (%s)", strings.Join(marks, ", ")) - query = fmt.Sprintf("DELETE FROM %s%s%s WHERE %s%s%s %s", Q, mi.table, Q, Q, mi.fields.pk.column, Q, sqlIn) - - d.ins.ReplaceMarks(&query) - var res sql.Result - if qs != nil && qs.forContext { - res, err = q.ExecContext(qs.ctx, query, args...) - } else { - res, err = q.Exec(query, args...) - } - if err == nil { - num, err := res.RowsAffected() - if err != nil { - return 0, err - } - if num > 0 { - err := d.deleteRels(q, mi, args, tz) - if err != nil { - return num, err - } - } - return num, nil - } - return 0, err -} - -// read related records. -func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, container interface{}, tz *time.Location, cols []string) (int64, error) { - - val := reflect.ValueOf(container) - ind := reflect.Indirect(val) - - errTyp := true - one := true - isPtr := true - - if val.Kind() == reflect.Ptr { - fn := "" - if ind.Kind() == reflect.Slice { - one = false - typ := ind.Type().Elem() - switch typ.Kind() { - case reflect.Ptr: - fn = getFullName(typ.Elem()) - case reflect.Struct: - isPtr = false - fn = getFullName(typ) - } - } else { - fn = getFullName(ind.Type()) - } - errTyp = fn != mi.fullName - } - - if errTyp { - if one { - panic(fmt.Errorf("wrong object type `%s` for rows scan, need *%s", val.Type(), mi.fullName)) - } else { - panic(fmt.Errorf("wrong object type `%s` for rows scan, need *[]*%s or *[]%s", val.Type(), mi.fullName, mi.fullName)) - } - } - - rlimit := qs.limit - offset := qs.offset - - Q := d.ins.TableQuote() - - var tCols []string - if len(cols) > 0 { - hasRel := len(qs.related) > 0 || qs.relDepth > 0 - tCols = make([]string, 0, len(cols)) - var maps map[string]bool - if hasRel { - maps = make(map[string]bool) - } - for _, col := range cols { - if fi, ok := mi.fields.GetByAny(col); ok { - tCols = append(tCols, fi.column) - if hasRel { - maps[fi.column] = true - } - } else { - return 0, fmt.Errorf("wrong field/column name `%s`", col) - } - } - if hasRel { - for _, fi := range mi.fields.fieldsDB { - if fi.fieldType&IsRelField > 0 { - if !maps[fi.column] { - tCols = append(tCols, fi.column) - } - } - } - } - } else { - tCols = mi.fields.dbcols - } - - colsNum := len(tCols) - sep := fmt.Sprintf("%s, T0.%s", Q, Q) - sels := fmt.Sprintf("T0.%s%s%s", Q, strings.Join(tCols, sep), Q) - - tables := newDbTables(mi, d.ins) - tables.parseRelated(qs.related, qs.relDepth) - - where, args := tables.getCondSQL(cond, false, tz) - groupBy := tables.getGroupSQL(qs.groups) - orderBy := tables.getOrderSQL(qs.orders) - limit := tables.getLimitSQL(mi, offset, rlimit) - join := tables.getJoinSQL() - - for _, tbl := range tables.tables { - if tbl.sel { - colsNum += len(tbl.mi.fields.dbcols) - sep := fmt.Sprintf("%s, %s.%s", Q, tbl.index, Q) - sels += fmt.Sprintf(", %s.%s%s%s", tbl.index, Q, strings.Join(tbl.mi.fields.dbcols, sep), Q) - } - } - - sqlSelect := "SELECT" - if qs.distinct { - sqlSelect += " DISTINCT" - } - query := fmt.Sprintf("%s %s FROM %s%s%s T0 %s%s%s%s%s", sqlSelect, sels, Q, mi.table, Q, join, where, groupBy, orderBy, limit) - - if qs.forupdate { - query += " FOR UPDATE" - } - - d.ins.ReplaceMarks(&query) - - var rs *sql.Rows - var err error - if qs != nil && qs.forContext { - rs, err = q.QueryContext(qs.ctx, query, args...) - if err != nil { - return 0, err - } - } else { - rs, err = q.Query(query, args...) - if err != nil { - return 0, err - } - } - - refs := make([]interface{}, colsNum) - for i := range refs { - var ref interface{} - refs[i] = &ref - } - - defer rs.Close() - - slice := ind - - var cnt int64 - for rs.Next() { - if one && cnt == 0 || !one { - if err := rs.Scan(refs...); err != nil { - return 0, err - } - - elm := reflect.New(mi.addrField.Elem().Type()) - mind := reflect.Indirect(elm) - - cacheV := make(map[string]*reflect.Value) - cacheM := make(map[string]*modelInfo) - trefs := refs - - d.setColsValues(mi, &mind, tCols, refs[:len(tCols)], tz) - trefs = refs[len(tCols):] - - for _, tbl := range tables.tables { - // loop selected tables - if tbl.sel { - last := mind - names := "" - mmi := mi - // loop cascade models - for _, name := range tbl.names { - names += name - if val, ok := cacheV[names]; ok { - last = *val - mmi = cacheM[names] - } else { - fi := mmi.fields.GetByName(name) - lastm := mmi - mmi = fi.relModelInfo - field := last - if last.Kind() != reflect.Invalid { - field = reflect.Indirect(last.FieldByIndex(fi.fieldIndex)) - if field.IsValid() { - d.setColsValues(mmi, &field, mmi.fields.dbcols, trefs[:len(mmi.fields.dbcols)], tz) - for _, fi := range mmi.fields.fieldsReverse { - if fi.inModel && fi.reverseFieldInfo.mi == lastm { - if fi.reverseFieldInfo != nil { - f := field.FieldByIndex(fi.fieldIndex) - if f.Kind() == reflect.Ptr { - f.Set(last.Addr()) - } - } - } - } - last = field - } - } - cacheV[names] = &field - cacheM[names] = mmi - } - } - trefs = trefs[len(mmi.fields.dbcols):] - } - } - - if one { - ind.Set(mind) - } else { - if cnt == 0 { - // you can use a empty & caped container list - // orm will not replace it - if ind.Len() != 0 { - // if container is not empty - // create a new one - slice = reflect.New(ind.Type()).Elem() - } - } - - if isPtr { - slice = reflect.Append(slice, mind.Addr()) - } else { - slice = reflect.Append(slice, mind) - } - } - } - cnt++ - } - - if !one { - if cnt > 0 { - ind.Set(slice) - } else { - // when a result is empty and container is nil - // to set a empty container - if ind.IsNil() { - ind.Set(reflect.MakeSlice(ind.Type(), 0, 0)) - } - } - } - - return cnt, nil -} - -// excute count sql and return count result int64. -func (d *dbBase) Count(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, tz *time.Location) (cnt int64, err error) { - tables := newDbTables(mi, d.ins) - tables.parseRelated(qs.related, qs.relDepth) - - where, args := tables.getCondSQL(cond, false, tz) - groupBy := tables.getGroupSQL(qs.groups) - tables.getOrderSQL(qs.orders) - join := tables.getJoinSQL() - - Q := d.ins.TableQuote() - - query := fmt.Sprintf("SELECT COUNT(*) FROM %s%s%s T0 %s%s%s", Q, mi.table, Q, join, where, groupBy) - - if groupBy != "" { - query = fmt.Sprintf("SELECT COUNT(*) FROM (%s) AS T", query) - } - - d.ins.ReplaceMarks(&query) - - var row *sql.Row - if qs != nil && qs.forContext { - row = q.QueryRowContext(qs.ctx, query, args...) - } else { - row = q.QueryRow(query, args...) - } - err = row.Scan(&cnt) - return -} - -// generate sql with replacing operator string placeholders and replaced values. -func (d *dbBase) GenerateOperatorSQL(mi *modelInfo, fi *fieldInfo, operator string, args []interface{}, tz *time.Location) (string, []interface{}) { - var sql string - params := getFlatParams(fi, args, tz) - - if len(params) == 0 { - panic(fmt.Errorf("operator `%s` need at least one args", operator)) - } - arg := params[0] - - switch operator { - case "in": - marks := make([]string, len(params)) - for i := range marks { - marks[i] = "?" - } - sql = fmt.Sprintf("IN (%s)", strings.Join(marks, ", ")) - case "between": - if len(params) != 2 { - panic(fmt.Errorf("operator `%s` need 2 args not %d", operator, len(params))) - } - sql = "BETWEEN ? AND ?" - default: - if len(params) > 1 { - panic(fmt.Errorf("operator `%s` need 1 args not %d", operator, len(params))) - } - sql = d.ins.OperatorSQL(operator) - switch operator { - case "exact", "strictexact": - if arg == nil { - params[0] = "IS NULL" - } - case "iexact", "contains", "icontains", "startswith", "endswith", "istartswith", "iendswith": - param := strings.Replace(ToStr(arg), `%`, `\%`, -1) - switch operator { - case "iexact": - case "contains", "icontains": - param = fmt.Sprintf("%%%s%%", param) - case "startswith", "istartswith": - param = fmt.Sprintf("%s%%", param) - case "endswith", "iendswith": - param = fmt.Sprintf("%%%s", param) - } - params[0] = param - case "isnull": - if b, ok := arg.(bool); ok { - if b { - sql = "IS NULL" - } else { - sql = "IS NOT NULL" - } - params = nil - } else { - panic(fmt.Errorf("operator `%s` need a bool value not `%T`", operator, arg)) - } - } - } - return sql, params -} - -// gernerate sql string with inner function, such as UPPER(text). -func (d *dbBase) GenerateOperatorLeftCol(*fieldInfo, string, *string) { - // default not use -} - -// set values to struct column. -func (d *dbBase) setColsValues(mi *modelInfo, ind *reflect.Value, cols []string, values []interface{}, tz *time.Location) { - for i, column := range cols { - val := reflect.Indirect(reflect.ValueOf(values[i])).Interface() - - fi := mi.fields.GetByColumn(column) - - field := ind.FieldByIndex(fi.fieldIndex) - - value, err := d.convertValueFromDB(fi, val, tz) - if err != nil { - panic(fmt.Errorf("Raw value: `%v` %s", val, err.Error())) - } - - _, err = d.setFieldValue(fi, value, field) - - if err != nil { - panic(fmt.Errorf("Raw value: `%v` %s", val, err.Error())) - } - } -} - -// convert value from database result to value following in field type. -func (d *dbBase) convertValueFromDB(fi *fieldInfo, val interface{}, tz *time.Location) (interface{}, error) { - if val == nil { - return nil, nil - } - - var value interface{} - var tErr error - - var str *StrTo - switch v := val.(type) { - case []byte: - s := StrTo(string(v)) - str = &s - case string: - s := StrTo(v) - str = &s - } - - fieldType := fi.fieldType - -setValue: - switch { - case fieldType == TypeBooleanField: - if str == nil { - switch v := val.(type) { - case int64: - b := v == 1 - value = b - default: - s := StrTo(ToStr(v)) - str = &s - } - } - if str != nil { - b, err := str.Bool() - if err != nil { - tErr = err - goto end - } - value = b - } - case fieldType == TypeVarCharField || fieldType == TypeCharField || fieldType == TypeTextField || fieldType == TypeJSONField || fieldType == TypeJsonbField: - if str == nil { - value = ToStr(val) - } else { - value = str.String() - } - case fieldType == TypeTimeField || fieldType == TypeDateField || fieldType == TypeDateTimeField: - if str == nil { - switch t := val.(type) { - case time.Time: - d.ins.TimeFromDB(&t, tz) - value = t - default: - s := StrTo(ToStr(t)) - str = &s - } - } - if str != nil { - s := str.String() - var ( - t time.Time - err error - ) - if len(s) >= 19 { - s = s[:19] - t, err = time.ParseInLocation(formatDateTime, s, tz) - } else if len(s) >= 10 { - if len(s) > 10 { - s = s[:10] - } - t, err = time.ParseInLocation(formatDate, s, tz) - } else if len(s) >= 8 { - if len(s) > 8 { - s = s[:8] - } - t, err = time.ParseInLocation(formatTime, s, tz) - } - t = t.In(DefaultTimeLoc) - - if err != nil && s != "00:00:00" && s != "0000-00-00" && s != "0000-00-00 00:00:00" { - tErr = err - goto end - } - value = t - } - case fieldType&IsIntegerField > 0: - if str == nil { - s := StrTo(ToStr(val)) - str = &s - } - if str != nil { - var err error - switch fieldType { - case TypeBitField: - _, err = str.Int8() - case TypeSmallIntegerField: - _, err = str.Int16() - case TypeIntegerField: - _, err = str.Int32() - case TypeBigIntegerField: - _, err = str.Int64() - case TypePositiveBitField: - _, err = str.Uint8() - case TypePositiveSmallIntegerField: - _, err = str.Uint16() - case TypePositiveIntegerField: - _, err = str.Uint32() - case TypePositiveBigIntegerField: - _, err = str.Uint64() - } - if err != nil { - tErr = err - goto end - } - if fieldType&IsPositiveIntegerField > 0 { - v, _ := str.Uint64() - value = v - } else { - v, _ := str.Int64() - value = v - } - } - case fieldType == TypeFloatField || fieldType == TypeDecimalField: - if str == nil { - switch v := val.(type) { - case float64: - value = v - default: - s := StrTo(ToStr(v)) - str = &s - } - } - if str != nil { - v, err := str.Float64() - if err != nil { - tErr = err - goto end - } - value = v - } - case fieldType&IsRelField > 0: - fi = fi.relModelInfo.fields.pk - fieldType = fi.fieldType - goto setValue - } - -end: - if tErr != nil { - err := fmt.Errorf("convert to `%s` failed, field: %s err: %s", fi.addrValue.Type(), fi.fullName, tErr) - return nil, err - } - - return value, nil - -} - -// set one value to struct column field. -func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) { - - fieldType := fi.fieldType - isNative := !fi.isFielder - -setValue: - switch { - case fieldType == TypeBooleanField: - if isNative { - if nb, ok := field.Interface().(sql.NullBool); ok { - if value == nil { - nb.Valid = false - } else { - nb.Bool = value.(bool) - nb.Valid = true - } - field.Set(reflect.ValueOf(nb)) - } else if field.Kind() == reflect.Ptr { - if value != nil { - v := value.(bool) - field.Set(reflect.ValueOf(&v)) - } - } else { - if value == nil { - value = false - } - field.SetBool(value.(bool)) - } - } - case fieldType == TypeVarCharField || fieldType == TypeCharField || fieldType == TypeTextField || fieldType == TypeJSONField || fieldType == TypeJsonbField: - if isNative { - if ns, ok := field.Interface().(sql.NullString); ok { - if value == nil { - ns.Valid = false - } else { - ns.String = value.(string) - ns.Valid = true - } - field.Set(reflect.ValueOf(ns)) - } else if field.Kind() == reflect.Ptr { - if value != nil { - v := value.(string) - field.Set(reflect.ValueOf(&v)) - } - } else { - if value == nil { - value = "" - } - field.SetString(value.(string)) - } - } - case fieldType == TypeTimeField || fieldType == TypeDateField || fieldType == TypeDateTimeField: - if isNative { - if value == nil { - value = time.Time{} - } else if field.Kind() == reflect.Ptr { - if value != nil { - v := value.(time.Time) - field.Set(reflect.ValueOf(&v)) - } - } else { - field.Set(reflect.ValueOf(value)) - } - } - case fieldType == TypePositiveBitField && field.Kind() == reflect.Ptr: - if value != nil { - v := uint8(value.(uint64)) - field.Set(reflect.ValueOf(&v)) - } - case fieldType == TypePositiveSmallIntegerField && field.Kind() == reflect.Ptr: - if value != nil { - v := uint16(value.(uint64)) - field.Set(reflect.ValueOf(&v)) - } - case fieldType == TypePositiveIntegerField && field.Kind() == reflect.Ptr: - if value != nil { - if field.Type() == reflect.TypeOf(new(uint)) { - v := uint(value.(uint64)) - field.Set(reflect.ValueOf(&v)) - } else { - v := uint32(value.(uint64)) - field.Set(reflect.ValueOf(&v)) - } - } - case fieldType == TypePositiveBigIntegerField && field.Kind() == reflect.Ptr: - if value != nil { - v := value.(uint64) - field.Set(reflect.ValueOf(&v)) - } - case fieldType == TypeBitField && field.Kind() == reflect.Ptr: - if value != nil { - v := int8(value.(int64)) - field.Set(reflect.ValueOf(&v)) - } - case fieldType == TypeSmallIntegerField && field.Kind() == reflect.Ptr: - if value != nil { - v := int16(value.(int64)) - field.Set(reflect.ValueOf(&v)) - } - case fieldType == TypeIntegerField && field.Kind() == reflect.Ptr: - if value != nil { - if field.Type() == reflect.TypeOf(new(int)) { - v := int(value.(int64)) - field.Set(reflect.ValueOf(&v)) - } else { - v := int32(value.(int64)) - field.Set(reflect.ValueOf(&v)) - } - } - case fieldType == TypeBigIntegerField && field.Kind() == reflect.Ptr: - if value != nil { - v := value.(int64) - field.Set(reflect.ValueOf(&v)) - } - case fieldType&IsIntegerField > 0: - if fieldType&IsPositiveIntegerField > 0 { - if isNative { - if value == nil { - value = uint64(0) - } - field.SetUint(value.(uint64)) - } - } else { - if isNative { - if ni, ok := field.Interface().(sql.NullInt64); ok { - if value == nil { - ni.Valid = false - } else { - ni.Int64 = value.(int64) - ni.Valid = true - } - field.Set(reflect.ValueOf(ni)) - } else { - if value == nil { - value = int64(0) - } - field.SetInt(value.(int64)) - } - } - } - case fieldType == TypeFloatField || fieldType == TypeDecimalField: - if isNative { - if nf, ok := field.Interface().(sql.NullFloat64); ok { - if value == nil { - nf.Valid = false - } else { - nf.Float64 = value.(float64) - nf.Valid = true - } - field.Set(reflect.ValueOf(nf)) - } else if field.Kind() == reflect.Ptr { - if value != nil { - if field.Type() == reflect.TypeOf(new(float32)) { - v := float32(value.(float64)) - field.Set(reflect.ValueOf(&v)) - } else { - v := value.(float64) - field.Set(reflect.ValueOf(&v)) - } - } - } else { - - if value == nil { - value = float64(0) - } - field.SetFloat(value.(float64)) - } - } - case fieldType&IsRelField > 0: - if value != nil { - fieldType = fi.relModelInfo.fields.pk.fieldType - mf := reflect.New(fi.relModelInfo.addrField.Elem().Type()) - field.Set(mf) - f := mf.Elem().FieldByIndex(fi.relModelInfo.fields.pk.fieldIndex) - field = f - goto setValue - } - } - - if !isNative { - fd := field.Addr().Interface().(Fielder) - err := fd.SetRaw(value) - if err != nil { - err = fmt.Errorf("converted value `%v` set to Fielder `%s` failed, err: %s", value, fi.fullName, err) - return nil, err - } - } - - return value, nil -} - -// query sql, read values , save to *[]ParamList. -func (d *dbBase) ReadValues(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, exprs []string, container interface{}, tz *time.Location) (int64, error) { - - var ( - maps []Params - lists []ParamsList - list ParamsList - ) - - typ := 0 - switch v := container.(type) { - case *[]Params: - d := *v - if len(d) == 0 { - maps = d - } - typ = 1 - case *[]ParamsList: - d := *v - if len(d) == 0 { - lists = d - } - typ = 2 - case *ParamsList: - d := *v - if len(d) == 0 { - list = d - } - typ = 3 - default: - panic(fmt.Errorf("unsupport read values type `%T`", container)) - } - - tables := newDbTables(mi, d.ins) - - var ( - cols []string - infos []*fieldInfo - ) - - hasExprs := len(exprs) > 0 - - Q := d.ins.TableQuote() - - if hasExprs { - cols = make([]string, 0, len(exprs)) - infos = make([]*fieldInfo, 0, len(exprs)) - for _, ex := range exprs { - index, name, fi, suc := tables.parseExprs(mi, strings.Split(ex, ExprSep)) - if !suc { - panic(fmt.Errorf("unknown field/column name `%s`", ex)) - } - cols = append(cols, fmt.Sprintf("%s.%s%s%s %s%s%s", index, Q, fi.column, Q, Q, name, Q)) - infos = append(infos, fi) - } - } else { - cols = make([]string, 0, len(mi.fields.dbcols)) - infos = make([]*fieldInfo, 0, len(exprs)) - for _, fi := range mi.fields.fieldsDB { - cols = append(cols, fmt.Sprintf("T0.%s%s%s %s%s%s", Q, fi.column, Q, Q, fi.name, Q)) - infos = append(infos, fi) - } - } - - where, args := tables.getCondSQL(cond, false, tz) - groupBy := tables.getGroupSQL(qs.groups) - orderBy := tables.getOrderSQL(qs.orders) - limit := tables.getLimitSQL(mi, qs.offset, qs.limit) - join := tables.getJoinSQL() - - sels := strings.Join(cols, ", ") - - sqlSelect := "SELECT" - if qs.distinct { - sqlSelect += " DISTINCT" - } - query := fmt.Sprintf("%s %s FROM %s%s%s T0 %s%s%s%s%s", sqlSelect, sels, Q, mi.table, Q, join, where, groupBy, orderBy, limit) - - d.ins.ReplaceMarks(&query) - - rs, err := q.Query(query, args...) - if err != nil { - return 0, err - } - refs := make([]interface{}, len(cols)) - for i := range refs { - var ref interface{} - refs[i] = &ref - } - - defer rs.Close() - - var ( - cnt int64 - columns []string - ) - for rs.Next() { - if cnt == 0 { - cols, err := rs.Columns() - if err != nil { - return 0, err - } - columns = cols - } - - if err := rs.Scan(refs...); err != nil { - return 0, err - } - - switch typ { - case 1: - params := make(Params, len(cols)) - for i, ref := range refs { - fi := infos[i] - - val := reflect.Indirect(reflect.ValueOf(ref)).Interface() - - value, err := d.convertValueFromDB(fi, val, tz) - if err != nil { - panic(fmt.Errorf("db value convert failed `%v` %s", val, err.Error())) - } - - params[columns[i]] = value - } - maps = append(maps, params) - case 2: - params := make(ParamsList, 0, len(cols)) - for i, ref := range refs { - fi := infos[i] - - val := reflect.Indirect(reflect.ValueOf(ref)).Interface() - - value, err := d.convertValueFromDB(fi, val, tz) - if err != nil { - panic(fmt.Errorf("db value convert failed `%v` %s", val, err.Error())) - } - - params = append(params, value) - } - lists = append(lists, params) - case 3: - for i, ref := range refs { - fi := infos[i] - - val := reflect.Indirect(reflect.ValueOf(ref)).Interface() - - value, err := d.convertValueFromDB(fi, val, tz) - if err != nil { - panic(fmt.Errorf("db value convert failed `%v` %s", val, err.Error())) - } - - list = append(list, value) - } - } - - cnt++ - } - - switch v := container.(type) { - case *[]Params: - *v = maps - case *[]ParamsList: - *v = lists - case *ParamsList: - *v = list - } - - return cnt, nil -} - -func (d *dbBase) RowsTo(dbQuerier, *querySet, *modelInfo, *Condition, interface{}, string, string, *time.Location) (int64, error) { - return 0, nil -} - -// flag of update joined record. -func (d *dbBase) SupportUpdateJoin() bool { - return true -} - -func (d *dbBase) MaxLimit() uint64 { - return 18446744073709551615 -} - -// return quote. -func (d *dbBase) TableQuote() string { - return "`" -} - -// replace value placeholder in parametered sql string. -func (d *dbBase) ReplaceMarks(query *string) { - // default use `?` as mark, do nothing -} - -// flag of RETURNING sql. -func (d *dbBase) HasReturningID(*modelInfo, *string) bool { - return false -} - -// sync auto key -func (d *dbBase) setval(db dbQuerier, mi *modelInfo, autoFields []string) error { - return nil -} - -// convert time from db. -func (d *dbBase) TimeFromDB(t *time.Time, tz *time.Location) { - *t = t.In(tz) -} - -// convert time to db. -func (d *dbBase) TimeToDB(t *time.Time, tz *time.Location) { - *t = t.In(tz) -} - -// get database types. -func (d *dbBase) DbTypes() map[string]string { - return nil -} - -// gt all tables. -func (d *dbBase) GetTables(db dbQuerier) (map[string]bool, error) { - tables := make(map[string]bool) - query := d.ins.ShowTablesQuery() - rows, err := db.Query(query) - if err != nil { - return tables, err - } - - defer rows.Close() - - for rows.Next() { - var table string - err := rows.Scan(&table) - if err != nil { - return tables, err - } - if table != "" { - tables[table] = true - } - } - - return tables, nil -} - -// get all cloumns in table. -func (d *dbBase) GetColumns(db dbQuerier, table string) (map[string][3]string, error) { - columns := make(map[string][3]string) - query := d.ins.ShowColumnsQuery(table) - rows, err := db.Query(query) - if err != nil { - return columns, err - } - - defer rows.Close() - - for rows.Next() { - var ( - name string - typ string - null string - ) - err := rows.Scan(&name, &typ, &null) - if err != nil { - return columns, err - } - columns[name] = [3]string{name, typ, null} - } - - return columns, nil -} - -// not implement. -func (d *dbBase) OperatorSQL(operator string) string { - panic(ErrNotImplement) -} - -// not implement. -func (d *dbBase) ShowTablesQuery() string { - panic(ErrNotImplement) -} - -// not implement. -func (d *dbBase) ShowColumnsQuery(table string) string { - panic(ErrNotImplement) -} - -// not implement. -func (d *dbBase) IndexExists(dbQuerier, string, string) bool { - panic(ErrNotImplement) -} diff --git a/vendor/github.com/astaxie/beego/orm/db_alias.go b/vendor/github.com/astaxie/beego/orm/db_alias.go deleted file mode 100644 index 369802a7..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_alias.go +++ /dev/null @@ -1,469 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "context" - "database/sql" - "fmt" - "reflect" - "sync" - "time" - - lru "github.com/hashicorp/golang-lru" -) - -// DriverType database driver constant int. -type DriverType int - -// Enum the Database driver -const ( - _ DriverType = iota // int enum type - DRMySQL // mysql - DRSqlite // sqlite - DROracle // oracle - DRPostgres // pgsql - DRTiDB // TiDB -) - -// database driver string. -type driver string - -// get type constant int of current driver.. -func (d driver) Type() DriverType { - a, _ := dataBaseCache.get(string(d)) - return a.Driver -} - -// get name of current driver -func (d driver) Name() string { - return string(d) -} - -// check driver iis implemented Driver interface or not. -var _ Driver = new(driver) - -var ( - dataBaseCache = &_dbCache{cache: make(map[string]*alias)} - drivers = map[string]DriverType{ - "mysql": DRMySQL, - "postgres": DRPostgres, - "sqlite3": DRSqlite, - "tidb": DRTiDB, - "oracle": DROracle, - "oci8": DROracle, // github.com/mattn/go-oci8 - "ora": DROracle, //https://github.com/rana/ora - } - dbBasers = map[DriverType]dbBaser{ - DRMySQL: newdbBaseMysql(), - DRSqlite: newdbBaseSqlite(), - DROracle: newdbBaseOracle(), - DRPostgres: newdbBasePostgres(), - DRTiDB: newdbBaseTidb(), - } -) - -// database alias cacher. -type _dbCache struct { - mux sync.RWMutex - cache map[string]*alias -} - -// add database alias with original name. -func (ac *_dbCache) add(name string, al *alias) (added bool) { - ac.mux.Lock() - defer ac.mux.Unlock() - if _, ok := ac.cache[name]; !ok { - ac.cache[name] = al - added = true - } - return -} - -// get database alias if cached. -func (ac *_dbCache) get(name string) (al *alias, ok bool) { - ac.mux.RLock() - defer ac.mux.RUnlock() - al, ok = ac.cache[name] - return -} - -// get default alias. -func (ac *_dbCache) getDefault() (al *alias) { - al, _ = ac.get("default") - return -} - -type DB struct { - *sync.RWMutex - DB *sql.DB - stmtDecorators *lru.Cache -} - -func (d *DB) Begin() (*sql.Tx, error) { - return d.DB.Begin() -} - -func (d *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) { - return d.DB.BeginTx(ctx, opts) -} - -//su must call release to release *sql.Stmt after using -func (d *DB) getStmtDecorator(query string) (*stmtDecorator, error) { - d.RLock() - c, ok := d.stmtDecorators.Get(query) - if ok { - c.(*stmtDecorator).acquire() - d.RUnlock() - return c.(*stmtDecorator), nil - } - d.RUnlock() - - d.Lock() - c, ok = d.stmtDecorators.Get(query) - if ok { - c.(*stmtDecorator).acquire() - d.Unlock() - return c.(*stmtDecorator), nil - } - - stmt, err := d.Prepare(query) - if err != nil { - d.Unlock() - return nil, err - } - sd := newStmtDecorator(stmt) - sd.acquire() - d.stmtDecorators.Add(query, sd) - d.Unlock() - - return sd, nil -} - -func (d *DB) Prepare(query string) (*sql.Stmt, error) { - return d.DB.Prepare(query) -} - -func (d *DB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { - return d.DB.PrepareContext(ctx, query) -} - -func (d *DB) Exec(query string, args ...interface{}) (sql.Result, error) { - sd, err := d.getStmtDecorator(query) - if err != nil { - return nil, err - } - stmt := sd.getStmt() - defer sd.release() - return stmt.Exec(args...) -} - -func (d *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { - sd, err := d.getStmtDecorator(query) - if err != nil { - return nil, err - } - stmt := sd.getStmt() - defer sd.release() - return stmt.ExecContext(ctx, args...) -} - -func (d *DB) Query(query string, args ...interface{}) (*sql.Rows, error) { - sd, err := d.getStmtDecorator(query) - if err != nil { - return nil, err - } - stmt := sd.getStmt() - defer sd.release() - return stmt.Query(args...) -} - -func (d *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { - sd, err := d.getStmtDecorator(query) - if err != nil { - return nil, err - } - stmt := sd.getStmt() - defer sd.release() - return stmt.QueryContext(ctx, args...) -} - -func (d *DB) QueryRow(query string, args ...interface{}) *sql.Row { - sd, err := d.getStmtDecorator(query) - if err != nil { - panic(err) - } - stmt := sd.getStmt() - defer sd.release() - return stmt.QueryRow(args...) - -} - -func (d *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row { - sd, err := d.getStmtDecorator(query) - if err != nil { - panic(err) - } - stmt := sd.getStmt() - defer sd.release() - return stmt.QueryRowContext(ctx, args) -} - -type alias struct { - Name string - Driver DriverType - DriverName string - DataSource string - MaxIdleConns int - MaxOpenConns int - DB *DB - DbBaser dbBaser - TZ *time.Location - Engine string -} - -func detectTZ(al *alias) { - // orm timezone system match database - // default use Local - al.TZ = DefaultTimeLoc - - if al.DriverName == "sphinx" { - return - } - - switch al.Driver { - case DRMySQL: - row := al.DB.QueryRow("SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP)") - var tz string - row.Scan(&tz) - if len(tz) >= 8 { - if tz[0] != '-' { - tz = "+" + tz - } - t, err := time.Parse("-07:00:00", tz) - if err == nil { - if t.Location().String() != "" { - al.TZ = t.Location() - } - } else { - DebugLog.Printf("Detect DB timezone: %s %s\n", tz, err.Error()) - } - } - - // get default engine from current database - row = al.DB.QueryRow("SELECT ENGINE, TRANSACTIONS FROM information_schema.engines WHERE SUPPORT = 'DEFAULT'") - var engine string - var tx bool - row.Scan(&engine, &tx) - - if engine != "" { - al.Engine = engine - } else { - al.Engine = "INNODB" - } - - case DRSqlite, DROracle: - al.TZ = time.UTC - - case DRPostgres: - row := al.DB.QueryRow("SELECT current_setting('TIMEZONE')") - var tz string - row.Scan(&tz) - loc, err := time.LoadLocation(tz) - if err == nil { - al.TZ = loc - } else { - DebugLog.Printf("Detect DB timezone: %s %s\n", tz, err.Error()) - } - } -} - -func addAliasWthDB(aliasName, driverName string, db *sql.DB) (*alias, error) { - al := new(alias) - al.Name = aliasName - al.DriverName = driverName - al.DB = &DB{ - RWMutex: new(sync.RWMutex), - DB: db, - stmtDecorators: newStmtDecoratorLruWithEvict(), - } - - if dr, ok := drivers[driverName]; ok { - al.DbBaser = dbBasers[dr] - al.Driver = dr - } else { - return nil, fmt.Errorf("driver name `%s` have not registered", driverName) - } - - err := db.Ping() - if err != nil { - return nil, fmt.Errorf("register db Ping `%s`, %s", aliasName, err.Error()) - } - - if !dataBaseCache.add(aliasName, al) { - return nil, fmt.Errorf("DataBase alias name `%s` already registered, cannot reuse", aliasName) - } - - return al, nil -} - -// AddAliasWthDB add a aliasName for the drivename -func AddAliasWthDB(aliasName, driverName string, db *sql.DB) error { - _, err := addAliasWthDB(aliasName, driverName, db) - return err -} - -// RegisterDataBase Setting the database connect params. Use the database driver self dataSource args. -func RegisterDataBase(aliasName, driverName, dataSource string, params ...int) error { - var ( - err error - db *sql.DB - al *alias - ) - - db, err = sql.Open(driverName, dataSource) - if err != nil { - err = fmt.Errorf("register db `%s`, %s", aliasName, err.Error()) - goto end - } - - al, err = addAliasWthDB(aliasName, driverName, db) - if err != nil { - goto end - } - - al.DataSource = dataSource - - detectTZ(al) - - for i, v := range params { - switch i { - case 0: - SetMaxIdleConns(al.Name, v) - case 1: - SetMaxOpenConns(al.Name, v) - } - } - -end: - if err != nil { - if db != nil { - db.Close() - } - DebugLog.Println(err.Error()) - } - - return err -} - -// RegisterDriver Register a database driver use specify driver name, this can be definition the driver is which database type. -func RegisterDriver(driverName string, typ DriverType) error { - if t, ok := drivers[driverName]; !ok { - drivers[driverName] = typ - } else { - if t != typ { - return fmt.Errorf("driverName `%s` db driver already registered and is other type", driverName) - } - } - return nil -} - -// SetDataBaseTZ Change the database default used timezone -func SetDataBaseTZ(aliasName string, tz *time.Location) error { - if al, ok := dataBaseCache.get(aliasName); ok { - al.TZ = tz - } else { - return fmt.Errorf("DataBase alias name `%s` not registered", aliasName) - } - return nil -} - -// SetMaxIdleConns Change the max idle conns for *sql.DB, use specify database alias name -func SetMaxIdleConns(aliasName string, maxIdleConns int) { - al := getDbAlias(aliasName) - al.MaxIdleConns = maxIdleConns - al.DB.DB.SetMaxIdleConns(maxIdleConns) -} - -// SetMaxOpenConns Change the max open conns for *sql.DB, use specify database alias name -func SetMaxOpenConns(aliasName string, maxOpenConns int) { - al := getDbAlias(aliasName) - al.MaxOpenConns = maxOpenConns - al.DB.DB.SetMaxOpenConns(maxOpenConns) - // for tip go 1.2 - if fun := reflect.ValueOf(al.DB).MethodByName("SetMaxOpenConns"); fun.IsValid() { - fun.Call([]reflect.Value{reflect.ValueOf(maxOpenConns)}) - } -} - -// GetDB Get *sql.DB from registered database by db alias name. -// Use "default" as alias name if you not set. -func GetDB(aliasNames ...string) (*sql.DB, error) { - var name string - if len(aliasNames) > 0 { - name = aliasNames[0] - } else { - name = "default" - } - al, ok := dataBaseCache.get(name) - if ok { - return al.DB.DB, nil - } - return nil, fmt.Errorf("DataBase of alias name `%s` not found", name) -} - -type stmtDecorator struct { - wg sync.WaitGroup - stmt *sql.Stmt -} - -func (s *stmtDecorator) getStmt() *sql.Stmt { - return s.stmt -} - -// acquire will add one -// since this method will be used inside read lock scope, -// so we can not do more things here -// we should think about refactor this -func (s *stmtDecorator) acquire() { - s.wg.Add(1) -} - -func (s *stmtDecorator) release() { - s.wg.Done() -} - -//garbage recycle for stmt -func (s *stmtDecorator) destroy() { - go func() { - s.wg.Wait() - _ = s.stmt.Close() - }() -} - -func newStmtDecorator(sqlStmt *sql.Stmt) *stmtDecorator { - return &stmtDecorator{ - stmt: sqlStmt, - } -} - -func newStmtDecoratorLruWithEvict() *lru.Cache { - // temporarily solution - // we fixed this problem in v2.x - cache, _ := lru.NewWithEvict(50, func(key interface{}, value interface{}) { - value.(*stmtDecorator).destroy() - }) - return cache -} diff --git a/vendor/github.com/astaxie/beego/orm/db_mysql.go b/vendor/github.com/astaxie/beego/orm/db_mysql.go deleted file mode 100644 index 8dd1e755..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_mysql.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "reflect" - "strings" -) - -// mysql operators. -var mysqlOperators = map[string]string{ - "exact": "= ?", - "iexact": "LIKE ?", - "strictexact": "= BINARY ?", - "contains": "LIKE BINARY ?", - "icontains": "LIKE ?", - // "regex": "REGEXP BINARY ?", - // "iregex": "REGEXP ?", - "gt": "> ?", - "gte": ">= ?", - "lt": "< ?", - "lte": "<= ?", - "eq": "= ?", - "ne": "!= ?", - "startswith": "LIKE BINARY ?", - "endswith": "LIKE BINARY ?", - "istartswith": "LIKE ?", - "iendswith": "LIKE ?", -} - -// mysql column field types. -var mysqlTypes = map[string]string{ - "auto": "AUTO_INCREMENT NOT NULL PRIMARY KEY", - "pk": "NOT NULL PRIMARY KEY", - "bool": "bool", - "string": "varchar(%d)", - "string-char": "char(%d)", - "string-text": "longtext", - "time.Time-date": "date", - "time.Time": "datetime", - "int8": "tinyint", - "int16": "smallint", - "int32": "integer", - "int64": "bigint", - "uint8": "tinyint unsigned", - "uint16": "smallint unsigned", - "uint32": "integer unsigned", - "uint64": "bigint unsigned", - "float64": "double precision", - "float64-decimal": "numeric(%d, %d)", -} - -// mysql dbBaser implementation. -type dbBaseMysql struct { - dbBase -} - -var _ dbBaser = new(dbBaseMysql) - -// get mysql operator. -func (d *dbBaseMysql) OperatorSQL(operator string) string { - return mysqlOperators[operator] -} - -// get mysql table field types. -func (d *dbBaseMysql) DbTypes() map[string]string { - return mysqlTypes -} - -// show table sql for mysql. -func (d *dbBaseMysql) ShowTablesQuery() string { - return "SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = DATABASE()" -} - -// show columns sql of table for mysql. -func (d *dbBaseMysql) ShowColumnsQuery(table string) string { - return fmt.Sprintf("SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE FROM information_schema.columns "+ - "WHERE table_schema = DATABASE() AND table_name = '%s'", table) -} - -// execute sql to check index exist. -func (d *dbBaseMysql) IndexExists(db dbQuerier, table string, name string) bool { - row := db.QueryRow("SELECT count(*) FROM information_schema.statistics "+ - "WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?", table, name) - var cnt int - row.Scan(&cnt) - return cnt > 0 -} - -// InsertOrUpdate a row -// If your primary key or unique column conflict will update -// If no will insert -// Add "`" for mysql sql building -func (d *dbBaseMysql) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a *alias, args ...string) (int64, error) { - var iouStr string - argsMap := map[string]string{} - - iouStr = "ON DUPLICATE KEY UPDATE" - - //Get on the key-value pairs - for _, v := range args { - kv := strings.Split(v, "=") - if len(kv) == 2 { - argsMap[strings.ToLower(kv[0])] = kv[1] - } - } - - isMulti := false - names := make([]string, 0, len(mi.fields.dbcols)-1) - Q := d.ins.TableQuote() - values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ) - - if err != nil { - return 0, err - } - - marks := make([]string, len(names)) - updateValues := make([]interface{}, 0) - updates := make([]string, len(names)) - - for i, v := range names { - marks[i] = "?" - valueStr := argsMap[strings.ToLower(v)] - if valueStr != "" { - updates[i] = "`" + v + "`" + "=" + valueStr - } else { - updates[i] = "`" + v + "`" + "=?" - updateValues = append(updateValues, values[i]) - } - } - - values = append(values, updateValues...) - - sep := fmt.Sprintf("%s, %s", Q, Q) - qmarks := strings.Join(marks, ", ") - qupdates := strings.Join(updates, ", ") - columns := strings.Join(names, sep) - - multi := len(values) / len(names) - - if isMulti { - qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks - } - //conflitValue maybe is a int,can`t use fmt.Sprintf - query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s) %s "+qupdates, Q, mi.table, Q, Q, columns, Q, qmarks, iouStr) - - d.ins.ReplaceMarks(&query) - - if isMulti || !d.ins.HasReturningID(mi, &query) { - res, err := q.Exec(query, values...) - if err == nil { - if isMulti { - return res.RowsAffected() - } - return res.LastInsertId() - } - return 0, err - } - - row := q.QueryRow(query, values...) - var id int64 - err = row.Scan(&id) - return id, err -} - -// create new mysql dbBaser. -func newdbBaseMysql() dbBaser { - b := new(dbBaseMysql) - b.ins = b - return b -} diff --git a/vendor/github.com/astaxie/beego/orm/db_oracle.go b/vendor/github.com/astaxie/beego/orm/db_oracle.go deleted file mode 100644 index 5d121f83..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_oracle.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "strings" -) - -// oracle operators. -var oracleOperators = map[string]string{ - "exact": "= ?", - "gt": "> ?", - "gte": ">= ?", - "lt": "< ?", - "lte": "<= ?", - "//iendswith": "LIKE ?", -} - -// oracle column field types. -var oracleTypes = map[string]string{ - "pk": "NOT NULL PRIMARY KEY", - "bool": "bool", - "string": "VARCHAR2(%d)", - "string-char": "CHAR(%d)", - "string-text": "VARCHAR2(%d)", - "time.Time-date": "DATE", - "time.Time": "TIMESTAMP", - "int8": "INTEGER", - "int16": "INTEGER", - "int32": "INTEGER", - "int64": "INTEGER", - "uint8": "INTEGER", - "uint16": "INTEGER", - "uint32": "INTEGER", - "uint64": "INTEGER", - "float64": "NUMBER", - "float64-decimal": "NUMBER(%d, %d)", -} - -// oracle dbBaser -type dbBaseOracle struct { - dbBase -} - -var _ dbBaser = new(dbBaseOracle) - -// create oracle dbBaser. -func newdbBaseOracle() dbBaser { - b := new(dbBaseOracle) - b.ins = b - return b -} - -// OperatorSQL get oracle operator. -func (d *dbBaseOracle) OperatorSQL(operator string) string { - return oracleOperators[operator] -} - -// DbTypes get oracle table field types. -func (d *dbBaseOracle) DbTypes() map[string]string { - return oracleTypes -} - -//ShowTablesQuery show all the tables in database -func (d *dbBaseOracle) ShowTablesQuery() string { - return "SELECT TABLE_NAME FROM USER_TABLES" -} - -// Oracle -func (d *dbBaseOracle) ShowColumnsQuery(table string) string { - return fmt.Sprintf("SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS "+ - "WHERE TABLE_NAME ='%s'", strings.ToUpper(table)) -} - -// check index is exist -func (d *dbBaseOracle) IndexExists(db dbQuerier, table string, name string) bool { - row := db.QueryRow("SELECT COUNT(*) FROM USER_IND_COLUMNS, USER_INDEXES "+ - "WHERE USER_IND_COLUMNS.INDEX_NAME = USER_INDEXES.INDEX_NAME "+ - "AND USER_IND_COLUMNS.TABLE_NAME = ? AND USER_IND_COLUMNS.INDEX_NAME = ?", strings.ToUpper(table), strings.ToUpper(name)) - - var cnt int - row.Scan(&cnt) - return cnt > 0 -} - -// execute insert sql with given struct and given values. -// insert the given values, not the field values in struct. -func (d *dbBaseOracle) InsertValue(q dbQuerier, mi *modelInfo, isMulti bool, names []string, values []interface{}) (int64, error) { - Q := d.ins.TableQuote() - - marks := make([]string, len(names)) - for i := range marks { - marks[i] = ":" + names[i] - } - - sep := fmt.Sprintf("%s, %s", Q, Q) - qmarks := strings.Join(marks, ", ") - columns := strings.Join(names, sep) - - multi := len(values) / len(names) - - if isMulti { - qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks - } - - query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks) - - d.ins.ReplaceMarks(&query) - - if isMulti || !d.ins.HasReturningID(mi, &query) { - res, err := q.Exec(query, values...) - if err == nil { - if isMulti { - return res.RowsAffected() - } - return res.LastInsertId() - } - return 0, err - } - row := q.QueryRow(query, values...) - var id int64 - err := row.Scan(&id) - return id, err -} diff --git a/vendor/github.com/astaxie/beego/orm/db_postgres.go b/vendor/github.com/astaxie/beego/orm/db_postgres.go deleted file mode 100644 index c488fb38..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_postgres.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "strconv" -) - -// postgresql operators. -var postgresOperators = map[string]string{ - "exact": "= ?", - "iexact": "= UPPER(?)", - "contains": "LIKE ?", - "icontains": "LIKE UPPER(?)", - "gt": "> ?", - "gte": ">= ?", - "lt": "< ?", - "lte": "<= ?", - "eq": "= ?", - "ne": "!= ?", - "startswith": "LIKE ?", - "endswith": "LIKE ?", - "istartswith": "LIKE UPPER(?)", - "iendswith": "LIKE UPPER(?)", -} - -// postgresql column field types. -var postgresTypes = map[string]string{ - "auto": "serial NOT NULL PRIMARY KEY", - "pk": "NOT NULL PRIMARY KEY", - "bool": "bool", - "string": "varchar(%d)", - "string-char": "char(%d)", - "string-text": "text", - "time.Time-date": "date", - "time.Time": "timestamp with time zone", - "int8": `smallint CHECK("%COL%" >= -127 AND "%COL%" <= 128)`, - "int16": "smallint", - "int32": "integer", - "int64": "bigint", - "uint8": `smallint CHECK("%COL%" >= 0 AND "%COL%" <= 255)`, - "uint16": `integer CHECK("%COL%" >= 0)`, - "uint32": `bigint CHECK("%COL%" >= 0)`, - "uint64": `bigint CHECK("%COL%" >= 0)`, - "float64": "double precision", - "float64-decimal": "numeric(%d, %d)", - "json": "json", - "jsonb": "jsonb", -} - -// postgresql dbBaser. -type dbBasePostgres struct { - dbBase -} - -var _ dbBaser = new(dbBasePostgres) - -// get postgresql operator. -func (d *dbBasePostgres) OperatorSQL(operator string) string { - return postgresOperators[operator] -} - -// generate functioned sql string, such as contains(text). -func (d *dbBasePostgres) GenerateOperatorLeftCol(fi *fieldInfo, operator string, leftCol *string) { - switch operator { - case "contains", "startswith", "endswith": - *leftCol = fmt.Sprintf("%s::text", *leftCol) - case "iexact", "icontains", "istartswith", "iendswith": - *leftCol = fmt.Sprintf("UPPER(%s::text)", *leftCol) - } -} - -// postgresql unsupports updating joined record. -func (d *dbBasePostgres) SupportUpdateJoin() bool { - return false -} - -func (d *dbBasePostgres) MaxLimit() uint64 { - return 0 -} - -// postgresql quote is ". -func (d *dbBasePostgres) TableQuote() string { - return `"` -} - -// postgresql value placeholder is $n. -// replace default ? to $n. -func (d *dbBasePostgres) ReplaceMarks(query *string) { - q := *query - num := 0 - for _, c := range q { - if c == '?' { - num++ - } - } - if num == 0 { - return - } - data := make([]byte, 0, len(q)+num) - num = 1 - for i := 0; i < len(q); i++ { - c := q[i] - if c == '?' { - data = append(data, '$') - data = append(data, []byte(strconv.Itoa(num))...) - num++ - } else { - data = append(data, c) - } - } - *query = string(data) -} - -// make returning sql support for postgresql. -func (d *dbBasePostgres) HasReturningID(mi *modelInfo, query *string) bool { - fi := mi.fields.pk - if fi.fieldType&IsPositiveIntegerField == 0 && fi.fieldType&IsIntegerField == 0 { - return false - } - - if query != nil { - *query = fmt.Sprintf(`%s RETURNING "%s"`, *query, fi.column) - } - return true -} - -// sync auto key -func (d *dbBasePostgres) setval(db dbQuerier, mi *modelInfo, autoFields []string) error { - if len(autoFields) == 0 { - return nil - } - - Q := d.ins.TableQuote() - for _, name := range autoFields { - query := fmt.Sprintf("SELECT setval(pg_get_serial_sequence('%s', '%s'), (SELECT MAX(%s%s%s) FROM %s%s%s));", - mi.table, name, - Q, name, Q, - Q, mi.table, Q) - if _, err := db.Exec(query); err != nil { - return err - } - } - return nil -} - -// show table sql for postgresql. -func (d *dbBasePostgres) ShowTablesQuery() string { - return "SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')" -} - -// show table columns sql for postgresql. -func (d *dbBasePostgres) ShowColumnsQuery(table string) string { - return fmt.Sprintf("SELECT column_name, data_type, is_nullable FROM information_schema.columns where table_schema NOT IN ('pg_catalog', 'information_schema') and table_name = '%s'", table) -} - -// get column types of postgresql. -func (d *dbBasePostgres) DbTypes() map[string]string { - return postgresTypes -} - -// check index exist in postgresql. -func (d *dbBasePostgres) IndexExists(db dbQuerier, table string, name string) bool { - query := fmt.Sprintf("SELECT COUNT(*) FROM pg_indexes WHERE tablename = '%s' AND indexname = '%s'", table, name) - row := db.QueryRow(query) - var cnt int - row.Scan(&cnt) - return cnt > 0 -} - -// create new postgresql dbBaser. -func newdbBasePostgres() dbBaser { - b := new(dbBasePostgres) - b.ins = b - return b -} diff --git a/vendor/github.com/astaxie/beego/orm/db_sqlite.go b/vendor/github.com/astaxie/beego/orm/db_sqlite.go deleted file mode 100644 index 1d62ee34..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_sqlite.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "database/sql" - "fmt" - "reflect" - "time" -) - -// sqlite operators. -var sqliteOperators = map[string]string{ - "exact": "= ?", - "iexact": "LIKE ? ESCAPE '\\'", - "contains": "LIKE ? ESCAPE '\\'", - "icontains": "LIKE ? ESCAPE '\\'", - "gt": "> ?", - "gte": ">= ?", - "lt": "< ?", - "lte": "<= ?", - "eq": "= ?", - "ne": "!= ?", - "startswith": "LIKE ? ESCAPE '\\'", - "endswith": "LIKE ? ESCAPE '\\'", - "istartswith": "LIKE ? ESCAPE '\\'", - "iendswith": "LIKE ? ESCAPE '\\'", -} - -// sqlite column types. -var sqliteTypes = map[string]string{ - "auto": "integer NOT NULL PRIMARY KEY AUTOINCREMENT", - "pk": "NOT NULL PRIMARY KEY", - "bool": "bool", - "string": "varchar(%d)", - "string-char": "character(%d)", - "string-text": "text", - "time.Time-date": "date", - "time.Time": "datetime", - "int8": "tinyint", - "int16": "smallint", - "int32": "integer", - "int64": "bigint", - "uint8": "tinyint unsigned", - "uint16": "smallint unsigned", - "uint32": "integer unsigned", - "uint64": "bigint unsigned", - "float64": "real", - "float64-decimal": "decimal", -} - -// sqlite dbBaser. -type dbBaseSqlite struct { - dbBase -} - -var _ dbBaser = new(dbBaseSqlite) - -// override base db read for update behavior as SQlite does not support syntax -func (d *dbBaseSqlite) Read(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string, isForUpdate bool) error { - if isForUpdate { - DebugLog.Println("[WARN] SQLite does not support SELECT FOR UPDATE query, isForUpdate param is ignored and always as false to do the work") - } - return d.dbBase.Read(q, mi, ind, tz, cols, false) -} - -// get sqlite operator. -func (d *dbBaseSqlite) OperatorSQL(operator string) string { - return sqliteOperators[operator] -} - -// generate functioned sql for sqlite. -// only support DATE(text). -func (d *dbBaseSqlite) GenerateOperatorLeftCol(fi *fieldInfo, operator string, leftCol *string) { - if fi.fieldType == TypeDateField { - *leftCol = fmt.Sprintf("DATE(%s)", *leftCol) - } -} - -// unable updating joined record in sqlite. -func (d *dbBaseSqlite) SupportUpdateJoin() bool { - return false -} - -// max int in sqlite. -func (d *dbBaseSqlite) MaxLimit() uint64 { - return 9223372036854775807 -} - -// get column types in sqlite. -func (d *dbBaseSqlite) DbTypes() map[string]string { - return sqliteTypes -} - -// get show tables sql in sqlite. -func (d *dbBaseSqlite) ShowTablesQuery() string { - return "SELECT name FROM sqlite_master WHERE type = 'table'" -} - -// get columns in sqlite. -func (d *dbBaseSqlite) GetColumns(db dbQuerier, table string) (map[string][3]string, error) { - query := d.ins.ShowColumnsQuery(table) - rows, err := db.Query(query) - if err != nil { - return nil, err - } - - columns := make(map[string][3]string) - for rows.Next() { - var tmp, name, typ, null sql.NullString - err := rows.Scan(&tmp, &name, &typ, &null, &tmp, &tmp) - if err != nil { - return nil, err - } - columns[name.String] = [3]string{name.String, typ.String, null.String} - } - - return columns, nil -} - -// get show columns sql in sqlite. -func (d *dbBaseSqlite) ShowColumnsQuery(table string) string { - return fmt.Sprintf("pragma table_info('%s')", table) -} - -// check index exist in sqlite. -func (d *dbBaseSqlite) IndexExists(db dbQuerier, table string, name string) bool { - query := fmt.Sprintf("PRAGMA index_list('%s')", table) - rows, err := db.Query(query) - if err != nil { - panic(err) - } - defer rows.Close() - for rows.Next() { - var tmp, index sql.NullString - rows.Scan(&tmp, &index, &tmp, &tmp, &tmp) - if name == index.String { - return true - } - } - return false -} - -// create new sqlite dbBaser. -func newdbBaseSqlite() dbBaser { - b := new(dbBaseSqlite) - b.ins = b - return b -} diff --git a/vendor/github.com/astaxie/beego/orm/db_tables.go b/vendor/github.com/astaxie/beego/orm/db_tables.go deleted file mode 100644 index 4b21a6fc..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_tables.go +++ /dev/null @@ -1,482 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "strings" - "time" -) - -// table info struct. -type dbTable struct { - id int - index string - name string - names []string - sel bool - inner bool - mi *modelInfo - fi *fieldInfo - jtl *dbTable -} - -// tables collection struct, contains some tables. -type dbTables struct { - tablesM map[string]*dbTable - tables []*dbTable - mi *modelInfo - base dbBaser - skipEnd bool -} - -// set table info to collection. -// if not exist, create new. -func (t *dbTables) set(names []string, mi *modelInfo, fi *fieldInfo, inner bool) *dbTable { - name := strings.Join(names, ExprSep) - if j, ok := t.tablesM[name]; ok { - j.name = name - j.mi = mi - j.fi = fi - j.inner = inner - } else { - i := len(t.tables) + 1 - jt := &dbTable{i, fmt.Sprintf("T%d", i), name, names, false, inner, mi, fi, nil} - t.tablesM[name] = jt - t.tables = append(t.tables, jt) - } - return t.tablesM[name] -} - -// add table info to collection. -func (t *dbTables) add(names []string, mi *modelInfo, fi *fieldInfo, inner bool) (*dbTable, bool) { - name := strings.Join(names, ExprSep) - if _, ok := t.tablesM[name]; !ok { - i := len(t.tables) + 1 - jt := &dbTable{i, fmt.Sprintf("T%d", i), name, names, false, inner, mi, fi, nil} - t.tablesM[name] = jt - t.tables = append(t.tables, jt) - return jt, true - } - return t.tablesM[name], false -} - -// get table info in collection. -func (t *dbTables) get(name string) (*dbTable, bool) { - j, ok := t.tablesM[name] - return j, ok -} - -// get related fields info in recursive depth loop. -// loop once, depth decreases one. -func (t *dbTables) loopDepth(depth int, prefix string, fi *fieldInfo, related []string) []string { - if depth < 0 || fi.fieldType == RelManyToMany { - return related - } - - if prefix == "" { - prefix = fi.name - } else { - prefix = prefix + ExprSep + fi.name - } - related = append(related, prefix) - - depth-- - for _, fi := range fi.relModelInfo.fields.fieldsRel { - related = t.loopDepth(depth, prefix, fi, related) - } - - return related -} - -// parse related fields. -func (t *dbTables) parseRelated(rels []string, depth int) { - - relsNum := len(rels) - related := make([]string, relsNum) - copy(related, rels) - - relDepth := depth - - if relsNum != 0 { - relDepth = 0 - } - - relDepth-- - for _, fi := range t.mi.fields.fieldsRel { - related = t.loopDepth(relDepth, "", fi, related) - } - - for i, s := range related { - var ( - exs = strings.Split(s, ExprSep) - names = make([]string, 0, len(exs)) - mmi = t.mi - cancel = true - jtl *dbTable - ) - - inner := true - - for _, ex := range exs { - if fi, ok := mmi.fields.GetByAny(ex); ok && fi.rel && fi.fieldType != RelManyToMany { - names = append(names, fi.name) - mmi = fi.relModelInfo - - if fi.null || t.skipEnd { - inner = false - } - - jt := t.set(names, mmi, fi, inner) - jt.jtl = jtl - - if fi.reverse { - cancel = false - } - - if cancel { - jt.sel = depth > 0 - - if i < relsNum { - jt.sel = true - } - } - - jtl = jt - - } else { - panic(fmt.Errorf("unknown model/table name `%s`", ex)) - } - } - } -} - -// generate join string. -func (t *dbTables) getJoinSQL() (join string) { - Q := t.base.TableQuote() - - for _, jt := range t.tables { - if jt.inner { - join += "INNER JOIN " - } else { - join += "LEFT OUTER JOIN " - } - var ( - table string - t1, t2 string - c1, c2 string - ) - t1 = "T0" - if jt.jtl != nil { - t1 = jt.jtl.index - } - t2 = jt.index - table = jt.mi.table - - switch { - case jt.fi.fieldType == RelManyToMany || jt.fi.fieldType == RelReverseMany || jt.fi.reverse && jt.fi.reverseFieldInfo.fieldType == RelManyToMany: - c1 = jt.fi.mi.fields.pk.column - for _, ffi := range jt.mi.fields.fieldsRel { - if jt.fi.mi == ffi.relModelInfo { - c2 = ffi.column - break - } - } - default: - c1 = jt.fi.column - c2 = jt.fi.relModelInfo.fields.pk.column - - if jt.fi.reverse { - c1 = jt.mi.fields.pk.column - c2 = jt.fi.reverseFieldInfo.column - } - } - - join += fmt.Sprintf("%s%s%s %s ON %s.%s%s%s = %s.%s%s%s ", Q, table, Q, t2, - t2, Q, c2, Q, t1, Q, c1, Q) - } - return -} - -// parse orm model struct field tag expression. -func (t *dbTables) parseExprs(mi *modelInfo, exprs []string) (index, name string, info *fieldInfo, success bool) { - var ( - jtl *dbTable - fi *fieldInfo - fiN *fieldInfo - mmi = mi - ) - - num := len(exprs) - 1 - var names []string - - inner := true - -loopFor: - for i, ex := range exprs { - - var ok, okN bool - - if fiN != nil { - fi = fiN - ok = true - fiN = nil - } - - if i == 0 { - fi, ok = mmi.fields.GetByAny(ex) - } - - _ = okN - - if ok { - - isRel := fi.rel || fi.reverse - - names = append(names, fi.name) - - switch { - case fi.rel: - mmi = fi.relModelInfo - if fi.fieldType == RelManyToMany { - mmi = fi.relThroughModelInfo - } - case fi.reverse: - mmi = fi.reverseFieldInfo.mi - } - - if i < num { - fiN, okN = mmi.fields.GetByAny(exprs[i+1]) - } - - if isRel && (!fi.mi.isThrough || num != i) { - if fi.null || t.skipEnd { - inner = false - } - - if t.skipEnd && okN || !t.skipEnd { - if t.skipEnd && okN && fiN.pk { - goto loopEnd - } - - jt, _ := t.add(names, mmi, fi, inner) - jt.jtl = jtl - jtl = jt - } - - } - - if num != i { - continue - } - - loopEnd: - - if i == 0 || jtl == nil { - index = "T0" - } else { - index = jtl.index - } - - info = fi - - if jtl == nil { - name = fi.name - } else { - name = jtl.name + ExprSep + fi.name - } - - switch { - case fi.rel: - - case fi.reverse: - switch fi.reverseFieldInfo.fieldType { - case RelOneToOne, RelForeignKey: - index = jtl.index - info = fi.reverseFieldInfo.mi.fields.pk - name = info.name - } - } - - break loopFor - - } else { - index = "" - name = "" - info = nil - success = false - return - } - } - - success = index != "" && info != nil - return -} - -// generate condition sql. -func (t *dbTables) getCondSQL(cond *Condition, sub bool, tz *time.Location) (where string, params []interface{}) { - if cond == nil || cond.IsEmpty() { - return - } - - Q := t.base.TableQuote() - - mi := t.mi - - for i, p := range cond.params { - if i > 0 { - if p.isOr { - where += "OR " - } else { - where += "AND " - } - } - if p.isNot { - where += "NOT " - } - if p.isCond { - w, ps := t.getCondSQL(p.cond, true, tz) - if w != "" { - w = fmt.Sprintf("( %s) ", w) - } - where += w - params = append(params, ps...) - } else { - exprs := p.exprs - - num := len(exprs) - 1 - operator := "" - if operators[exprs[num]] { - operator = exprs[num] - exprs = exprs[:num] - } - - index, _, fi, suc := t.parseExprs(mi, exprs) - if !suc { - panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(p.exprs, ExprSep))) - } - - if operator == "" { - operator = "exact" - } - - var operSQL string - var args []interface{} - if p.isRaw { - operSQL = p.sql - } else { - operSQL, args = t.base.GenerateOperatorSQL(mi, fi, operator, p.args, tz) - } - - leftCol := fmt.Sprintf("%s.%s%s%s", index, Q, fi.column, Q) - t.base.GenerateOperatorLeftCol(fi, operator, &leftCol) - - where += fmt.Sprintf("%s %s ", leftCol, operSQL) - params = append(params, args...) - - } - } - - if !sub && where != "" { - where = "WHERE " + where - } - - return -} - -// generate group sql. -func (t *dbTables) getGroupSQL(groups []string) (groupSQL string) { - if len(groups) == 0 { - return - } - - Q := t.base.TableQuote() - - groupSqls := make([]string, 0, len(groups)) - for _, group := range groups { - exprs := strings.Split(group, ExprSep) - - index, _, fi, suc := t.parseExprs(t.mi, exprs) - if !suc { - panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(exprs, ExprSep))) - } - - groupSqls = append(groupSqls, fmt.Sprintf("%s.%s%s%s", index, Q, fi.column, Q)) - } - - groupSQL = fmt.Sprintf("GROUP BY %s ", strings.Join(groupSqls, ", ")) - return -} - -// generate order sql. -func (t *dbTables) getOrderSQL(orders []string) (orderSQL string) { - if len(orders) == 0 { - return - } - - Q := t.base.TableQuote() - - orderSqls := make([]string, 0, len(orders)) - for _, order := range orders { - asc := "ASC" - if order[0] == '-' { - asc = "DESC" - order = order[1:] - } - exprs := strings.Split(order, ExprSep) - - index, _, fi, suc := t.parseExprs(t.mi, exprs) - if !suc { - panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(exprs, ExprSep))) - } - - orderSqls = append(orderSqls, fmt.Sprintf("%s.%s%s%s %s", index, Q, fi.column, Q, asc)) - } - - orderSQL = fmt.Sprintf("ORDER BY %s ", strings.Join(orderSqls, ", ")) - return -} - -// generate limit sql. -func (t *dbTables) getLimitSQL(mi *modelInfo, offset int64, limit int64) (limits string) { - if limit == 0 { - limit = int64(DefaultRowsLimit) - } - if limit < 0 { - // no limit - if offset > 0 { - maxLimit := t.base.MaxLimit() - if maxLimit == 0 { - limits = fmt.Sprintf("OFFSET %d", offset) - } else { - limits = fmt.Sprintf("LIMIT %d OFFSET %d", maxLimit, offset) - } - } - } else if offset <= 0 { - limits = fmt.Sprintf("LIMIT %d", limit) - } else { - limits = fmt.Sprintf("LIMIT %d OFFSET %d", limit, offset) - } - return -} - -// crete new tables collection. -func newDbTables(mi *modelInfo, base dbBaser) *dbTables { - tables := &dbTables{} - tables.tablesM = make(map[string]*dbTable) - tables.mi = mi - tables.base = base - return tables -} diff --git a/vendor/github.com/astaxie/beego/orm/db_tidb.go b/vendor/github.com/astaxie/beego/orm/db_tidb.go deleted file mode 100644 index 6020a488..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_tidb.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2015 TiDB Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" -) - -// mysql dbBaser implementation. -type dbBaseTidb struct { - dbBase -} - -var _ dbBaser = new(dbBaseTidb) - -// get mysql operator. -func (d *dbBaseTidb) OperatorSQL(operator string) string { - return mysqlOperators[operator] -} - -// get mysql table field types. -func (d *dbBaseTidb) DbTypes() map[string]string { - return mysqlTypes -} - -// show table sql for mysql. -func (d *dbBaseTidb) ShowTablesQuery() string { - return "SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = DATABASE()" -} - -// show columns sql of table for mysql. -func (d *dbBaseTidb) ShowColumnsQuery(table string) string { - return fmt.Sprintf("SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE FROM information_schema.columns "+ - "WHERE table_schema = DATABASE() AND table_name = '%s'", table) -} - -// execute sql to check index exist. -func (d *dbBaseTidb) IndexExists(db dbQuerier, table string, name string) bool { - row := db.QueryRow("SELECT count(*) FROM information_schema.statistics "+ - "WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?", table, name) - var cnt int - row.Scan(&cnt) - return cnt > 0 -} - -// create new mysql dbBaser. -func newdbBaseTidb() dbBaser { - b := new(dbBaseTidb) - b.ins = b - return b -} diff --git a/vendor/github.com/astaxie/beego/orm/db_utils.go b/vendor/github.com/astaxie/beego/orm/db_utils.go deleted file mode 100644 index 7ae10ca5..00000000 --- a/vendor/github.com/astaxie/beego/orm/db_utils.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "reflect" - "time" -) - -// get table alias. -func getDbAlias(name string) *alias { - if al, ok := dataBaseCache.get(name); ok { - return al - } - panic(fmt.Errorf("unknown DataBase alias name %s", name)) -} - -// get pk column info. -func getExistPk(mi *modelInfo, ind reflect.Value) (column string, value interface{}, exist bool) { - fi := mi.fields.pk - - v := ind.FieldByIndex(fi.fieldIndex) - if fi.fieldType&IsPositiveIntegerField > 0 { - vu := v.Uint() - exist = vu > 0 - value = vu - } else if fi.fieldType&IsIntegerField > 0 { - vu := v.Int() - exist = true - value = vu - } else if fi.fieldType&IsRelField > 0 { - _, value, exist = getExistPk(fi.relModelInfo, reflect.Indirect(v)) - } else { - vu := v.String() - exist = vu != "" - value = vu - } - - column = fi.column - return -} - -// get fields description as flatted string. -func getFlatParams(fi *fieldInfo, args []interface{}, tz *time.Location) (params []interface{}) { - -outFor: - for _, arg := range args { - val := reflect.ValueOf(arg) - - if arg == nil { - params = append(params, arg) - continue - } - - kind := val.Kind() - if kind == reflect.Ptr { - val = val.Elem() - kind = val.Kind() - arg = val.Interface() - } - - switch kind { - case reflect.String: - v := val.String() - if fi != nil { - if fi.fieldType == TypeTimeField || fi.fieldType == TypeDateField || fi.fieldType == TypeDateTimeField { - var t time.Time - var err error - if len(v) >= 19 { - s := v[:19] - t, err = time.ParseInLocation(formatDateTime, s, DefaultTimeLoc) - } else if len(v) >= 10 { - s := v - if len(v) > 10 { - s = v[:10] - } - t, err = time.ParseInLocation(formatDate, s, tz) - } else { - s := v - if len(s) > 8 { - s = v[:8] - } - t, err = time.ParseInLocation(formatTime, s, tz) - } - if err == nil { - if fi.fieldType == TypeDateField { - v = t.In(tz).Format(formatDate) - } else if fi.fieldType == TypeDateTimeField { - v = t.In(tz).Format(formatDateTime) - } else { - v = t.In(tz).Format(formatTime) - } - } - } - } - arg = v - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - arg = val.Int() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - arg = val.Uint() - case reflect.Float32: - arg, _ = StrTo(ToStr(arg)).Float64() - case reflect.Float64: - arg = val.Float() - case reflect.Bool: - arg = val.Bool() - case reflect.Slice, reflect.Array: - if _, ok := arg.([]byte); ok { - continue outFor - } - - var args []interface{} - for i := 0; i < val.Len(); i++ { - v := val.Index(i) - - var vu interface{} - if v.CanInterface() { - vu = v.Interface() - } - - if vu == nil { - continue - } - - args = append(args, vu) - } - - if len(args) > 0 { - p := getFlatParams(fi, args, tz) - params = append(params, p...) - } - continue outFor - case reflect.Struct: - if v, ok := arg.(time.Time); ok { - if fi != nil && fi.fieldType == TypeDateField { - arg = v.In(tz).Format(formatDate) - } else if fi != nil && fi.fieldType == TypeDateTimeField { - arg = v.In(tz).Format(formatDateTime) - } else if fi != nil && fi.fieldType == TypeTimeField { - arg = v.In(tz).Format(formatTime) - } else { - arg = v.In(tz).Format(formatDateTime) - } - } else { - typ := val.Type() - name := getFullName(typ) - var value interface{} - if mmi, ok := modelCache.getByFullName(name); ok { - if _, vu, exist := getExistPk(mmi, val); exist { - value = vu - } - } - arg = value - - if arg == nil { - panic(fmt.Errorf("need a valid args value, unknown table or value `%s`", name)) - } - } - } - - params = append(params, arg) - } - return -} diff --git a/vendor/github.com/astaxie/beego/orm/models.go b/vendor/github.com/astaxie/beego/orm/models.go deleted file mode 100644 index 4776bcba..00000000 --- a/vendor/github.com/astaxie/beego/orm/models.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "sync" -) - -const ( - odCascade = "cascade" - odSetNULL = "set_null" - odSetDefault = "set_default" - odDoNothing = "do_nothing" - defaultStructTagName = "orm" - defaultStructTagDelim = ";" -) - -var ( - modelCache = &_modelCache{ - cache: make(map[string]*modelInfo), - cacheByFullName: make(map[string]*modelInfo), - } -) - -// model info collection -type _modelCache struct { - sync.RWMutex // only used outsite for bootStrap - orders []string - cache map[string]*modelInfo - cacheByFullName map[string]*modelInfo - done bool -} - -// get all model info -func (mc *_modelCache) all() map[string]*modelInfo { - m := make(map[string]*modelInfo, len(mc.cache)) - for k, v := range mc.cache { - m[k] = v - } - return m -} - -// get ordered model info -func (mc *_modelCache) allOrdered() []*modelInfo { - m := make([]*modelInfo, 0, len(mc.orders)) - for _, table := range mc.orders { - m = append(m, mc.cache[table]) - } - return m -} - -// get model info by table name -func (mc *_modelCache) get(table string) (mi *modelInfo, ok bool) { - mi, ok = mc.cache[table] - return -} - -// get model info by full name -func (mc *_modelCache) getByFullName(name string) (mi *modelInfo, ok bool) { - mi, ok = mc.cacheByFullName[name] - return -} - -// set model info to collection -func (mc *_modelCache) set(table string, mi *modelInfo) *modelInfo { - mii := mc.cache[table] - mc.cache[table] = mi - mc.cacheByFullName[mi.fullName] = mi - if mii == nil { - mc.orders = append(mc.orders, table) - } - return mii -} - -// clean all model info. -func (mc *_modelCache) clean() { - mc.orders = make([]string, 0) - mc.cache = make(map[string]*modelInfo) - mc.cacheByFullName = make(map[string]*modelInfo) - mc.done = false -} - -// ResetModelCache Clean model cache. Then you can re-RegisterModel. -// Common use this api for test case. -func ResetModelCache() { - modelCache.clean() -} diff --git a/vendor/github.com/astaxie/beego/orm/models_boot.go b/vendor/github.com/astaxie/beego/orm/models_boot.go deleted file mode 100644 index 8c56b3c4..00000000 --- a/vendor/github.com/astaxie/beego/orm/models_boot.go +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "os" - "reflect" - "runtime/debug" - "strings" -) - -// register models. -// PrefixOrSuffix means table name prefix or suffix. -// isPrefix whether the prefix is prefix or suffix -func registerModel(PrefixOrSuffix string, model interface{}, isPrefix bool) { - val := reflect.ValueOf(model) - typ := reflect.Indirect(val).Type() - - if val.Kind() != reflect.Ptr { - panic(fmt.Errorf(" cannot use non-ptr model struct `%s`", getFullName(typ))) - } - // For this case: - // u := &User{} - // registerModel(&u) - if typ.Kind() == reflect.Ptr { - panic(fmt.Errorf(" only allow ptr model struct, it looks you use two reference to the struct `%s`", typ)) - } - - table := getTableName(val) - - if PrefixOrSuffix != "" { - if isPrefix { - table = PrefixOrSuffix + table - } else { - table = table + PrefixOrSuffix - } - } - // models's fullname is pkgpath + struct name - name := getFullName(typ) - if _, ok := modelCache.getByFullName(name); ok { - fmt.Printf(" model `%s` repeat register, must be unique\n", name) - os.Exit(2) - } - - if _, ok := modelCache.get(table); ok { - fmt.Printf(" table name `%s` repeat register, must be unique\n", table) - os.Exit(2) - } - - mi := newModelInfo(val) - if mi.fields.pk == nil { - outFor: - for _, fi := range mi.fields.fieldsDB { - if strings.ToLower(fi.name) == "id" { - switch fi.addrValue.Elem().Kind() { - case reflect.Int, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint32, reflect.Uint64: - fi.auto = true - fi.pk = true - mi.fields.pk = fi - break outFor - } - } - } - - if mi.fields.pk == nil { - fmt.Printf(" `%s` needs a primary key field, default is to use 'id' if not set\n", name) - os.Exit(2) - } - - } - - mi.table = table - mi.pkg = typ.PkgPath() - mi.model = model - mi.manual = true - - modelCache.set(table, mi) -} - -// bootstrap models -func bootStrap() { - if modelCache.done { - return - } - var ( - err error - models map[string]*modelInfo - ) - if dataBaseCache.getDefault() == nil { - err = fmt.Errorf("must have one register DataBase alias named `default`") - goto end - } - - // set rel and reverse model - // RelManyToMany set the relTable - models = modelCache.all() - for _, mi := range models { - for _, fi := range mi.fields.columns { - if fi.rel || fi.reverse { - elm := fi.addrValue.Type().Elem() - if fi.fieldType == RelReverseMany || fi.fieldType == RelManyToMany { - elm = elm.Elem() - } - // check the rel or reverse model already register - name := getFullName(elm) - mii, ok := modelCache.getByFullName(name) - if !ok || mii.pkg != elm.PkgPath() { - err = fmt.Errorf("can not find rel in field `%s`, `%s` may be miss register", fi.fullName, elm.String()) - goto end - } - fi.relModelInfo = mii - - switch fi.fieldType { - case RelManyToMany: - if fi.relThrough != "" { - if i := strings.LastIndex(fi.relThrough, "."); i != -1 && len(fi.relThrough) > (i+1) { - pn := fi.relThrough[:i] - rmi, ok := modelCache.getByFullName(fi.relThrough) - if !ok || pn != rmi.pkg { - err = fmt.Errorf("field `%s` wrong rel_through value `%s` cannot find table", fi.fullName, fi.relThrough) - goto end - } - fi.relThroughModelInfo = rmi - fi.relTable = rmi.table - } else { - err = fmt.Errorf("field `%s` wrong rel_through value `%s`", fi.fullName, fi.relThrough) - goto end - } - } else { - i := newM2MModelInfo(mi, mii) - if fi.relTable != "" { - i.table = fi.relTable - } - if v := modelCache.set(i.table, i); v != nil { - err = fmt.Errorf("the rel table name `%s` already registered, cannot be use, please change one", fi.relTable) - goto end - } - fi.relTable = i.table - fi.relThroughModelInfo = i - } - - fi.relThroughModelInfo.isThrough = true - } - } - } - } - - // check the rel filed while the relModelInfo also has filed point to current model - // if not exist, add a new field to the relModelInfo - models = modelCache.all() - for _, mi := range models { - for _, fi := range mi.fields.fieldsRel { - switch fi.fieldType { - case RelForeignKey, RelOneToOne, RelManyToMany: - inModel := false - for _, ffi := range fi.relModelInfo.fields.fieldsReverse { - if ffi.relModelInfo == mi { - inModel = true - break - } - } - if !inModel { - rmi := fi.relModelInfo - ffi := new(fieldInfo) - ffi.name = mi.name - ffi.column = ffi.name - ffi.fullName = rmi.fullName + "." + ffi.name - ffi.reverse = true - ffi.relModelInfo = mi - ffi.mi = rmi - if fi.fieldType == RelOneToOne { - ffi.fieldType = RelReverseOne - } else { - ffi.fieldType = RelReverseMany - } - if !rmi.fields.Add(ffi) { - added := false - for cnt := 0; cnt < 5; cnt++ { - ffi.name = fmt.Sprintf("%s%d", mi.name, cnt) - ffi.column = ffi.name - ffi.fullName = rmi.fullName + "." + ffi.name - if added = rmi.fields.Add(ffi); added { - break - } - } - if !added { - panic(fmt.Errorf("cannot generate auto reverse field info `%s` to `%s`", fi.fullName, ffi.fullName)) - } - } - } - } - } - } - - models = modelCache.all() - for _, mi := range models { - for _, fi := range mi.fields.fieldsRel { - switch fi.fieldType { - case RelManyToMany: - for _, ffi := range fi.relThroughModelInfo.fields.fieldsRel { - switch ffi.fieldType { - case RelOneToOne, RelForeignKey: - if ffi.relModelInfo == fi.relModelInfo { - fi.reverseFieldInfoTwo = ffi - } - if ffi.relModelInfo == mi { - fi.reverseField = ffi.name - fi.reverseFieldInfo = ffi - } - } - } - if fi.reverseFieldInfoTwo == nil { - err = fmt.Errorf("can not find m2m field for m2m model `%s`, ensure your m2m model defined correct", - fi.relThroughModelInfo.fullName) - goto end - } - } - } - } - - models = modelCache.all() - for _, mi := range models { - for _, fi := range mi.fields.fieldsReverse { - switch fi.fieldType { - case RelReverseOne: - found := false - mForA: - for _, ffi := range fi.relModelInfo.fields.fieldsByType[RelOneToOne] { - if ffi.relModelInfo == mi { - found = true - fi.reverseField = ffi.name - fi.reverseFieldInfo = ffi - - ffi.reverseField = fi.name - ffi.reverseFieldInfo = fi - break mForA - } - } - if !found { - err = fmt.Errorf("reverse field `%s` not found in model `%s`", fi.fullName, fi.relModelInfo.fullName) - goto end - } - case RelReverseMany: - found := false - mForB: - for _, ffi := range fi.relModelInfo.fields.fieldsByType[RelForeignKey] { - if ffi.relModelInfo == mi { - found = true - fi.reverseField = ffi.name - fi.reverseFieldInfo = ffi - - ffi.reverseField = fi.name - ffi.reverseFieldInfo = fi - - break mForB - } - } - if !found { - mForC: - for _, ffi := range fi.relModelInfo.fields.fieldsByType[RelManyToMany] { - conditions := fi.relThrough != "" && fi.relThrough == ffi.relThrough || - fi.relTable != "" && fi.relTable == ffi.relTable || - fi.relThrough == "" && fi.relTable == "" - if ffi.relModelInfo == mi && conditions { - found = true - - fi.reverseField = ffi.reverseFieldInfoTwo.name - fi.reverseFieldInfo = ffi.reverseFieldInfoTwo - fi.relThroughModelInfo = ffi.relThroughModelInfo - fi.reverseFieldInfoTwo = ffi.reverseFieldInfo - fi.reverseFieldInfoM2M = ffi - ffi.reverseFieldInfoM2M = fi - - break mForC - } - } - } - if !found { - err = fmt.Errorf("reverse field for `%s` not found in model `%s`", fi.fullName, fi.relModelInfo.fullName) - goto end - } - } - } - } - -end: - if err != nil { - fmt.Println(err) - debug.PrintStack() - os.Exit(2) - } -} - -// RegisterModel register models -func RegisterModel(models ...interface{}) { - if modelCache.done { - panic(fmt.Errorf("RegisterModel must be run before BootStrap")) - } - RegisterModelWithPrefix("", models...) -} - -// RegisterModelWithPrefix register models with a prefix -func RegisterModelWithPrefix(prefix string, models ...interface{}) { - if modelCache.done { - panic(fmt.Errorf("RegisterModelWithPrefix must be run before BootStrap")) - } - - for _, model := range models { - registerModel(prefix, model, true) - } -} - -// RegisterModelWithSuffix register models with a suffix -func RegisterModelWithSuffix(suffix string, models ...interface{}) { - if modelCache.done { - panic(fmt.Errorf("RegisterModelWithSuffix must be run before BootStrap")) - } - - for _, model := range models { - registerModel(suffix, model, false) - } -} - -// BootStrap bootstrap models. -// make all model parsed and can not add more models -func BootStrap() { - modelCache.Lock() - defer modelCache.Unlock() - if modelCache.done { - return - } - bootStrap() - modelCache.done = true -} diff --git a/vendor/github.com/astaxie/beego/orm/models_fields.go b/vendor/github.com/astaxie/beego/orm/models_fields.go deleted file mode 100644 index b4fad94f..00000000 --- a/vendor/github.com/astaxie/beego/orm/models_fields.go +++ /dev/null @@ -1,783 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "strconv" - "time" -) - -// Define the Type enum -const ( - TypeBooleanField = 1 << iota - TypeVarCharField - TypeCharField - TypeTextField - TypeTimeField - TypeDateField - TypeDateTimeField - TypeBitField - TypeSmallIntegerField - TypeIntegerField - TypeBigIntegerField - TypePositiveBitField - TypePositiveSmallIntegerField - TypePositiveIntegerField - TypePositiveBigIntegerField - TypeFloatField - TypeDecimalField - TypeJSONField - TypeJsonbField - RelForeignKey - RelOneToOne - RelManyToMany - RelReverseOne - RelReverseMany -) - -// Define some logic enum -const ( - IsIntegerField = ^-TypePositiveBigIntegerField >> 6 << 7 - IsPositiveIntegerField = ^-TypePositiveBigIntegerField >> 10 << 11 - IsRelField = ^-RelReverseMany >> 18 << 19 - IsFieldType = ^-RelReverseMany<<1 + 1 -) - -// BooleanField A true/false field. -type BooleanField bool - -// Value return the BooleanField -func (e BooleanField) Value() bool { - return bool(e) -} - -// Set will set the BooleanField -func (e *BooleanField) Set(d bool) { - *e = BooleanField(d) -} - -// String format the Bool to string -func (e *BooleanField) String() string { - return strconv.FormatBool(e.Value()) -} - -// FieldType return BooleanField the type -func (e *BooleanField) FieldType() int { - return TypeBooleanField -} - -// SetRaw set the interface to bool -func (e *BooleanField) SetRaw(value interface{}) error { - switch d := value.(type) { - case bool: - e.Set(d) - case string: - v, err := StrTo(d).Bool() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return the current value -func (e *BooleanField) RawValue() interface{} { - return e.Value() -} - -// verify the BooleanField implement the Fielder interface -var _ Fielder = new(BooleanField) - -// CharField A string field -// required values tag: size -// The size is enforced at the database level and in models’s validation. -// eg: `orm:"size(120)"` -type CharField string - -// Value return the CharField's Value -func (e CharField) Value() string { - return string(e) -} - -// Set CharField value -func (e *CharField) Set(d string) { - *e = CharField(d) -} - -// String return the CharField -func (e *CharField) String() string { - return e.Value() -} - -// FieldType return the enum type -func (e *CharField) FieldType() int { - return TypeVarCharField -} - -// SetRaw set the interface to string -func (e *CharField) SetRaw(value interface{}) error { - switch d := value.(type) { - case string: - e.Set(d) - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return the CharField value -func (e *CharField) RawValue() interface{} { - return e.Value() -} - -// verify CharField implement Fielder -var _ Fielder = new(CharField) - -// TimeField A time, represented in go by a time.Time instance. -// only time values like 10:00:00 -// Has a few extra, optional attr tag: -// -// auto_now: -// Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. -// Note that the current date is always used; it’s not just a default value that you can override. -// -// auto_now_add: -// Automatically set the field to now when the object is first created. Useful for creation of timestamps. -// Note that the current date is always used; it’s not just a default value that you can override. -// -// eg: `orm:"auto_now"` or `orm:"auto_now_add"` -type TimeField time.Time - -// Value return the time.Time -func (e TimeField) Value() time.Time { - return time.Time(e) -} - -// Set set the TimeField's value -func (e *TimeField) Set(d time.Time) { - *e = TimeField(d) -} - -// String convert time to string -func (e *TimeField) String() string { - return e.Value().String() -} - -// FieldType return enum type Date -func (e *TimeField) FieldType() int { - return TypeDateField -} - -// SetRaw convert the interface to time.Time. Allow string and time.Time -func (e *TimeField) SetRaw(value interface{}) error { - switch d := value.(type) { - case time.Time: - e.Set(d) - case string: - v, err := timeParse(d, formatTime) - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return time value -func (e *TimeField) RawValue() interface{} { - return e.Value() -} - -var _ Fielder = new(TimeField) - -// DateField A date, represented in go by a time.Time instance. -// only date values like 2006-01-02 -// Has a few extra, optional attr tag: -// -// auto_now: -// Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. -// Note that the current date is always used; it’s not just a default value that you can override. -// -// auto_now_add: -// Automatically set the field to now when the object is first created. Useful for creation of timestamps. -// Note that the current date is always used; it’s not just a default value that you can override. -// -// eg: `orm:"auto_now"` or `orm:"auto_now_add"` -type DateField time.Time - -// Value return the time.Time -func (e DateField) Value() time.Time { - return time.Time(e) -} - -// Set set the DateField's value -func (e *DateField) Set(d time.Time) { - *e = DateField(d) -} - -// String convert datetime to string -func (e *DateField) String() string { - return e.Value().String() -} - -// FieldType return enum type Date -func (e *DateField) FieldType() int { - return TypeDateField -} - -// SetRaw convert the interface to time.Time. Allow string and time.Time -func (e *DateField) SetRaw(value interface{}) error { - switch d := value.(type) { - case time.Time: - e.Set(d) - case string: - v, err := timeParse(d, formatDate) - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return Date value -func (e *DateField) RawValue() interface{} { - return e.Value() -} - -// verify DateField implement fielder interface -var _ Fielder = new(DateField) - -// DateTimeField A date, represented in go by a time.Time instance. -// datetime values like 2006-01-02 15:04:05 -// Takes the same extra arguments as DateField. -type DateTimeField time.Time - -// Value return the datetime value -func (e DateTimeField) Value() time.Time { - return time.Time(e) -} - -// Set set the time.Time to datetime -func (e *DateTimeField) Set(d time.Time) { - *e = DateTimeField(d) -} - -// String return the time's String -func (e *DateTimeField) String() string { - return e.Value().String() -} - -// FieldType return the enum TypeDateTimeField -func (e *DateTimeField) FieldType() int { - return TypeDateTimeField -} - -// SetRaw convert the string or time.Time to DateTimeField -func (e *DateTimeField) SetRaw(value interface{}) error { - switch d := value.(type) { - case time.Time: - e.Set(d) - case string: - v, err := timeParse(d, formatDateTime) - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return the datetime value -func (e *DateTimeField) RawValue() interface{} { - return e.Value() -} - -// verify datetime implement fielder -var _ Fielder = new(DateTimeField) - -// FloatField A floating-point number represented in go by a float32 value. -type FloatField float64 - -// Value return the FloatField value -func (e FloatField) Value() float64 { - return float64(e) -} - -// Set the Float64 -func (e *FloatField) Set(d float64) { - *e = FloatField(d) -} - -// String return the string -func (e *FloatField) String() string { - return ToStr(e.Value(), -1, 32) -} - -// FieldType return the enum type -func (e *FloatField) FieldType() int { - return TypeFloatField -} - -// SetRaw converter interface Float64 float32 or string to FloatField -func (e *FloatField) SetRaw(value interface{}) error { - switch d := value.(type) { - case float32: - e.Set(float64(d)) - case float64: - e.Set(d) - case string: - v, err := StrTo(d).Float64() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return the FloatField value -func (e *FloatField) RawValue() interface{} { - return e.Value() -} - -// verify FloatField implement Fielder -var _ Fielder = new(FloatField) - -// SmallIntegerField -32768 to 32767 -type SmallIntegerField int16 - -// Value return int16 value -func (e SmallIntegerField) Value() int16 { - return int16(e) -} - -// Set the SmallIntegerField value -func (e *SmallIntegerField) Set(d int16) { - *e = SmallIntegerField(d) -} - -// String convert smallint to string -func (e *SmallIntegerField) String() string { - return ToStr(e.Value()) -} - -// FieldType return enum type SmallIntegerField -func (e *SmallIntegerField) FieldType() int { - return TypeSmallIntegerField -} - -// SetRaw convert interface int16/string to int16 -func (e *SmallIntegerField) SetRaw(value interface{}) error { - switch d := value.(type) { - case int16: - e.Set(d) - case string: - v, err := StrTo(d).Int16() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return smallint value -func (e *SmallIntegerField) RawValue() interface{} { - return e.Value() -} - -// verify SmallIntegerField implement Fielder -var _ Fielder = new(SmallIntegerField) - -// IntegerField -2147483648 to 2147483647 -type IntegerField int32 - -// Value return the int32 -func (e IntegerField) Value() int32 { - return int32(e) -} - -// Set IntegerField value -func (e *IntegerField) Set(d int32) { - *e = IntegerField(d) -} - -// String convert Int32 to string -func (e *IntegerField) String() string { - return ToStr(e.Value()) -} - -// FieldType return the enum type -func (e *IntegerField) FieldType() int { - return TypeIntegerField -} - -// SetRaw convert interface int32/string to int32 -func (e *IntegerField) SetRaw(value interface{}) error { - switch d := value.(type) { - case int32: - e.Set(d) - case string: - v, err := StrTo(d).Int32() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return IntegerField value -func (e *IntegerField) RawValue() interface{} { - return e.Value() -} - -// verify IntegerField implement Fielder -var _ Fielder = new(IntegerField) - -// BigIntegerField -9223372036854775808 to 9223372036854775807. -type BigIntegerField int64 - -// Value return int64 -func (e BigIntegerField) Value() int64 { - return int64(e) -} - -// Set the BigIntegerField value -func (e *BigIntegerField) Set(d int64) { - *e = BigIntegerField(d) -} - -// String convert BigIntegerField to string -func (e *BigIntegerField) String() string { - return ToStr(e.Value()) -} - -// FieldType return enum type -func (e *BigIntegerField) FieldType() int { - return TypeBigIntegerField -} - -// SetRaw convert interface int64/string to int64 -func (e *BigIntegerField) SetRaw(value interface{}) error { - switch d := value.(type) { - case int64: - e.Set(d) - case string: - v, err := StrTo(d).Int64() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return BigIntegerField value -func (e *BigIntegerField) RawValue() interface{} { - return e.Value() -} - -// verify BigIntegerField implement Fielder -var _ Fielder = new(BigIntegerField) - -// PositiveSmallIntegerField 0 to 65535 -type PositiveSmallIntegerField uint16 - -// Value return uint16 -func (e PositiveSmallIntegerField) Value() uint16 { - return uint16(e) -} - -// Set PositiveSmallIntegerField value -func (e *PositiveSmallIntegerField) Set(d uint16) { - *e = PositiveSmallIntegerField(d) -} - -// String convert uint16 to string -func (e *PositiveSmallIntegerField) String() string { - return ToStr(e.Value()) -} - -// FieldType return enum type -func (e *PositiveSmallIntegerField) FieldType() int { - return TypePositiveSmallIntegerField -} - -// SetRaw convert Interface uint16/string to uint16 -func (e *PositiveSmallIntegerField) SetRaw(value interface{}) error { - switch d := value.(type) { - case uint16: - e.Set(d) - case string: - v, err := StrTo(d).Uint16() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue returns PositiveSmallIntegerField value -func (e *PositiveSmallIntegerField) RawValue() interface{} { - return e.Value() -} - -// verify PositiveSmallIntegerField implement Fielder -var _ Fielder = new(PositiveSmallIntegerField) - -// PositiveIntegerField 0 to 4294967295 -type PositiveIntegerField uint32 - -// Value return PositiveIntegerField value. Uint32 -func (e PositiveIntegerField) Value() uint32 { - return uint32(e) -} - -// Set the PositiveIntegerField value -func (e *PositiveIntegerField) Set(d uint32) { - *e = PositiveIntegerField(d) -} - -// String convert PositiveIntegerField to string -func (e *PositiveIntegerField) String() string { - return ToStr(e.Value()) -} - -// FieldType return enum type -func (e *PositiveIntegerField) FieldType() int { - return TypePositiveIntegerField -} - -// SetRaw convert interface uint32/string to Uint32 -func (e *PositiveIntegerField) SetRaw(value interface{}) error { - switch d := value.(type) { - case uint32: - e.Set(d) - case string: - v, err := StrTo(d).Uint32() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return the PositiveIntegerField Value -func (e *PositiveIntegerField) RawValue() interface{} { - return e.Value() -} - -// verify PositiveIntegerField implement Fielder -var _ Fielder = new(PositiveIntegerField) - -// PositiveBigIntegerField 0 to 18446744073709551615 -type PositiveBigIntegerField uint64 - -// Value return uint64 -func (e PositiveBigIntegerField) Value() uint64 { - return uint64(e) -} - -// Set PositiveBigIntegerField value -func (e *PositiveBigIntegerField) Set(d uint64) { - *e = PositiveBigIntegerField(d) -} - -// String convert PositiveBigIntegerField to string -func (e *PositiveBigIntegerField) String() string { - return ToStr(e.Value()) -} - -// FieldType return enum type -func (e *PositiveBigIntegerField) FieldType() int { - return TypePositiveIntegerField -} - -// SetRaw convert interface uint64/string to Uint64 -func (e *PositiveBigIntegerField) SetRaw(value interface{}) error { - switch d := value.(type) { - case uint64: - e.Set(d) - case string: - v, err := StrTo(d).Uint64() - if err == nil { - e.Set(v) - } - return err - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return PositiveBigIntegerField value -func (e *PositiveBigIntegerField) RawValue() interface{} { - return e.Value() -} - -// verify PositiveBigIntegerField implement Fielder -var _ Fielder = new(PositiveBigIntegerField) - -// TextField A large text field. -type TextField string - -// Value return TextField value -func (e TextField) Value() string { - return string(e) -} - -// Set the TextField value -func (e *TextField) Set(d string) { - *e = TextField(d) -} - -// String convert TextField to string -func (e *TextField) String() string { - return e.Value() -} - -// FieldType return enum type -func (e *TextField) FieldType() int { - return TypeTextField -} - -// SetRaw convert interface string to string -func (e *TextField) SetRaw(value interface{}) error { - switch d := value.(type) { - case string: - e.Set(d) - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return TextField value -func (e *TextField) RawValue() interface{} { - return e.Value() -} - -// verify TextField implement Fielder -var _ Fielder = new(TextField) - -// JSONField postgres json field. -type JSONField string - -// Value return JSONField value -func (j JSONField) Value() string { - return string(j) -} - -// Set the JSONField value -func (j *JSONField) Set(d string) { - *j = JSONField(d) -} - -// String convert JSONField to string -func (j *JSONField) String() string { - return j.Value() -} - -// FieldType return enum type -func (j *JSONField) FieldType() int { - return TypeJSONField -} - -// SetRaw convert interface string to string -func (j *JSONField) SetRaw(value interface{}) error { - switch d := value.(type) { - case string: - j.Set(d) - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return JSONField value -func (j *JSONField) RawValue() interface{} { - return j.Value() -} - -// verify JSONField implement Fielder -var _ Fielder = new(JSONField) - -// JsonbField postgres json field. -type JsonbField string - -// Value return JsonbField value -func (j JsonbField) Value() string { - return string(j) -} - -// Set the JsonbField value -func (j *JsonbField) Set(d string) { - *j = JsonbField(d) -} - -// String convert JsonbField to string -func (j *JsonbField) String() string { - return j.Value() -} - -// FieldType return enum type -func (j *JsonbField) FieldType() int { - return TypeJsonbField -} - -// SetRaw convert interface string to string -func (j *JsonbField) SetRaw(value interface{}) error { - switch d := value.(type) { - case string: - j.Set(d) - default: - return fmt.Errorf(" unknown value `%s`", value) - } - return nil -} - -// RawValue return JsonbField value -func (j *JsonbField) RawValue() interface{} { - return j.Value() -} - -// verify JsonbField implement Fielder -var _ Fielder = new(JsonbField) diff --git a/vendor/github.com/astaxie/beego/orm/models_info_f.go b/vendor/github.com/astaxie/beego/orm/models_info_f.go deleted file mode 100644 index 7044b0bd..00000000 --- a/vendor/github.com/astaxie/beego/orm/models_info_f.go +++ /dev/null @@ -1,473 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "errors" - "fmt" - "reflect" - "strings" -) - -var errSkipField = errors.New("skip field") - -// field info collection -type fields struct { - pk *fieldInfo - columns map[string]*fieldInfo - fields map[string]*fieldInfo - fieldsLow map[string]*fieldInfo - fieldsByType map[int][]*fieldInfo - fieldsRel []*fieldInfo - fieldsReverse []*fieldInfo - fieldsDB []*fieldInfo - rels []*fieldInfo - orders []string - dbcols []string -} - -// add field info -func (f *fields) Add(fi *fieldInfo) (added bool) { - if f.fields[fi.name] == nil && f.columns[fi.column] == nil { - f.columns[fi.column] = fi - f.fields[fi.name] = fi - f.fieldsLow[strings.ToLower(fi.name)] = fi - } else { - return - } - if _, ok := f.fieldsByType[fi.fieldType]; !ok { - f.fieldsByType[fi.fieldType] = make([]*fieldInfo, 0) - } - f.fieldsByType[fi.fieldType] = append(f.fieldsByType[fi.fieldType], fi) - f.orders = append(f.orders, fi.column) - if fi.dbcol { - f.dbcols = append(f.dbcols, fi.column) - f.fieldsDB = append(f.fieldsDB, fi) - } - if fi.rel { - f.fieldsRel = append(f.fieldsRel, fi) - } - if fi.reverse { - f.fieldsReverse = append(f.fieldsReverse, fi) - } - return true -} - -// get field info by name -func (f *fields) GetByName(name string) *fieldInfo { - return f.fields[name] -} - -// get field info by column name -func (f *fields) GetByColumn(column string) *fieldInfo { - return f.columns[column] -} - -// get field info by string, name is prior -func (f *fields) GetByAny(name string) (*fieldInfo, bool) { - if fi, ok := f.fields[name]; ok { - return fi, ok - } - if fi, ok := f.fieldsLow[strings.ToLower(name)]; ok { - return fi, ok - } - if fi, ok := f.columns[name]; ok { - return fi, ok - } - return nil, false -} - -// create new field info collection -func newFields() *fields { - f := new(fields) - f.fields = make(map[string]*fieldInfo) - f.fieldsLow = make(map[string]*fieldInfo) - f.columns = make(map[string]*fieldInfo) - f.fieldsByType = make(map[int][]*fieldInfo) - return f -} - -// single field info -type fieldInfo struct { - mi *modelInfo - fieldIndex []int - fieldType int - dbcol bool // table column fk and onetoone - inModel bool - name string - fullName string - column string - addrValue reflect.Value - sf reflect.StructField - auto bool - pk bool - null bool - index bool - unique bool - colDefault bool // whether has default tag - initial StrTo // store the default value - size int - toText bool - autoNow bool - autoNowAdd bool - rel bool // if type equal to RelForeignKey, RelOneToOne, RelManyToMany then true - reverse bool - reverseField string - reverseFieldInfo *fieldInfo - reverseFieldInfoTwo *fieldInfo - reverseFieldInfoM2M *fieldInfo - relTable string - relThrough string - relThroughModelInfo *modelInfo - relModelInfo *modelInfo - digits int - decimals int - isFielder bool // implement Fielder interface - onDelete string - description string -} - -// new field info -func newFieldInfo(mi *modelInfo, field reflect.Value, sf reflect.StructField, mName string) (fi *fieldInfo, err error) { - var ( - tag string - tagValue string - initial StrTo // store the default value - fieldType int - attrs map[string]bool - tags map[string]string - addrField reflect.Value - ) - - fi = new(fieldInfo) - - // if field which CanAddr is the follow type - // A value is addressable if it is an element of a slice, - // an element of an addressable array, a field of an - // addressable struct, or the result of dereferencing a pointer. - addrField = field - if field.CanAddr() && field.Kind() != reflect.Ptr { - addrField = field.Addr() - if _, ok := addrField.Interface().(Fielder); !ok { - if field.Kind() == reflect.Slice { - addrField = field - } - } - } - - attrs, tags = parseStructTag(sf.Tag.Get(defaultStructTagName)) - - if _, ok := attrs["-"]; ok { - return nil, errSkipField - } - - digits := tags["digits"] - decimals := tags["decimals"] - size := tags["size"] - onDelete := tags["on_delete"] - - initial.Clear() - if v, ok := tags["default"]; ok { - initial.Set(v) - } - -checkType: - switch f := addrField.Interface().(type) { - case Fielder: - fi.isFielder = true - if field.Kind() == reflect.Ptr { - err = fmt.Errorf("the model Fielder can not be use ptr") - goto end - } - fieldType = f.FieldType() - if fieldType&IsRelField > 0 { - err = fmt.Errorf("unsupport type custom field, please refer to https://github.com/astaxie/beego/blob/master/orm/models_fields.go#L24-L42") - goto end - } - default: - tag = "rel" - tagValue = tags[tag] - if tagValue != "" { - switch tagValue { - case "fk": - fieldType = RelForeignKey - break checkType - case "one": - fieldType = RelOneToOne - break checkType - case "m2m": - fieldType = RelManyToMany - if tv := tags["rel_table"]; tv != "" { - fi.relTable = tv - } else if tv := tags["rel_through"]; tv != "" { - fi.relThrough = tv - } - break checkType - default: - err = fmt.Errorf("rel only allow these value: fk, one, m2m") - goto wrongTag - } - } - tag = "reverse" - tagValue = tags[tag] - if tagValue != "" { - switch tagValue { - case "one": - fieldType = RelReverseOne - break checkType - case "many": - fieldType = RelReverseMany - if tv := tags["rel_table"]; tv != "" { - fi.relTable = tv - } else if tv := tags["rel_through"]; tv != "" { - fi.relThrough = tv - } - break checkType - default: - err = fmt.Errorf("reverse only allow these value: one, many") - goto wrongTag - } - } - - fieldType, err = getFieldType(addrField) - if err != nil { - goto end - } - if fieldType == TypeVarCharField { - switch tags["type"] { - case "char": - fieldType = TypeCharField - case "text": - fieldType = TypeTextField - case "json": - fieldType = TypeJSONField - case "jsonb": - fieldType = TypeJsonbField - } - } - if fieldType == TypeFloatField && (digits != "" || decimals != "") { - fieldType = TypeDecimalField - } - if fieldType == TypeDateTimeField && tags["type"] == "date" { - fieldType = TypeDateField - } - if fieldType == TypeTimeField && tags["type"] == "time" { - fieldType = TypeTimeField - } - } - - // check the rel and reverse type - // rel should Ptr - // reverse should slice []*struct - switch fieldType { - case RelForeignKey, RelOneToOne, RelReverseOne: - if field.Kind() != reflect.Ptr { - err = fmt.Errorf("rel/reverse:one field must be *%s", field.Type().Name()) - goto end - } - case RelManyToMany, RelReverseMany: - if field.Kind() != reflect.Slice { - err = fmt.Errorf("rel/reverse:many field must be slice") - goto end - } else { - if field.Type().Elem().Kind() != reflect.Ptr { - err = fmt.Errorf("rel/reverse:many slice must be []*%s", field.Type().Elem().Name()) - goto end - } - } - } - - if fieldType&IsFieldType == 0 { - err = fmt.Errorf("wrong field type") - goto end - } - - fi.fieldType = fieldType - fi.name = sf.Name - fi.column = getColumnName(fieldType, addrField, sf, tags["column"]) - fi.addrValue = addrField - fi.sf = sf - fi.fullName = mi.fullName + mName + "." + sf.Name - - fi.description = tags["description"] - fi.null = attrs["null"] - fi.index = attrs["index"] - fi.auto = attrs["auto"] - fi.pk = attrs["pk"] - fi.unique = attrs["unique"] - - // Mark object property if there is attribute "default" in the orm configuration - if _, ok := tags["default"]; ok { - fi.colDefault = true - } - - switch fieldType { - case RelManyToMany, RelReverseMany, RelReverseOne: - fi.null = false - fi.index = false - fi.auto = false - fi.pk = false - fi.unique = false - default: - fi.dbcol = true - } - - switch fieldType { - case RelForeignKey, RelOneToOne, RelManyToMany: - fi.rel = true - if fieldType == RelOneToOne { - fi.unique = true - } - case RelReverseMany, RelReverseOne: - fi.reverse = true - } - - if fi.rel && fi.dbcol { - switch onDelete { - case odCascade, odDoNothing: - case odSetDefault: - if !initial.Exist() { - err = errors.New("on_delete: set_default need set field a default value") - goto end - } - case odSetNULL: - if !fi.null { - err = errors.New("on_delete: set_null need set field null") - goto end - } - default: - if onDelete == "" { - onDelete = odCascade - } else { - err = fmt.Errorf("on_delete value expected choice in `cascade,set_null,set_default,do_nothing`, unknown `%s`", onDelete) - goto end - } - } - - fi.onDelete = onDelete - } - - switch fieldType { - case TypeBooleanField: - case TypeVarCharField, TypeCharField, TypeJSONField, TypeJsonbField: - if size != "" { - v, e := StrTo(size).Int32() - if e != nil { - err = fmt.Errorf("wrong size value `%s`", size) - } else { - fi.size = int(v) - } - } else { - fi.size = 255 - fi.toText = true - } - case TypeTextField: - fi.index = false - fi.unique = false - case TypeTimeField, TypeDateField, TypeDateTimeField: - if attrs["auto_now"] { - fi.autoNow = true - } else if attrs["auto_now_add"] { - fi.autoNowAdd = true - } - case TypeFloatField: - case TypeDecimalField: - d1 := digits - d2 := decimals - v1, er1 := StrTo(d1).Int8() - v2, er2 := StrTo(d2).Int8() - if er1 != nil || er2 != nil { - err = fmt.Errorf("wrong digits/decimals value %s/%s", d2, d1) - goto end - } - fi.digits = int(v1) - fi.decimals = int(v2) - default: - switch { - case fieldType&IsIntegerField > 0: - case fieldType&IsRelField > 0: - } - } - - if fieldType&IsIntegerField == 0 { - if fi.auto { - err = fmt.Errorf("non-integer type cannot set auto") - goto end - } - } - - if fi.auto || fi.pk { - if fi.auto { - switch addrField.Elem().Kind() { - case reflect.Int, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint32, reflect.Uint64: - default: - err = fmt.Errorf("auto primary key only support int, int32, int64, uint, uint32, uint64 but found `%s`", addrField.Elem().Kind()) - goto end - } - fi.pk = true - } - fi.null = false - fi.index = false - fi.unique = false - } - - if fi.unique { - fi.index = false - } - - // can not set default for these type - if fi.auto || fi.pk || fi.unique || fieldType == TypeTimeField || fieldType == TypeDateField || fieldType == TypeDateTimeField { - initial.Clear() - } - - if initial.Exist() { - v := initial - switch fieldType { - case TypeBooleanField: - _, err = v.Bool() - case TypeFloatField, TypeDecimalField: - _, err = v.Float64() - case TypeBitField: - _, err = v.Int8() - case TypeSmallIntegerField: - _, err = v.Int16() - case TypeIntegerField: - _, err = v.Int32() - case TypeBigIntegerField: - _, err = v.Int64() - case TypePositiveBitField: - _, err = v.Uint8() - case TypePositiveSmallIntegerField: - _, err = v.Uint16() - case TypePositiveIntegerField: - _, err = v.Uint32() - case TypePositiveBigIntegerField: - _, err = v.Uint64() - } - if err != nil { - tag, tagValue = "default", tags["default"] - goto wrongTag - } - } - - fi.initial = initial -end: - if err != nil { - return nil, err - } - return -wrongTag: - return nil, fmt.Errorf("wrong tag format: `%s:\"%s\"`, %s", tag, tagValue, err) -} diff --git a/vendor/github.com/astaxie/beego/orm/models_info_m.go b/vendor/github.com/astaxie/beego/orm/models_info_m.go deleted file mode 100644 index a4d733b6..00000000 --- a/vendor/github.com/astaxie/beego/orm/models_info_m.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "os" - "reflect" -) - -// single model info -type modelInfo struct { - pkg string - name string - fullName string - table string - model interface{} - fields *fields - manual bool - addrField reflect.Value //store the original struct value - uniques []string - isThrough bool -} - -// new model info -func newModelInfo(val reflect.Value) (mi *modelInfo) { - mi = &modelInfo{} - mi.fields = newFields() - ind := reflect.Indirect(val) - mi.addrField = val - mi.name = ind.Type().Name() - mi.fullName = getFullName(ind.Type()) - addModelFields(mi, ind, "", []int{}) - return -} - -// index: FieldByIndex returns the nested field corresponding to index -func addModelFields(mi *modelInfo, ind reflect.Value, mName string, index []int) { - var ( - err error - fi *fieldInfo - sf reflect.StructField - ) - - for i := 0; i < ind.NumField(); i++ { - field := ind.Field(i) - sf = ind.Type().Field(i) - // if the field is unexported skip - if sf.PkgPath != "" { - continue - } - // add anonymous struct fields - if sf.Anonymous { - addModelFields(mi, field, mName+"."+sf.Name, append(index, i)) - continue - } - - fi, err = newFieldInfo(mi, field, sf, mName) - if err == errSkipField { - err = nil - continue - } else if err != nil { - break - } - //record current field index - fi.fieldIndex = append(fi.fieldIndex, index...) - fi.fieldIndex = append(fi.fieldIndex, i) - fi.mi = mi - fi.inModel = true - if !mi.fields.Add(fi) { - err = fmt.Errorf("duplicate column name: %s", fi.column) - break - } - if fi.pk { - if mi.fields.pk != nil { - err = fmt.Errorf("one model must have one pk field only") - break - } else { - mi.fields.pk = fi - } - } - } - - if err != nil { - fmt.Println(fmt.Errorf("field: %s.%s, %s", ind.Type(), sf.Name, err)) - os.Exit(2) - } -} - -// combine related model info to new model info. -// prepare for relation models query. -func newM2MModelInfo(m1, m2 *modelInfo) (mi *modelInfo) { - mi = new(modelInfo) - mi.fields = newFields() - mi.table = m1.table + "_" + m2.table + "s" - mi.name = camelString(mi.table) - mi.fullName = m1.pkg + "." + mi.name - - fa := new(fieldInfo) // pk - f1 := new(fieldInfo) // m1 table RelForeignKey - f2 := new(fieldInfo) // m2 table RelForeignKey - fa.fieldType = TypeBigIntegerField - fa.auto = true - fa.pk = true - fa.dbcol = true - fa.name = "Id" - fa.column = "id" - fa.fullName = mi.fullName + "." + fa.name - - f1.dbcol = true - f2.dbcol = true - f1.fieldType = RelForeignKey - f2.fieldType = RelForeignKey - f1.name = camelString(m1.table) - f2.name = camelString(m2.table) - f1.fullName = mi.fullName + "." + f1.name - f2.fullName = mi.fullName + "." + f2.name - f1.column = m1.table + "_id" - f2.column = m2.table + "_id" - f1.rel = true - f2.rel = true - f1.relTable = m1.table - f2.relTable = m2.table - f1.relModelInfo = m1 - f2.relModelInfo = m2 - f1.mi = mi - f2.mi = mi - - mi.fields.Add(fa) - mi.fields.Add(f1) - mi.fields.Add(f2) - mi.fields.pk = fa - - mi.uniques = []string{f1.column, f2.column} - return -} diff --git a/vendor/github.com/astaxie/beego/orm/models_utils.go b/vendor/github.com/astaxie/beego/orm/models_utils.go deleted file mode 100644 index 71127a6b..00000000 --- a/vendor/github.com/astaxie/beego/orm/models_utils.go +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "database/sql" - "fmt" - "reflect" - "strings" - "time" -) - -// 1 is attr -// 2 is tag -var supportTag = map[string]int{ - "-": 1, - "null": 1, - "index": 1, - "unique": 1, - "pk": 1, - "auto": 1, - "auto_now": 1, - "auto_now_add": 1, - "size": 2, - "column": 2, - "default": 2, - "rel": 2, - "reverse": 2, - "rel_table": 2, - "rel_through": 2, - "digits": 2, - "decimals": 2, - "on_delete": 2, - "type": 2, - "description": 2, -} - -// get reflect.Type name with package path. -func getFullName(typ reflect.Type) string { - return typ.PkgPath() + "." + typ.Name() -} - -// getTableName get struct table name. -// If the struct implement the TableName, then get the result as tablename -// else use the struct name which will apply snakeString. -func getTableName(val reflect.Value) string { - if fun := val.MethodByName("TableName"); fun.IsValid() { - vals := fun.Call([]reflect.Value{}) - // has return and the first val is string - if len(vals) > 0 && vals[0].Kind() == reflect.String { - return vals[0].String() - } - } - return snakeString(reflect.Indirect(val).Type().Name()) -} - -// get table engine, myisam or innodb. -func getTableEngine(val reflect.Value) string { - fun := val.MethodByName("TableEngine") - if fun.IsValid() { - vals := fun.Call([]reflect.Value{}) - if len(vals) > 0 && vals[0].Kind() == reflect.String { - return vals[0].String() - } - } - return "" -} - -// get table index from method. -func getTableIndex(val reflect.Value) [][]string { - fun := val.MethodByName("TableIndex") - if fun.IsValid() { - vals := fun.Call([]reflect.Value{}) - if len(vals) > 0 && vals[0].CanInterface() { - if d, ok := vals[0].Interface().([][]string); ok { - return d - } - } - } - return nil -} - -// get table unique from method -func getTableUnique(val reflect.Value) [][]string { - fun := val.MethodByName("TableUnique") - if fun.IsValid() { - vals := fun.Call([]reflect.Value{}) - if len(vals) > 0 && vals[0].CanInterface() { - if d, ok := vals[0].Interface().([][]string); ok { - return d - } - } - } - return nil -} - -// get snaked column name -func getColumnName(ft int, addrField reflect.Value, sf reflect.StructField, col string) string { - column := col - if col == "" { - column = nameStrategyMap[nameStrategy](sf.Name) - } - switch ft { - case RelForeignKey, RelOneToOne: - if len(col) == 0 { - column = column + "_id" - } - case RelManyToMany, RelReverseMany, RelReverseOne: - column = sf.Name - } - return column -} - -// return field type as type constant from reflect.Value -func getFieldType(val reflect.Value) (ft int, err error) { - switch val.Type() { - case reflect.TypeOf(new(int8)): - ft = TypeBitField - case reflect.TypeOf(new(int16)): - ft = TypeSmallIntegerField - case reflect.TypeOf(new(int32)), - reflect.TypeOf(new(int)): - ft = TypeIntegerField - case reflect.TypeOf(new(int64)): - ft = TypeBigIntegerField - case reflect.TypeOf(new(uint8)): - ft = TypePositiveBitField - case reflect.TypeOf(new(uint16)): - ft = TypePositiveSmallIntegerField - case reflect.TypeOf(new(uint32)), - reflect.TypeOf(new(uint)): - ft = TypePositiveIntegerField - case reflect.TypeOf(new(uint64)): - ft = TypePositiveBigIntegerField - case reflect.TypeOf(new(float32)), - reflect.TypeOf(new(float64)): - ft = TypeFloatField - case reflect.TypeOf(new(bool)): - ft = TypeBooleanField - case reflect.TypeOf(new(string)): - ft = TypeVarCharField - case reflect.TypeOf(new(time.Time)): - ft = TypeDateTimeField - default: - elm := reflect.Indirect(val) - switch elm.Kind() { - case reflect.Int8: - ft = TypeBitField - case reflect.Int16: - ft = TypeSmallIntegerField - case reflect.Int32, reflect.Int: - ft = TypeIntegerField - case reflect.Int64: - ft = TypeBigIntegerField - case reflect.Uint8: - ft = TypePositiveBitField - case reflect.Uint16: - ft = TypePositiveSmallIntegerField - case reflect.Uint32, reflect.Uint: - ft = TypePositiveIntegerField - case reflect.Uint64: - ft = TypePositiveBigIntegerField - case reflect.Float32, reflect.Float64: - ft = TypeFloatField - case reflect.Bool: - ft = TypeBooleanField - case reflect.String: - ft = TypeVarCharField - default: - if elm.Interface() == nil { - panic(fmt.Errorf("%s is nil pointer, may be miss setting tag", val)) - } - switch elm.Interface().(type) { - case sql.NullInt64: - ft = TypeBigIntegerField - case sql.NullFloat64: - ft = TypeFloatField - case sql.NullBool: - ft = TypeBooleanField - case sql.NullString: - ft = TypeVarCharField - case time.Time: - ft = TypeDateTimeField - } - } - } - if ft&IsFieldType == 0 { - err = fmt.Errorf("unsupport field type %s, may be miss setting tag", val) - } - return -} - -// parse struct tag string -func parseStructTag(data string) (attrs map[string]bool, tags map[string]string) { - attrs = make(map[string]bool) - tags = make(map[string]string) - for _, v := range strings.Split(data, defaultStructTagDelim) { - if v == "" { - continue - } - v = strings.TrimSpace(v) - if t := strings.ToLower(v); supportTag[t] == 1 { - attrs[t] = true - } else if i := strings.Index(v, "("); i > 0 && strings.Index(v, ")") == len(v)-1 { - name := t[:i] - if supportTag[name] == 2 { - v = v[i+1 : len(v)-1] - tags[name] = v - } - } else { - DebugLog.Println("unsupport orm tag", v) - } - } - return -} diff --git a/vendor/github.com/astaxie/beego/orm/orm.go b/vendor/github.com/astaxie/beego/orm/orm.go deleted file mode 100644 index 0551b1cd..00000000 --- a/vendor/github.com/astaxie/beego/orm/orm.go +++ /dev/null @@ -1,579 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.8 - -// Package orm provide ORM for MySQL/PostgreSQL/sqlite -// Simple Usage -// -// package main -// -// import ( -// "fmt" -// "github.com/astaxie/beego/orm" -// _ "github.com/go-sql-driver/mysql" // import your used driver -// ) -// -// // Model Struct -// type User struct { -// Id int `orm:"auto"` -// Name string `orm:"size(100)"` -// } -// -// func init() { -// orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30) -// } -// -// func main() { -// o := orm.NewOrm() -// user := User{Name: "slene"} -// // insert -// id, err := o.Insert(&user) -// // update -// user.Name = "astaxie" -// num, err := o.Update(&user) -// // read one -// u := User{Id: user.Id} -// err = o.Read(&u) -// // delete -// num, err = o.Delete(&u) -// } -// -// more docs: http://beego.me/docs/mvc/model/overview.md -package orm - -import ( - "context" - "database/sql" - "errors" - "fmt" - "os" - "reflect" - "sync" - "time" -) - -// DebugQueries define the debug -const ( - DebugQueries = iota -) - -// Define common vars -var ( - Debug = false - DebugLog = NewLog(os.Stdout) - DefaultRowsLimit = -1 - DefaultRelsDepth = 2 - DefaultTimeLoc = time.Local - ErrTxHasBegan = errors.New(" transaction already begin") - ErrTxDone = errors.New(" transaction not begin") - ErrMultiRows = errors.New(" return multi rows") - ErrNoRows = errors.New(" no row found") - ErrStmtClosed = errors.New(" stmt already closed") - ErrArgs = errors.New(" args error may be empty") - ErrNotImplement = errors.New("have not implement") -) - -// Params stores the Params -type Params map[string]interface{} - -// ParamsList stores paramslist -type ParamsList []interface{} - -type orm struct { - alias *alias - db dbQuerier - isTx bool -} - -var _ Ormer = new(orm) - -// get model info and model reflect value -func (o *orm) getMiInd(md interface{}, needPtr bool) (mi *modelInfo, ind reflect.Value) { - val := reflect.ValueOf(md) - ind = reflect.Indirect(val) - typ := ind.Type() - if needPtr && val.Kind() != reflect.Ptr { - panic(fmt.Errorf(" cannot use non-ptr model struct `%s`", getFullName(typ))) - } - name := getFullName(typ) - if mi, ok := modelCache.getByFullName(name); ok { - return mi, ind - } - panic(fmt.Errorf(" table: `%s` not found, make sure it was registered with `RegisterModel()`", name)) -} - -// get field info from model info by given field name -func (o *orm) getFieldInfo(mi *modelInfo, name string) *fieldInfo { - fi, ok := mi.fields.GetByAny(name) - if !ok { - panic(fmt.Errorf(" cannot find field `%s` for model `%s`", name, mi.fullName)) - } - return fi -} - -// read data to model -func (o *orm) Read(md interface{}, cols ...string) error { - mi, ind := o.getMiInd(md, true) - return o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols, false) -} - -// read data to model, like Read(), but use "SELECT FOR UPDATE" form -func (o *orm) ReadForUpdate(md interface{}, cols ...string) error { - mi, ind := o.getMiInd(md, true) - return o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols, true) -} - -// Try to read a row from the database, or insert one if it doesn't exist -func (o *orm) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) { - cols = append([]string{col1}, cols...) - mi, ind := o.getMiInd(md, true) - err := o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols, false) - if err == ErrNoRows { - // Create - id, err := o.Insert(md) - return (err == nil), id, err - } - - id, vid := int64(0), ind.FieldByIndex(mi.fields.pk.fieldIndex) - if mi.fields.pk.fieldType&IsPositiveIntegerField > 0 { - id = int64(vid.Uint()) - } else if mi.fields.pk.rel { - return o.ReadOrCreate(vid.Interface(), mi.fields.pk.relModelInfo.fields.pk.name) - } else { - id = vid.Int() - } - - return false, id, err -} - -// insert model data to database -func (o *orm) Insert(md interface{}) (int64, error) { - mi, ind := o.getMiInd(md, true) - id, err := o.alias.DbBaser.Insert(o.db, mi, ind, o.alias.TZ) - if err != nil { - return id, err - } - - o.setPk(mi, ind, id) - - return id, nil -} - -// set auto pk field -func (o *orm) setPk(mi *modelInfo, ind reflect.Value, id int64) { - if mi.fields.pk.auto { - if mi.fields.pk.fieldType&IsPositiveIntegerField > 0 { - ind.FieldByIndex(mi.fields.pk.fieldIndex).SetUint(uint64(id)) - } else { - ind.FieldByIndex(mi.fields.pk.fieldIndex).SetInt(id) - } - } -} - -// insert some models to database -func (o *orm) InsertMulti(bulk int, mds interface{}) (int64, error) { - var cnt int64 - - sind := reflect.Indirect(reflect.ValueOf(mds)) - - switch sind.Kind() { - case reflect.Array, reflect.Slice: - if sind.Len() == 0 { - return cnt, ErrArgs - } - default: - return cnt, ErrArgs - } - - if bulk <= 1 { - for i := 0; i < sind.Len(); i++ { - ind := reflect.Indirect(sind.Index(i)) - mi, _ := o.getMiInd(ind.Interface(), false) - id, err := o.alias.DbBaser.Insert(o.db, mi, ind, o.alias.TZ) - if err != nil { - return cnt, err - } - - o.setPk(mi, ind, id) - - cnt++ - } - } else { - mi, _ := o.getMiInd(sind.Index(0).Interface(), false) - return o.alias.DbBaser.InsertMulti(o.db, mi, sind, bulk, o.alias.TZ) - } - return cnt, nil -} - -// InsertOrUpdate data to database -func (o *orm) InsertOrUpdate(md interface{}, colConflitAndArgs ...string) (int64, error) { - mi, ind := o.getMiInd(md, true) - id, err := o.alias.DbBaser.InsertOrUpdate(o.db, mi, ind, o.alias, colConflitAndArgs...) - if err != nil { - return id, err - } - - o.setPk(mi, ind, id) - - return id, nil -} - -// update model to database. -// cols set the columns those want to update. -func (o *orm) Update(md interface{}, cols ...string) (int64, error) { - mi, ind := o.getMiInd(md, true) - return o.alias.DbBaser.Update(o.db, mi, ind, o.alias.TZ, cols) -} - -// delete model in database -// cols shows the delete conditions values read from. default is pk -func (o *orm) Delete(md interface{}, cols ...string) (int64, error) { - mi, ind := o.getMiInd(md, true) - num, err := o.alias.DbBaser.Delete(o.db, mi, ind, o.alias.TZ, cols) - if err != nil { - return num, err - } - if num > 0 { - o.setPk(mi, ind, 0) - } - return num, nil -} - -// create a models to models queryer -func (o *orm) QueryM2M(md interface{}, name string) QueryM2Mer { - mi, ind := o.getMiInd(md, true) - fi := o.getFieldInfo(mi, name) - - switch { - case fi.fieldType == RelManyToMany: - case fi.fieldType == RelReverseMany && fi.reverseFieldInfo.mi.isThrough: - default: - panic(fmt.Errorf(" model `%s` . name `%s` is not a m2m field", fi.name, mi.fullName)) - } - - return newQueryM2M(md, o, mi, fi, ind) -} - -// load related models to md model. -// args are limit, offset int and order string. -// -// example: -// orm.LoadRelated(post,"Tags") -// for _,tag := range post.Tags{...} -// -// make sure the relation is defined in model struct tags. -func (o *orm) LoadRelated(md interface{}, name string, args ...interface{}) (int64, error) { - _, fi, ind, qseter := o.queryRelated(md, name) - - qs := qseter.(*querySet) - - var relDepth int - var limit, offset int64 - var order string - for i, arg := range args { - switch i { - case 0: - if v, ok := arg.(bool); ok { - if v { - relDepth = DefaultRelsDepth - } - } else if v, ok := arg.(int); ok { - relDepth = v - } - case 1: - limit = ToInt64(arg) - case 2: - offset = ToInt64(arg) - case 3: - order, _ = arg.(string) - } - } - - switch fi.fieldType { - case RelOneToOne, RelForeignKey, RelReverseOne: - limit = 1 - offset = 0 - } - - qs.limit = limit - qs.offset = offset - qs.relDepth = relDepth - - if len(order) > 0 { - qs.orders = []string{order} - } - - find := ind.FieldByIndex(fi.fieldIndex) - - var nums int64 - var err error - switch fi.fieldType { - case RelOneToOne, RelForeignKey, RelReverseOne: - val := reflect.New(find.Type().Elem()) - container := val.Interface() - err = qs.One(container) - if err == nil { - find.Set(val) - nums = 1 - } - default: - nums, err = qs.All(find.Addr().Interface()) - } - - return nums, err -} - -// return a QuerySeter for related models to md model. -// it can do all, update, delete in QuerySeter. -// example: -// qs := orm.QueryRelated(post,"Tag") -// qs.All(&[]*Tag{}) -// -func (o *orm) QueryRelated(md interface{}, name string) QuerySeter { - // is this api needed ? - _, _, _, qs := o.queryRelated(md, name) - return qs -} - -// get QuerySeter for related models to md model -func (o *orm) queryRelated(md interface{}, name string) (*modelInfo, *fieldInfo, reflect.Value, QuerySeter) { - mi, ind := o.getMiInd(md, true) - fi := o.getFieldInfo(mi, name) - - _, _, exist := getExistPk(mi, ind) - if !exist { - panic(ErrMissPK) - } - - var qs *querySet - - switch fi.fieldType { - case RelOneToOne, RelForeignKey, RelManyToMany: - if !fi.inModel { - break - } - qs = o.getRelQs(md, mi, fi) - case RelReverseOne, RelReverseMany: - if !fi.inModel { - break - } - qs = o.getReverseQs(md, mi, fi) - } - - if qs == nil { - panic(fmt.Errorf(" name `%s` for model `%s` is not an available rel/reverse field", md, name)) - } - - return mi, fi, ind, qs -} - -// get reverse relation QuerySeter -func (o *orm) getReverseQs(md interface{}, mi *modelInfo, fi *fieldInfo) *querySet { - switch fi.fieldType { - case RelReverseOne, RelReverseMany: - default: - panic(fmt.Errorf(" name `%s` for model `%s` is not an available reverse field", fi.name, mi.fullName)) - } - - var q *querySet - - if fi.fieldType == RelReverseMany && fi.reverseFieldInfo.mi.isThrough { - q = newQuerySet(o, fi.relModelInfo).(*querySet) - q.cond = NewCondition().And(fi.reverseFieldInfoM2M.column+ExprSep+fi.reverseFieldInfo.column, md) - } else { - q = newQuerySet(o, fi.reverseFieldInfo.mi).(*querySet) - q.cond = NewCondition().And(fi.reverseFieldInfo.column, md) - } - - return q -} - -// get relation QuerySeter -func (o *orm) getRelQs(md interface{}, mi *modelInfo, fi *fieldInfo) *querySet { - switch fi.fieldType { - case RelOneToOne, RelForeignKey, RelManyToMany: - default: - panic(fmt.Errorf(" name `%s` for model `%s` is not an available rel field", fi.name, mi.fullName)) - } - - q := newQuerySet(o, fi.relModelInfo).(*querySet) - q.cond = NewCondition() - - if fi.fieldType == RelManyToMany { - q.cond = q.cond.And(fi.reverseFieldInfoM2M.column+ExprSep+fi.reverseFieldInfo.column, md) - } else { - q.cond = q.cond.And(fi.reverseFieldInfo.column, md) - } - - return q -} - -// return a QuerySeter for table operations. -// table name can be string or struct. -// e.g. QueryTable("user"), QueryTable(&user{}) or QueryTable((*User)(nil)), -func (o *orm) QueryTable(ptrStructOrTableName interface{}) (qs QuerySeter) { - var name string - if table, ok := ptrStructOrTableName.(string); ok { - name = nameStrategyMap[defaultNameStrategy](table) - if mi, ok := modelCache.get(name); ok { - qs = newQuerySet(o, mi) - } - } else { - name = getFullName(indirectType(reflect.TypeOf(ptrStructOrTableName))) - if mi, ok := modelCache.getByFullName(name); ok { - qs = newQuerySet(o, mi) - } - } - if qs == nil { - panic(fmt.Errorf(" table name: `%s` not exists", name)) - } - return -} - -// switch to another registered database driver by given name. -func (o *orm) Using(name string) error { - if o.isTx { - panic(fmt.Errorf(" transaction has been start, cannot change db")) - } - if al, ok := dataBaseCache.get(name); ok { - o.alias = al - if Debug { - o.db = newDbQueryLog(al, al.DB) - } else { - o.db = al.DB - } - } else { - return fmt.Errorf(" unknown db alias name `%s`", name) - } - return nil -} - -// begin transaction -func (o *orm) Begin() error { - return o.BeginTx(context.Background(), nil) -} - -func (o *orm) BeginTx(ctx context.Context, opts *sql.TxOptions) error { - if o.isTx { - return ErrTxHasBegan - } - var tx *sql.Tx - tx, err := o.db.(txer).BeginTx(ctx, opts) - if err != nil { - return err - } - o.isTx = true - if Debug { - o.db.(*dbQueryLog).SetDB(tx) - } else { - o.db = tx - } - return nil -} - -// commit transaction -func (o *orm) Commit() error { - if !o.isTx { - return ErrTxDone - } - err := o.db.(txEnder).Commit() - if err == nil { - o.isTx = false - o.Using(o.alias.Name) - } else if err == sql.ErrTxDone { - return ErrTxDone - } - return err -} - -// rollback transaction -func (o *orm) Rollback() error { - if !o.isTx { - return ErrTxDone - } - err := o.db.(txEnder).Rollback() - if err == nil { - o.isTx = false - o.Using(o.alias.Name) - } else if err == sql.ErrTxDone { - return ErrTxDone - } - return err -} - -// return a raw query seter for raw sql string. -func (o *orm) Raw(query string, args ...interface{}) RawSeter { - return newRawSet(o, query, args) -} - -// return current using database Driver -func (o *orm) Driver() Driver { - return driver(o.alias.Name) -} - -// return sql.DBStats for current database -func (o *orm) DBStats() *sql.DBStats { - if o.alias != nil && o.alias.DB != nil { - stats := o.alias.DB.DB.Stats() - return &stats - } - return nil -} - -// NewOrm create new orm -func NewOrm() Ormer { - BootStrap() // execute only once - - o := new(orm) - err := o.Using("default") - if err != nil { - panic(err) - } - return o -} - -// NewOrmWithDB create a new ormer object with specify *sql.DB for query -func NewOrmWithDB(driverName, aliasName string, db *sql.DB) (Ormer, error) { - var al *alias - - if dr, ok := drivers[driverName]; ok { - al = new(alias) - al.DbBaser = dbBasers[dr] - al.Driver = dr - } else { - return nil, fmt.Errorf("driver name `%s` have not registered", driverName) - } - - al.Name = aliasName - al.DriverName = driverName - al.DB = &DB{ - RWMutex: new(sync.RWMutex), - DB: db, - stmtDecorators: newStmtDecoratorLruWithEvict(), - } - - detectTZ(al) - - o := new(orm) - o.alias = al - - if Debug { - o.db = newDbQueryLog(o.alias, db) - } else { - o.db = db - } - - return o, nil -} diff --git a/vendor/github.com/astaxie/beego/orm/orm_conds.go b/vendor/github.com/astaxie/beego/orm/orm_conds.go deleted file mode 100644 index f3fd66f0..00000000 --- a/vendor/github.com/astaxie/beego/orm/orm_conds.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "strings" -) - -// ExprSep define the expression separation -const ( - ExprSep = "__" -) - -type condValue struct { - exprs []string - args []interface{} - cond *Condition - isOr bool - isNot bool - isCond bool - isRaw bool - sql string -} - -// Condition struct. -// work for WHERE conditions. -type Condition struct { - params []condValue -} - -// NewCondition return new condition struct -func NewCondition() *Condition { - c := &Condition{} - return c -} - -// Raw add raw sql to condition -func (c Condition) Raw(expr string, sql string) *Condition { - if len(sql) == 0 { - panic(fmt.Errorf(" sql cannot empty")) - } - c.params = append(c.params, condValue{exprs: strings.Split(expr, ExprSep), sql: sql, isRaw: true}) - return &c -} - -// And add expression to condition -func (c Condition) And(expr string, args ...interface{}) *Condition { - if expr == "" || len(args) == 0 { - panic(fmt.Errorf(" args cannot empty")) - } - c.params = append(c.params, condValue{exprs: strings.Split(expr, ExprSep), args: args}) - return &c -} - -// AndNot add NOT expression to condition -func (c Condition) AndNot(expr string, args ...interface{}) *Condition { - if expr == "" || len(args) == 0 { - panic(fmt.Errorf(" args cannot empty")) - } - c.params = append(c.params, condValue{exprs: strings.Split(expr, ExprSep), args: args, isNot: true}) - return &c -} - -// AndCond combine a condition to current condition -func (c *Condition) AndCond(cond *Condition) *Condition { - c = c.clone() - if c == cond { - panic(fmt.Errorf(" cannot use self as sub cond")) - } - if cond != nil { - c.params = append(c.params, condValue{cond: cond, isCond: true}) - } - return c -} - -// AndNotCond combine a AND NOT condition to current condition -func (c *Condition) AndNotCond(cond *Condition) *Condition { - c = c.clone() - if c == cond { - panic(fmt.Errorf(" cannot use self as sub cond")) - } - - if cond != nil { - c.params = append(c.params, condValue{cond: cond, isCond: true, isNot: true}) - } - return c -} - -// Or add OR expression to condition -func (c Condition) Or(expr string, args ...interface{}) *Condition { - if expr == "" || len(args) == 0 { - panic(fmt.Errorf(" args cannot empty")) - } - c.params = append(c.params, condValue{exprs: strings.Split(expr, ExprSep), args: args, isOr: true}) - return &c -} - -// OrNot add OR NOT expression to condition -func (c Condition) OrNot(expr string, args ...interface{}) *Condition { - if expr == "" || len(args) == 0 { - panic(fmt.Errorf(" args cannot empty")) - } - c.params = append(c.params, condValue{exprs: strings.Split(expr, ExprSep), args: args, isNot: true, isOr: true}) - return &c -} - -// OrCond combine a OR condition to current condition -func (c *Condition) OrCond(cond *Condition) *Condition { - c = c.clone() - if c == cond { - panic(fmt.Errorf(" cannot use self as sub cond")) - } - if cond != nil { - c.params = append(c.params, condValue{cond: cond, isCond: true, isOr: true}) - } - return c -} - -// OrNotCond combine a OR NOT condition to current condition -func (c *Condition) OrNotCond(cond *Condition) *Condition { - c = c.clone() - if c == cond { - panic(fmt.Errorf(" cannot use self as sub cond")) - } - - if cond != nil { - c.params = append(c.params, condValue{cond: cond, isCond: true, isNot: true, isOr: true}) - } - return c -} - -// IsEmpty check the condition arguments are empty or not. -func (c *Condition) IsEmpty() bool { - return len(c.params) == 0 -} - -// clone clone a condition -func (c Condition) clone() *Condition { - return &c -} diff --git a/vendor/github.com/astaxie/beego/orm/orm_log.go b/vendor/github.com/astaxie/beego/orm/orm_log.go deleted file mode 100644 index 5bb3a24f..00000000 --- a/vendor/github.com/astaxie/beego/orm/orm_log.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "context" - "database/sql" - "fmt" - "io" - "log" - "strings" - "time" -) - -// Log implement the log.Logger -type Log struct { - *log.Logger -} - -//costomer log func -var LogFunc func(query map[string]interface{}) - -// NewLog set io.Writer to create a Logger. -func NewLog(out io.Writer) *Log { - d := new(Log) - d.Logger = log.New(out, "[ORM]", log.LstdFlags) - return d -} - -func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error, args ...interface{}) { - var logMap = make(map[string]interface{}) - sub := time.Now().Sub(t) / 1e5 - elsp := float64(int(sub)) / 10.0 - logMap["cost_time"] = elsp - flag := " OK" - if err != nil { - flag = "FAIL" - } - logMap["flag"] = flag - con := fmt.Sprintf(" -[Queries/%s] - [%s / %11s / %7.1fms] - [%s]", alias.Name, flag, operaton, elsp, query) - cons := make([]string, 0, len(args)) - for _, arg := range args { - cons = append(cons, fmt.Sprintf("%v", arg)) - } - if len(cons) > 0 { - con += fmt.Sprintf(" - `%s`", strings.Join(cons, "`, `")) - } - if err != nil { - con += " - " + err.Error() - } - logMap["sql"] = fmt.Sprintf("%s-`%s`", query, strings.Join(cons, "`, `")) - if LogFunc != nil { - LogFunc(logMap) - } - DebugLog.Println(con) -} - -// statement query logger struct. -// if dev mode, use stmtQueryLog, or use stmtQuerier. -type stmtQueryLog struct { - alias *alias - query string - stmt stmtQuerier -} - -var _ stmtQuerier = new(stmtQueryLog) - -func (d *stmtQueryLog) Close() error { - a := time.Now() - err := d.stmt.Close() - debugLogQueies(d.alias, "st.Close", d.query, a, err) - return err -} - -func (d *stmtQueryLog) Exec(args ...interface{}) (sql.Result, error) { - a := time.Now() - res, err := d.stmt.Exec(args...) - debugLogQueies(d.alias, "st.Exec", d.query, a, err, args...) - return res, err -} - -func (d *stmtQueryLog) Query(args ...interface{}) (*sql.Rows, error) { - a := time.Now() - res, err := d.stmt.Query(args...) - debugLogQueies(d.alias, "st.Query", d.query, a, err, args...) - return res, err -} - -func (d *stmtQueryLog) QueryRow(args ...interface{}) *sql.Row { - a := time.Now() - res := d.stmt.QueryRow(args...) - debugLogQueies(d.alias, "st.QueryRow", d.query, a, nil, args...) - return res -} - -func newStmtQueryLog(alias *alias, stmt stmtQuerier, query string) stmtQuerier { - d := new(stmtQueryLog) - d.stmt = stmt - d.alias = alias - d.query = query - return d -} - -// database query logger struct. -// if dev mode, use dbQueryLog, or use dbQuerier. -type dbQueryLog struct { - alias *alias - db dbQuerier - tx txer - txe txEnder -} - -var _ dbQuerier = new(dbQueryLog) -var _ txer = new(dbQueryLog) -var _ txEnder = new(dbQueryLog) - -func (d *dbQueryLog) Prepare(query string) (*sql.Stmt, error) { - a := time.Now() - stmt, err := d.db.Prepare(query) - debugLogQueies(d.alias, "db.Prepare", query, a, err) - return stmt, err -} - -func (d *dbQueryLog) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { - a := time.Now() - stmt, err := d.db.PrepareContext(ctx, query) - debugLogQueies(d.alias, "db.Prepare", query, a, err) - return stmt, err -} - -func (d *dbQueryLog) Exec(query string, args ...interface{}) (sql.Result, error) { - a := time.Now() - res, err := d.db.Exec(query, args...) - debugLogQueies(d.alias, "db.Exec", query, a, err, args...) - return res, err -} - -func (d *dbQueryLog) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { - a := time.Now() - res, err := d.db.ExecContext(ctx, query, args...) - debugLogQueies(d.alias, "db.Exec", query, a, err, args...) - return res, err -} - -func (d *dbQueryLog) Query(query string, args ...interface{}) (*sql.Rows, error) { - a := time.Now() - res, err := d.db.Query(query, args...) - debugLogQueies(d.alias, "db.Query", query, a, err, args...) - return res, err -} - -func (d *dbQueryLog) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { - a := time.Now() - res, err := d.db.QueryContext(ctx, query, args...) - debugLogQueies(d.alias, "db.Query", query, a, err, args...) - return res, err -} - -func (d *dbQueryLog) QueryRow(query string, args ...interface{}) *sql.Row { - a := time.Now() - res := d.db.QueryRow(query, args...) - debugLogQueies(d.alias, "db.QueryRow", query, a, nil, args...) - return res -} - -func (d *dbQueryLog) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row { - a := time.Now() - res := d.db.QueryRowContext(ctx, query, args...) - debugLogQueies(d.alias, "db.QueryRow", query, a, nil, args...) - return res -} - -func (d *dbQueryLog) Begin() (*sql.Tx, error) { - a := time.Now() - tx, err := d.db.(txer).Begin() - debugLogQueies(d.alias, "db.Begin", "START TRANSACTION", a, err) - return tx, err -} - -func (d *dbQueryLog) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) { - a := time.Now() - tx, err := d.db.(txer).BeginTx(ctx, opts) - debugLogQueies(d.alias, "db.BeginTx", "START TRANSACTION", a, err) - return tx, err -} - -func (d *dbQueryLog) Commit() error { - a := time.Now() - err := d.db.(txEnder).Commit() - debugLogQueies(d.alias, "tx.Commit", "COMMIT", a, err) - return err -} - -func (d *dbQueryLog) Rollback() error { - a := time.Now() - err := d.db.(txEnder).Rollback() - debugLogQueies(d.alias, "tx.Rollback", "ROLLBACK", a, err) - return err -} - -func (d *dbQueryLog) SetDB(db dbQuerier) { - d.db = db -} - -func newDbQueryLog(alias *alias, db dbQuerier) dbQuerier { - d := new(dbQueryLog) - d.alias = alias - d.db = db - return d -} diff --git a/vendor/github.com/astaxie/beego/orm/orm_object.go b/vendor/github.com/astaxie/beego/orm/orm_object.go deleted file mode 100644 index de3181ce..00000000 --- a/vendor/github.com/astaxie/beego/orm/orm_object.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "reflect" -) - -// an insert queryer struct -type insertSet struct { - mi *modelInfo - orm *orm - stmt stmtQuerier - closed bool -} - -var _ Inserter = new(insertSet) - -// insert model ignore it's registered or not. -func (o *insertSet) Insert(md interface{}) (int64, error) { - if o.closed { - return 0, ErrStmtClosed - } - val := reflect.ValueOf(md) - ind := reflect.Indirect(val) - typ := ind.Type() - name := getFullName(typ) - if val.Kind() != reflect.Ptr { - panic(fmt.Errorf(" cannot use non-ptr model struct `%s`", name)) - } - if name != o.mi.fullName { - panic(fmt.Errorf(" need model `%s` but found `%s`", o.mi.fullName, name)) - } - id, err := o.orm.alias.DbBaser.InsertStmt(o.stmt, o.mi, ind, o.orm.alias.TZ) - if err != nil { - return id, err - } - if id > 0 { - if o.mi.fields.pk.auto { - if o.mi.fields.pk.fieldType&IsPositiveIntegerField > 0 { - ind.FieldByIndex(o.mi.fields.pk.fieldIndex).SetUint(uint64(id)) - } else { - ind.FieldByIndex(o.mi.fields.pk.fieldIndex).SetInt(id) - } - } - } - return id, nil -} - -// close insert queryer statement -func (o *insertSet) Close() error { - if o.closed { - return ErrStmtClosed - } - o.closed = true - return o.stmt.Close() -} - -// create new insert queryer. -func newInsertSet(orm *orm, mi *modelInfo) (Inserter, error) { - bi := new(insertSet) - bi.orm = orm - bi.mi = mi - st, query, err := orm.alias.DbBaser.PrepareInsert(orm.db, mi) - if err != nil { - return nil, err - } - if Debug { - bi.stmt = newStmtQueryLog(orm.alias, st, query) - } else { - bi.stmt = st - } - return bi, nil -} diff --git a/vendor/github.com/astaxie/beego/orm/orm_querym2m.go b/vendor/github.com/astaxie/beego/orm/orm_querym2m.go deleted file mode 100644 index 6a270a0d..00000000 --- a/vendor/github.com/astaxie/beego/orm/orm_querym2m.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import "reflect" - -// model to model struct -type queryM2M struct { - md interface{} - mi *modelInfo - fi *fieldInfo - qs *querySet - ind reflect.Value -} - -// add models to origin models when creating queryM2M. -// example: -// m2m := orm.QueryM2M(post,"Tag") -// m2m.Add(&Tag1{},&Tag2{}) -// for _,tag := range post.Tags{} -// -// make sure the relation is defined in post model struct tag. -func (o *queryM2M) Add(mds ...interface{}) (int64, error) { - fi := o.fi - mi := fi.relThroughModelInfo - mfi := fi.reverseFieldInfo - rfi := fi.reverseFieldInfoTwo - - orm := o.qs.orm - dbase := orm.alias.DbBaser - - var models []interface{} - var otherValues []interface{} - var otherNames []string - - for _, colname := range mi.fields.dbcols { - if colname != mfi.column && colname != rfi.column && colname != fi.mi.fields.pk.column && - mi.fields.columns[colname] != mi.fields.pk { - otherNames = append(otherNames, colname) - } - } - for i, md := range mds { - if reflect.Indirect(reflect.ValueOf(md)).Kind() != reflect.Struct && i > 0 { - otherValues = append(otherValues, md) - mds = append(mds[:i], mds[i+1:]...) - } - } - for _, md := range mds { - val := reflect.ValueOf(md) - if val.Kind() == reflect.Slice || val.Kind() == reflect.Array { - for i := 0; i < val.Len(); i++ { - v := val.Index(i) - if v.CanInterface() { - models = append(models, v.Interface()) - } - } - } else { - models = append(models, md) - } - } - - _, v1, exist := getExistPk(o.mi, o.ind) - if !exist { - panic(ErrMissPK) - } - - names := []string{mfi.column, rfi.column} - - values := make([]interface{}, 0, len(models)*2) - for _, md := range models { - - ind := reflect.Indirect(reflect.ValueOf(md)) - var v2 interface{} - if ind.Kind() != reflect.Struct { - v2 = ind.Interface() - } else { - _, v2, exist = getExistPk(fi.relModelInfo, ind) - if !exist { - panic(ErrMissPK) - } - } - values = append(values, v1, v2) - - } - names = append(names, otherNames...) - values = append(values, otherValues...) - return dbase.InsertValue(orm.db, mi, true, names, values) -} - -// remove models following the origin model relationship -func (o *queryM2M) Remove(mds ...interface{}) (int64, error) { - fi := o.fi - qs := o.qs.Filter(fi.reverseFieldInfo.name, o.md) - - return qs.Filter(fi.reverseFieldInfoTwo.name+ExprSep+"in", mds).Delete() -} - -// check model is existed in relationship of origin model -func (o *queryM2M) Exist(md interface{}) bool { - fi := o.fi - return o.qs.Filter(fi.reverseFieldInfo.name, o.md). - Filter(fi.reverseFieldInfoTwo.name, md).Exist() -} - -// clean all models in related of origin model -func (o *queryM2M) Clear() (int64, error) { - fi := o.fi - return o.qs.Filter(fi.reverseFieldInfo.name, o.md).Delete() -} - -// count all related models of origin model -func (o *queryM2M) Count() (int64, error) { - fi := o.fi - return o.qs.Filter(fi.reverseFieldInfo.name, o.md).Count() -} - -var _ QueryM2Mer = new(queryM2M) - -// create new M2M queryer. -func newQueryM2M(md interface{}, o *orm, mi *modelInfo, fi *fieldInfo, ind reflect.Value) QueryM2Mer { - qm2m := new(queryM2M) - qm2m.md = md - qm2m.mi = mi - qm2m.fi = fi - qm2m.ind = ind - qm2m.qs = newQuerySet(o, fi.relThroughModelInfo).(*querySet) - return qm2m -} diff --git a/vendor/github.com/astaxie/beego/orm/orm_queryset.go b/vendor/github.com/astaxie/beego/orm/orm_queryset.go deleted file mode 100644 index 878b836b..00000000 --- a/vendor/github.com/astaxie/beego/orm/orm_queryset.go +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "context" - "fmt" -) - -type colValue struct { - value int64 - opt operator -} - -type operator int - -// define Col operations -const ( - ColAdd operator = iota - ColMinus - ColMultiply - ColExcept - ColBitAnd - ColBitRShift - ColBitLShift - ColBitXOR - ColBitOr -) - -// ColValue do the field raw changes. e.g Nums = Nums + 10. usage: -// Params{ -// "Nums": ColValue(Col_Add, 10), -// } -func ColValue(opt operator, value interface{}) interface{} { - switch opt { - case ColAdd, ColMinus, ColMultiply, ColExcept, ColBitAnd, ColBitRShift, - ColBitLShift, ColBitXOR, ColBitOr: - default: - panic(fmt.Errorf("orm.ColValue wrong operator")) - } - v, err := StrTo(ToStr(value)).Int64() - if err != nil { - panic(fmt.Errorf("orm.ColValue doesn't support non string/numeric type, %s", err)) - } - var val colValue - val.value = v - val.opt = opt - return val -} - -// real query struct -type querySet struct { - mi *modelInfo - cond *Condition - related []string - relDepth int - limit int64 - offset int64 - groups []string - orders []string - distinct bool - forupdate bool - orm *orm - ctx context.Context - forContext bool -} - -var _ QuerySeter = new(querySet) - -// add condition expression to QuerySeter. -func (o querySet) Filter(expr string, args ...interface{}) QuerySeter { - if o.cond == nil { - o.cond = NewCondition() - } - o.cond = o.cond.And(expr, args...) - return &o -} - -// add raw sql to querySeter. -func (o querySet) FilterRaw(expr string, sql string) QuerySeter { - if o.cond == nil { - o.cond = NewCondition() - } - o.cond = o.cond.Raw(expr, sql) - return &o -} - -// add NOT condition to querySeter. -func (o querySet) Exclude(expr string, args ...interface{}) QuerySeter { - if o.cond == nil { - o.cond = NewCondition() - } - o.cond = o.cond.AndNot(expr, args...) - return &o -} - -// set offset number -func (o *querySet) setOffset(num interface{}) { - o.offset = ToInt64(num) -} - -// add LIMIT value. -// args[0] means offset, e.g. LIMIT num,offset. -func (o querySet) Limit(limit interface{}, args ...interface{}) QuerySeter { - o.limit = ToInt64(limit) - if len(args) > 0 { - o.setOffset(args[0]) - } - return &o -} - -// add OFFSET value -func (o querySet) Offset(offset interface{}) QuerySeter { - o.setOffset(offset) - return &o -} - -// add GROUP expression -func (o querySet) GroupBy(exprs ...string) QuerySeter { - o.groups = exprs - return &o -} - -// add ORDER expression. -// "column" means ASC, "-column" means DESC. -func (o querySet) OrderBy(exprs ...string) QuerySeter { - o.orders = exprs - return &o -} - -// add DISTINCT to SELECT -func (o querySet) Distinct() QuerySeter { - o.distinct = true - return &o -} - -// add FOR UPDATE to SELECT -func (o querySet) ForUpdate() QuerySeter { - o.forupdate = true - return &o -} - -// set relation model to query together. -// it will query relation models and assign to parent model. -func (o querySet) RelatedSel(params ...interface{}) QuerySeter { - if len(params) == 0 { - o.relDepth = DefaultRelsDepth - } else { - for _, p := range params { - switch val := p.(type) { - case string: - o.related = append(o.related, val) - case int: - o.relDepth = val - default: - panic(fmt.Errorf(" wrong param kind: %v", val)) - } - } - } - return &o -} - -// set condition to QuerySeter. -func (o querySet) SetCond(cond *Condition) QuerySeter { - o.cond = cond - return &o -} - -// get condition from QuerySeter -func (o querySet) GetCond() *Condition { - return o.cond -} - -// return QuerySeter execution result number -func (o *querySet) Count() (int64, error) { - return o.orm.alias.DbBaser.Count(o.orm.db, o, o.mi, o.cond, o.orm.alias.TZ) -} - -// check result empty or not after QuerySeter executed -func (o *querySet) Exist() bool { - cnt, _ := o.orm.alias.DbBaser.Count(o.orm.db, o, o.mi, o.cond, o.orm.alias.TZ) - return cnt > 0 -} - -// execute update with parameters -func (o *querySet) Update(values Params) (int64, error) { - return o.orm.alias.DbBaser.UpdateBatch(o.orm.db, o, o.mi, o.cond, values, o.orm.alias.TZ) -} - -// execute delete -func (o *querySet) Delete() (int64, error) { - return o.orm.alias.DbBaser.DeleteBatch(o.orm.db, o, o.mi, o.cond, o.orm.alias.TZ) -} - -// return a insert queryer. -// it can be used in times. -// example: -// i,err := sq.PrepareInsert() -// i.Add(&user1{},&user2{}) -func (o *querySet) PrepareInsert() (Inserter, error) { - return newInsertSet(o.orm, o.mi) -} - -// query all data and map to containers. -// cols means the columns when querying. -func (o *querySet) All(container interface{}, cols ...string) (int64, error) { - return o.orm.alias.DbBaser.ReadBatch(o.orm.db, o, o.mi, o.cond, container, o.orm.alias.TZ, cols) -} - -// query one row data and map to containers. -// cols means the columns when querying. -func (o *querySet) One(container interface{}, cols ...string) error { - o.limit = 1 - num, err := o.orm.alias.DbBaser.ReadBatch(o.orm.db, o, o.mi, o.cond, container, o.orm.alias.TZ, cols) - if err != nil { - return err - } - if num == 0 { - return ErrNoRows - } - - if num > 1 { - return ErrMultiRows - } - return nil -} - -// query all data and map to []map[string]interface. -// expres means condition expression. -// it converts data to []map[column]value. -func (o *querySet) Values(results *[]Params, exprs ...string) (int64, error) { - return o.orm.alias.DbBaser.ReadValues(o.orm.db, o, o.mi, o.cond, exprs, results, o.orm.alias.TZ) -} - -// query all data and map to [][]interface -// it converts data to [][column_index]value -func (o *querySet) ValuesList(results *[]ParamsList, exprs ...string) (int64, error) { - return o.orm.alias.DbBaser.ReadValues(o.orm.db, o, o.mi, o.cond, exprs, results, o.orm.alias.TZ) -} - -// query all data and map to []interface. -// it's designed for one row record set, auto change to []value, not [][column]value. -func (o *querySet) ValuesFlat(result *ParamsList, expr string) (int64, error) { - return o.orm.alias.DbBaser.ReadValues(o.orm.db, o, o.mi, o.cond, []string{expr}, result, o.orm.alias.TZ) -} - -// query all rows into map[string]interface with specify key and value column name. -// keyCol = "name", valueCol = "value" -// table data -// name | value -// total | 100 -// found | 200 -// to map[string]interface{}{ -// "total": 100, -// "found": 200, -// } -func (o *querySet) RowsToMap(result *Params, keyCol, valueCol string) (int64, error) { - panic(ErrNotImplement) -} - -// query all rows into struct with specify key and value column name. -// keyCol = "name", valueCol = "value" -// table data -// name | value -// total | 100 -// found | 200 -// to struct { -// Total int -// Found int -// } -func (o *querySet) RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) { - panic(ErrNotImplement) -} - -// set context to QuerySeter. -func (o querySet) WithContext(ctx context.Context) QuerySeter { - o.ctx = ctx - o.forContext = true - return &o -} - -// create new QuerySeter. -func newQuerySet(orm *orm, mi *modelInfo) QuerySeter { - o := new(querySet) - o.mi = mi - o.orm = orm - return o -} diff --git a/vendor/github.com/astaxie/beego/orm/orm_raw.go b/vendor/github.com/astaxie/beego/orm/orm_raw.go deleted file mode 100644 index 1bdefc78..00000000 --- a/vendor/github.com/astaxie/beego/orm/orm_raw.go +++ /dev/null @@ -1,885 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "database/sql" - "fmt" - "reflect" - "time" - - "github.com/pkg/errors" -) - -// raw sql string prepared statement -type rawPrepare struct { - rs *rawSet - stmt stmtQuerier - closed bool -} - -func (o *rawPrepare) Exec(args ...interface{}) (sql.Result, error) { - if o.closed { - return nil, ErrStmtClosed - } - return o.stmt.Exec(args...) -} - -func (o *rawPrepare) Close() error { - o.closed = true - return o.stmt.Close() -} - -func newRawPreparer(rs *rawSet) (RawPreparer, error) { - o := new(rawPrepare) - o.rs = rs - - query := rs.query - rs.orm.alias.DbBaser.ReplaceMarks(&query) - - st, err := rs.orm.db.Prepare(query) - if err != nil { - return nil, err - } - if Debug { - o.stmt = newStmtQueryLog(rs.orm.alias, st, query) - } else { - o.stmt = st - } - return o, nil -} - -// raw query seter -type rawSet struct { - query string - args []interface{} - orm *orm -} - -var _ RawSeter = new(rawSet) - -// set args for every query -func (o rawSet) SetArgs(args ...interface{}) RawSeter { - o.args = args - return &o -} - -// execute raw sql and return sql.Result -func (o *rawSet) Exec() (sql.Result, error) { - query := o.query - o.orm.alias.DbBaser.ReplaceMarks(&query) - - args := getFlatParams(nil, o.args, o.orm.alias.TZ) - return o.orm.db.Exec(query, args...) -} - -// set field value to row container -func (o *rawSet) setFieldValue(ind reflect.Value, value interface{}) { - switch ind.Kind() { - case reflect.Bool: - if value == nil { - ind.SetBool(false) - } else if v, ok := value.(bool); ok { - ind.SetBool(v) - } else { - v, _ := StrTo(ToStr(value)).Bool() - ind.SetBool(v) - } - - case reflect.String: - if value == nil { - ind.SetString("") - } else { - ind.SetString(ToStr(value)) - } - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if value == nil { - ind.SetInt(0) - } else { - val := reflect.ValueOf(value) - switch val.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - ind.SetInt(val.Int()) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - ind.SetInt(int64(val.Uint())) - default: - v, _ := StrTo(ToStr(value)).Int64() - ind.SetInt(v) - } - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - if value == nil { - ind.SetUint(0) - } else { - val := reflect.ValueOf(value) - switch val.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - ind.SetUint(uint64(val.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - ind.SetUint(val.Uint()) - default: - v, _ := StrTo(ToStr(value)).Uint64() - ind.SetUint(v) - } - } - case reflect.Float64, reflect.Float32: - if value == nil { - ind.SetFloat(0) - } else { - val := reflect.ValueOf(value) - switch val.Kind() { - case reflect.Float64: - ind.SetFloat(val.Float()) - default: - v, _ := StrTo(ToStr(value)).Float64() - ind.SetFloat(v) - } - } - - case reflect.Struct: - if value == nil { - ind.Set(reflect.Zero(ind.Type())) - return - } - switch ind.Interface().(type) { - case time.Time: - var str string - switch d := value.(type) { - case time.Time: - o.orm.alias.DbBaser.TimeFromDB(&d, o.orm.alias.TZ) - ind.Set(reflect.ValueOf(d)) - case []byte: - str = string(d) - case string: - str = d - } - if str != "" { - if len(str) >= 19 { - str = str[:19] - t, err := time.ParseInLocation(formatDateTime, str, o.orm.alias.TZ) - if err == nil { - t = t.In(DefaultTimeLoc) - ind.Set(reflect.ValueOf(t)) - } - } else if len(str) >= 10 { - str = str[:10] - t, err := time.ParseInLocation(formatDate, str, DefaultTimeLoc) - if err == nil { - ind.Set(reflect.ValueOf(t)) - } - } - } - case sql.NullString, sql.NullInt64, sql.NullFloat64, sql.NullBool: - indi := reflect.New(ind.Type()).Interface() - sc, ok := indi.(sql.Scanner) - if !ok { - return - } - err := sc.Scan(value) - if err == nil { - ind.Set(reflect.Indirect(reflect.ValueOf(sc))) - } - } - - case reflect.Ptr: - if value == nil { - ind.Set(reflect.Zero(ind.Type())) - break - } - ind.Set(reflect.New(ind.Type().Elem())) - o.setFieldValue(reflect.Indirect(ind), value) - } -} - -// set field value in loop for slice container -func (o *rawSet) loopSetRefs(refs []interface{}, sInds []reflect.Value, nIndsPtr *[]reflect.Value, eTyps []reflect.Type, init bool) { - nInds := *nIndsPtr - - cur := 0 - for i := 0; i < len(sInds); i++ { - sInd := sInds[i] - eTyp := eTyps[i] - - typ := eTyp - isPtr := false - if typ.Kind() == reflect.Ptr { - isPtr = true - typ = typ.Elem() - } - if typ.Kind() == reflect.Ptr { - isPtr = true - typ = typ.Elem() - } - - var nInd reflect.Value - if init { - nInd = reflect.New(sInd.Type()).Elem() - } else { - nInd = nInds[i] - } - - val := reflect.New(typ) - ind := val.Elem() - - tpName := ind.Type().String() - - if ind.Kind() == reflect.Struct { - if tpName == "time.Time" { - value := reflect.ValueOf(refs[cur]).Elem().Interface() - if isPtr && value == nil { - val = reflect.New(val.Type()).Elem() - } else { - o.setFieldValue(ind, value) - } - cur++ - } - - } else { - value := reflect.ValueOf(refs[cur]).Elem().Interface() - if isPtr && value == nil { - val = reflect.New(val.Type()).Elem() - } else { - o.setFieldValue(ind, value) - } - cur++ - } - - if nInd.Kind() == reflect.Slice { - if isPtr { - nInd = reflect.Append(nInd, val) - } else { - nInd = reflect.Append(nInd, ind) - } - } else { - if isPtr { - nInd.Set(val) - } else { - nInd.Set(ind) - } - } - - nInds[i] = nInd - } -} - -// query data and map to container -func (o *rawSet) QueryRow(containers ...interface{}) error { - var ( - refs = make([]interface{}, 0, len(containers)) - sInds []reflect.Value - eTyps []reflect.Type - sMi *modelInfo - ) - structMode := false - for _, container := range containers { - val := reflect.ValueOf(container) - ind := reflect.Indirect(val) - - if val.Kind() != reflect.Ptr { - panic(fmt.Errorf(" all args must be use ptr")) - } - - etyp := ind.Type() - typ := etyp - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - } - - sInds = append(sInds, ind) - eTyps = append(eTyps, etyp) - - if typ.Kind() == reflect.Struct && typ.String() != "time.Time" { - if len(containers) > 1 { - panic(fmt.Errorf(" now support one struct only. see #384")) - } - - structMode = true - fn := getFullName(typ) - if mi, ok := modelCache.getByFullName(fn); ok { - sMi = mi - } - } else { - var ref interface{} - refs = append(refs, &ref) - } - } - - query := o.query - o.orm.alias.DbBaser.ReplaceMarks(&query) - - args := getFlatParams(nil, o.args, o.orm.alias.TZ) - rows, err := o.orm.db.Query(query, args...) - if err != nil { - if err == sql.ErrNoRows { - return ErrNoRows - } - return err - } - - defer rows.Close() - - if rows.Next() { - if structMode { - columns, err := rows.Columns() - if err != nil { - return err - } - - columnsMp := make(map[string]interface{}, len(columns)) - - refs = make([]interface{}, 0, len(columns)) - for _, col := range columns { - var ref interface{} - columnsMp[col] = &ref - refs = append(refs, &ref) - } - - if err := rows.Scan(refs...); err != nil { - return err - } - - ind := sInds[0] - - if ind.Kind() == reflect.Ptr { - if ind.IsNil() || !ind.IsValid() { - ind.Set(reflect.New(eTyps[0].Elem())) - } - ind = ind.Elem() - } - - if sMi != nil { - for _, col := range columns { - if fi := sMi.fields.GetByColumn(col); fi != nil { - value := reflect.ValueOf(columnsMp[col]).Elem().Interface() - field := ind.FieldByIndex(fi.fieldIndex) - if fi.fieldType&IsRelField > 0 { - mf := reflect.New(fi.relModelInfo.addrField.Elem().Type()) - field.Set(mf) - field = mf.Elem().FieldByIndex(fi.relModelInfo.fields.pk.fieldIndex) - } - if fi.isFielder { - fd := field.Addr().Interface().(Fielder) - err := fd.SetRaw(value) - if err != nil { - return errors.Errorf("set raw error:%s", err) - } - } else { - o.setFieldValue(field, value) - } - } - } - } else { - for i := 0; i < ind.NumField(); i++ { - f := ind.Field(i) - fe := ind.Type().Field(i) - _, tags := parseStructTag(fe.Tag.Get(defaultStructTagName)) - var col string - if col = tags["column"]; col == "" { - col = nameStrategyMap[nameStrategy](fe.Name) - } - if v, ok := columnsMp[col]; ok { - value := reflect.ValueOf(v).Elem().Interface() - o.setFieldValue(f, value) - } - } - } - - } else { - if err := rows.Scan(refs...); err != nil { - return err - } - - nInds := make([]reflect.Value, len(sInds)) - o.loopSetRefs(refs, sInds, &nInds, eTyps, true) - for i, sInd := range sInds { - nInd := nInds[i] - sInd.Set(nInd) - } - } - - } else { - return ErrNoRows - } - - return nil -} - -// query data rows and map to container -func (o *rawSet) QueryRows(containers ...interface{}) (int64, error) { - var ( - refs = make([]interface{}, 0, len(containers)) - sInds []reflect.Value - eTyps []reflect.Type - sMi *modelInfo - ) - structMode := false - for _, container := range containers { - val := reflect.ValueOf(container) - sInd := reflect.Indirect(val) - if val.Kind() != reflect.Ptr || sInd.Kind() != reflect.Slice { - panic(fmt.Errorf(" all args must be use ptr slice")) - } - - etyp := sInd.Type().Elem() - typ := etyp - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - } - - sInds = append(sInds, sInd) - eTyps = append(eTyps, etyp) - - if typ.Kind() == reflect.Struct && typ.String() != "time.Time" { - if len(containers) > 1 { - panic(fmt.Errorf(" now support one struct only. see #384")) - } - - structMode = true - fn := getFullName(typ) - if mi, ok := modelCache.getByFullName(fn); ok { - sMi = mi - } - } else { - var ref interface{} - refs = append(refs, &ref) - } - } - - query := o.query - o.orm.alias.DbBaser.ReplaceMarks(&query) - - args := getFlatParams(nil, o.args, o.orm.alias.TZ) - rows, err := o.orm.db.Query(query, args...) - if err != nil { - return 0, err - } - - defer rows.Close() - - var cnt int64 - nInds := make([]reflect.Value, len(sInds)) - sInd := sInds[0] - - for rows.Next() { - - if structMode { - columns, err := rows.Columns() - if err != nil { - return 0, err - } - - columnsMp := make(map[string]interface{}, len(columns)) - - refs = make([]interface{}, 0, len(columns)) - for _, col := range columns { - var ref interface{} - columnsMp[col] = &ref - refs = append(refs, &ref) - } - - if err := rows.Scan(refs...); err != nil { - return 0, err - } - - if cnt == 0 && !sInd.IsNil() { - sInd.Set(reflect.New(sInd.Type()).Elem()) - } - - var ind reflect.Value - if eTyps[0].Kind() == reflect.Ptr { - ind = reflect.New(eTyps[0].Elem()) - } else { - ind = reflect.New(eTyps[0]) - } - - if ind.Kind() == reflect.Ptr { - ind = ind.Elem() - } - - if sMi != nil { - for _, col := range columns { - if fi := sMi.fields.GetByColumn(col); fi != nil { - value := reflect.ValueOf(columnsMp[col]).Elem().Interface() - field := ind.FieldByIndex(fi.fieldIndex) - if fi.fieldType&IsRelField > 0 { - mf := reflect.New(fi.relModelInfo.addrField.Elem().Type()) - field.Set(mf) - field = mf.Elem().FieldByIndex(fi.relModelInfo.fields.pk.fieldIndex) - } - if fi.isFielder { - fd := field.Addr().Interface().(Fielder) - err := fd.SetRaw(value) - if err != nil { - return 0, errors.Errorf("set raw error:%s", err) - } - } else { - o.setFieldValue(field, value) - } - } - } - } else { - // define recursive function - var recursiveSetField func(rv reflect.Value) - recursiveSetField = func(rv reflect.Value) { - for i := 0; i < rv.NumField(); i++ { - f := rv.Field(i) - fe := rv.Type().Field(i) - - // check if the field is a Struct - // recursive the Struct type - if fe.Type.Kind() == reflect.Struct { - recursiveSetField(f) - } - - _, tags := parseStructTag(fe.Tag.Get(defaultStructTagName)) - var col string - if col = tags["column"]; col == "" { - col = nameStrategyMap[nameStrategy](fe.Name) - } - if v, ok := columnsMp[col]; ok { - value := reflect.ValueOf(v).Elem().Interface() - o.setFieldValue(f, value) - } - } - } - - // init call the recursive function - recursiveSetField(ind) - } - - if eTyps[0].Kind() == reflect.Ptr { - ind = ind.Addr() - } - - sInd = reflect.Append(sInd, ind) - - } else { - if err := rows.Scan(refs...); err != nil { - return 0, err - } - - o.loopSetRefs(refs, sInds, &nInds, eTyps, cnt == 0) - } - - cnt++ - } - - if cnt > 0 { - - if structMode { - sInds[0].Set(sInd) - } else { - for i, sInd := range sInds { - nInd := nInds[i] - sInd.Set(nInd) - } - } - } - - return cnt, nil -} - -func (o *rawSet) readValues(container interface{}, needCols []string) (int64, error) { - var ( - maps []Params - lists []ParamsList - list ParamsList - ) - - typ := 0 - switch container.(type) { - case *[]Params: - typ = 1 - case *[]ParamsList: - typ = 2 - case *ParamsList: - typ = 3 - default: - panic(fmt.Errorf(" unsupport read values type `%T`", container)) - } - - query := o.query - o.orm.alias.DbBaser.ReplaceMarks(&query) - - args := getFlatParams(nil, o.args, o.orm.alias.TZ) - - var rs *sql.Rows - rs, err := o.orm.db.Query(query, args...) - if err != nil { - return 0, err - } - - defer rs.Close() - - var ( - refs []interface{} - cnt int64 - cols []string - indexs []int - ) - - for rs.Next() { - if cnt == 0 { - columns, err := rs.Columns() - if err != nil { - return 0, err - } - if len(needCols) > 0 { - indexs = make([]int, 0, len(needCols)) - } else { - indexs = make([]int, 0, len(columns)) - } - - cols = columns - refs = make([]interface{}, len(cols)) - for i := range refs { - var ref sql.NullString - refs[i] = &ref - - if len(needCols) > 0 { - for _, c := range needCols { - if c == cols[i] { - indexs = append(indexs, i) - } - } - } else { - indexs = append(indexs, i) - } - } - } - - if err := rs.Scan(refs...); err != nil { - return 0, err - } - - switch typ { - case 1: - params := make(Params, len(cols)) - for _, i := range indexs { - ref := refs[i] - value := reflect.Indirect(reflect.ValueOf(ref)).Interface().(sql.NullString) - if value.Valid { - params[cols[i]] = value.String - } else { - params[cols[i]] = nil - } - } - maps = append(maps, params) - case 2: - params := make(ParamsList, 0, len(cols)) - for _, i := range indexs { - ref := refs[i] - value := reflect.Indirect(reflect.ValueOf(ref)).Interface().(sql.NullString) - if value.Valid { - params = append(params, value.String) - } else { - params = append(params, nil) - } - } - lists = append(lists, params) - case 3: - for _, i := range indexs { - ref := refs[i] - value := reflect.Indirect(reflect.ValueOf(ref)).Interface().(sql.NullString) - if value.Valid { - list = append(list, value.String) - } else { - list = append(list, nil) - } - } - } - - cnt++ - } - - switch v := container.(type) { - case *[]Params: - *v = maps - case *[]ParamsList: - *v = lists - case *ParamsList: - *v = list - } - - return cnt, nil -} - -func (o *rawSet) queryRowsTo(container interface{}, keyCol, valueCol string) (int64, error) { - var ( - maps Params - ind *reflect.Value - ) - - var typ int - switch container.(type) { - case *Params: - typ = 1 - default: - typ = 2 - vl := reflect.ValueOf(container) - id := reflect.Indirect(vl) - if vl.Kind() != reflect.Ptr || id.Kind() != reflect.Struct { - panic(fmt.Errorf(" RowsTo unsupport type `%T` need ptr struct", container)) - } - - ind = &id - } - - query := o.query - o.orm.alias.DbBaser.ReplaceMarks(&query) - - args := getFlatParams(nil, o.args, o.orm.alias.TZ) - - rs, err := o.orm.db.Query(query, args...) - if err != nil { - return 0, err - } - - defer rs.Close() - - var ( - refs []interface{} - cnt int64 - cols []string - ) - - var ( - keyIndex = -1 - valueIndex = -1 - ) - - for rs.Next() { - if cnt == 0 { - columns, err := rs.Columns() - if err != nil { - return 0, err - } - cols = columns - refs = make([]interface{}, len(cols)) - for i := range refs { - if keyCol == cols[i] { - keyIndex = i - } - if typ == 1 || keyIndex == i { - var ref sql.NullString - refs[i] = &ref - } else { - var ref interface{} - refs[i] = &ref - } - if valueCol == cols[i] { - valueIndex = i - } - } - if keyIndex == -1 || valueIndex == -1 { - panic(fmt.Errorf(" RowsTo unknown key, value column name `%s: %s`", keyCol, valueCol)) - } - } - - if err := rs.Scan(refs...); err != nil { - return 0, err - } - - if cnt == 0 { - switch typ { - case 1: - maps = make(Params) - } - } - - key := reflect.Indirect(reflect.ValueOf(refs[keyIndex])).Interface().(sql.NullString).String - - switch typ { - case 1: - value := reflect.Indirect(reflect.ValueOf(refs[valueIndex])).Interface().(sql.NullString) - if value.Valid { - maps[key] = value.String - } else { - maps[key] = nil - } - - default: - if id := ind.FieldByName(camelString(key)); id.IsValid() { - o.setFieldValue(id, reflect.ValueOf(refs[valueIndex]).Elem().Interface()) - } - } - - cnt++ - } - - if typ == 1 { - v, _ := container.(*Params) - *v = maps - } - - return cnt, nil -} - -// query data to []map[string]interface -func (o *rawSet) Values(container *[]Params, cols ...string) (int64, error) { - return o.readValues(container, cols) -} - -// query data to [][]interface -func (o *rawSet) ValuesList(container *[]ParamsList, cols ...string) (int64, error) { - return o.readValues(container, cols) -} - -// query data to []interface -func (o *rawSet) ValuesFlat(container *ParamsList, cols ...string) (int64, error) { - return o.readValues(container, cols) -} - -// query all rows into map[string]interface with specify key and value column name. -// keyCol = "name", valueCol = "value" -// table data -// name | value -// total | 100 -// found | 200 -// to map[string]interface{}{ -// "total": 100, -// "found": 200, -// } -func (o *rawSet) RowsToMap(result *Params, keyCol, valueCol string) (int64, error) { - return o.queryRowsTo(result, keyCol, valueCol) -} - -// query all rows into struct with specify key and value column name. -// keyCol = "name", valueCol = "value" -// table data -// name | value -// total | 100 -// found | 200 -// to struct { -// Total int -// Found int -// } -func (o *rawSet) RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) { - return o.queryRowsTo(ptrStruct, keyCol, valueCol) -} - -// return prepared raw statement for used in times. -func (o *rawSet) Prepare() (RawPreparer, error) { - return newRawPreparer(o) -} - -func newRawSet(orm *orm, query string, args []interface{}) RawSeter { - o := new(rawSet) - o.query = query - o.args = args - o.orm = orm - return o -} diff --git a/vendor/github.com/astaxie/beego/orm/qb.go b/vendor/github.com/astaxie/beego/orm/qb.go deleted file mode 100644 index e0655a17..00000000 --- a/vendor/github.com/astaxie/beego/orm/qb.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import "errors" - -// QueryBuilder is the Query builder interface -type QueryBuilder interface { - Select(fields ...string) QueryBuilder - ForUpdate() QueryBuilder - From(tables ...string) QueryBuilder - InnerJoin(table string) QueryBuilder - LeftJoin(table string) QueryBuilder - RightJoin(table string) QueryBuilder - On(cond string) QueryBuilder - Where(cond string) QueryBuilder - And(cond string) QueryBuilder - Or(cond string) QueryBuilder - In(vals ...string) QueryBuilder - OrderBy(fields ...string) QueryBuilder - Asc() QueryBuilder - Desc() QueryBuilder - Limit(limit int) QueryBuilder - Offset(offset int) QueryBuilder - GroupBy(fields ...string) QueryBuilder - Having(cond string) QueryBuilder - Update(tables ...string) QueryBuilder - Set(kv ...string) QueryBuilder - Delete(tables ...string) QueryBuilder - InsertInto(table string, fields ...string) QueryBuilder - Values(vals ...string) QueryBuilder - Subquery(sub string, alias string) string - String() string -} - -// NewQueryBuilder return the QueryBuilder -func NewQueryBuilder(driver string) (qb QueryBuilder, err error) { - if driver == "mysql" { - qb = new(MySQLQueryBuilder) - } else if driver == "tidb" { - qb = new(TiDBQueryBuilder) - } else if driver == "postgres" { - err = errors.New("postgres query builder is not supported yet") - } else if driver == "sqlite" { - err = errors.New("sqlite query builder is not supported yet") - } else { - err = errors.New("unknown driver for query builder") - } - return -} diff --git a/vendor/github.com/astaxie/beego/orm/qb_mysql.go b/vendor/github.com/astaxie/beego/orm/qb_mysql.go deleted file mode 100644 index 23bdc9ee..00000000 --- a/vendor/github.com/astaxie/beego/orm/qb_mysql.go +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "strconv" - "strings" -) - -// CommaSpace is the separation -const CommaSpace = ", " - -// MySQLQueryBuilder is the SQL build -type MySQLQueryBuilder struct { - Tokens []string -} - -// Select will join the fields -func (qb *MySQLQueryBuilder) Select(fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "SELECT", strings.Join(fields, CommaSpace)) - return qb -} - -// ForUpdate add the FOR UPDATE clause -func (qb *MySQLQueryBuilder) ForUpdate() QueryBuilder { - qb.Tokens = append(qb.Tokens, "FOR UPDATE") - return qb -} - -// From join the tables -func (qb *MySQLQueryBuilder) From(tables ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "FROM", strings.Join(tables, CommaSpace)) - return qb -} - -// InnerJoin INNER JOIN the table -func (qb *MySQLQueryBuilder) InnerJoin(table string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "INNER JOIN", table) - return qb -} - -// LeftJoin LEFT JOIN the table -func (qb *MySQLQueryBuilder) LeftJoin(table string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "LEFT JOIN", table) - return qb -} - -// RightJoin RIGHT JOIN the table -func (qb *MySQLQueryBuilder) RightJoin(table string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "RIGHT JOIN", table) - return qb -} - -// On join with on cond -func (qb *MySQLQueryBuilder) On(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "ON", cond) - return qb -} - -// Where join the Where cond -func (qb *MySQLQueryBuilder) Where(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "WHERE", cond) - return qb -} - -// And join the and cond -func (qb *MySQLQueryBuilder) And(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "AND", cond) - return qb -} - -// Or join the or cond -func (qb *MySQLQueryBuilder) Or(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "OR", cond) - return qb -} - -// In join the IN (vals) -func (qb *MySQLQueryBuilder) In(vals ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "IN", "(", strings.Join(vals, CommaSpace), ")") - return qb -} - -// OrderBy join the Order by fields -func (qb *MySQLQueryBuilder) OrderBy(fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "ORDER BY", strings.Join(fields, CommaSpace)) - return qb -} - -// Asc join the asc -func (qb *MySQLQueryBuilder) Asc() QueryBuilder { - qb.Tokens = append(qb.Tokens, "ASC") - return qb -} - -// Desc join the desc -func (qb *MySQLQueryBuilder) Desc() QueryBuilder { - qb.Tokens = append(qb.Tokens, "DESC") - return qb -} - -// Limit join the limit num -func (qb *MySQLQueryBuilder) Limit(limit int) QueryBuilder { - qb.Tokens = append(qb.Tokens, "LIMIT", strconv.Itoa(limit)) - return qb -} - -// Offset join the offset num -func (qb *MySQLQueryBuilder) Offset(offset int) QueryBuilder { - qb.Tokens = append(qb.Tokens, "OFFSET", strconv.Itoa(offset)) - return qb -} - -// GroupBy join the Group by fields -func (qb *MySQLQueryBuilder) GroupBy(fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "GROUP BY", strings.Join(fields, CommaSpace)) - return qb -} - -// Having join the Having cond -func (qb *MySQLQueryBuilder) Having(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "HAVING", cond) - return qb -} - -// Update join the update table -func (qb *MySQLQueryBuilder) Update(tables ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "UPDATE", strings.Join(tables, CommaSpace)) - return qb -} - -// Set join the set kv -func (qb *MySQLQueryBuilder) Set(kv ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "SET", strings.Join(kv, CommaSpace)) - return qb -} - -// Delete join the Delete tables -func (qb *MySQLQueryBuilder) Delete(tables ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "DELETE") - if len(tables) != 0 { - qb.Tokens = append(qb.Tokens, strings.Join(tables, CommaSpace)) - } - return qb -} - -// InsertInto join the insert SQL -func (qb *MySQLQueryBuilder) InsertInto(table string, fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "INSERT INTO", table) - if len(fields) != 0 { - fieldsStr := strings.Join(fields, CommaSpace) - qb.Tokens = append(qb.Tokens, "(", fieldsStr, ")") - } - return qb -} - -// Values join the Values(vals) -func (qb *MySQLQueryBuilder) Values(vals ...string) QueryBuilder { - valsStr := strings.Join(vals, CommaSpace) - qb.Tokens = append(qb.Tokens, "VALUES", "(", valsStr, ")") - return qb -} - -// Subquery join the sub as alias -func (qb *MySQLQueryBuilder) Subquery(sub string, alias string) string { - return fmt.Sprintf("(%s) AS %s", sub, alias) -} - -// String join all Tokens -func (qb *MySQLQueryBuilder) String() string { - return strings.Join(qb.Tokens, " ") -} diff --git a/vendor/github.com/astaxie/beego/orm/qb_tidb.go b/vendor/github.com/astaxie/beego/orm/qb_tidb.go deleted file mode 100644 index 87b3ae84..00000000 --- a/vendor/github.com/astaxie/beego/orm/qb_tidb.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2015 TiDB Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "strconv" - "strings" -) - -// TiDBQueryBuilder is the SQL build -type TiDBQueryBuilder struct { - Tokens []string -} - -// Select will join the fields -func (qb *TiDBQueryBuilder) Select(fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "SELECT", strings.Join(fields, CommaSpace)) - return qb -} - -// ForUpdate add the FOR UPDATE clause -func (qb *TiDBQueryBuilder) ForUpdate() QueryBuilder { - qb.Tokens = append(qb.Tokens, "FOR UPDATE") - return qb -} - -// From join the tables -func (qb *TiDBQueryBuilder) From(tables ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "FROM", strings.Join(tables, CommaSpace)) - return qb -} - -// InnerJoin INNER JOIN the table -func (qb *TiDBQueryBuilder) InnerJoin(table string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "INNER JOIN", table) - return qb -} - -// LeftJoin LEFT JOIN the table -func (qb *TiDBQueryBuilder) LeftJoin(table string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "LEFT JOIN", table) - return qb -} - -// RightJoin RIGHT JOIN the table -func (qb *TiDBQueryBuilder) RightJoin(table string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "RIGHT JOIN", table) - return qb -} - -// On join with on cond -func (qb *TiDBQueryBuilder) On(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "ON", cond) - return qb -} - -// Where join the Where cond -func (qb *TiDBQueryBuilder) Where(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "WHERE", cond) - return qb -} - -// And join the and cond -func (qb *TiDBQueryBuilder) And(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "AND", cond) - return qb -} - -// Or join the or cond -func (qb *TiDBQueryBuilder) Or(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "OR", cond) - return qb -} - -// In join the IN (vals) -func (qb *TiDBQueryBuilder) In(vals ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "IN", "(", strings.Join(vals, CommaSpace), ")") - return qb -} - -// OrderBy join the Order by fields -func (qb *TiDBQueryBuilder) OrderBy(fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "ORDER BY", strings.Join(fields, CommaSpace)) - return qb -} - -// Asc join the asc -func (qb *TiDBQueryBuilder) Asc() QueryBuilder { - qb.Tokens = append(qb.Tokens, "ASC") - return qb -} - -// Desc join the desc -func (qb *TiDBQueryBuilder) Desc() QueryBuilder { - qb.Tokens = append(qb.Tokens, "DESC") - return qb -} - -// Limit join the limit num -func (qb *TiDBQueryBuilder) Limit(limit int) QueryBuilder { - qb.Tokens = append(qb.Tokens, "LIMIT", strconv.Itoa(limit)) - return qb -} - -// Offset join the offset num -func (qb *TiDBQueryBuilder) Offset(offset int) QueryBuilder { - qb.Tokens = append(qb.Tokens, "OFFSET", strconv.Itoa(offset)) - return qb -} - -// GroupBy join the Group by fields -func (qb *TiDBQueryBuilder) GroupBy(fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "GROUP BY", strings.Join(fields, CommaSpace)) - return qb -} - -// Having join the Having cond -func (qb *TiDBQueryBuilder) Having(cond string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "HAVING", cond) - return qb -} - -// Update join the update table -func (qb *TiDBQueryBuilder) Update(tables ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "UPDATE", strings.Join(tables, CommaSpace)) - return qb -} - -// Set join the set kv -func (qb *TiDBQueryBuilder) Set(kv ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "SET", strings.Join(kv, CommaSpace)) - return qb -} - -// Delete join the Delete tables -func (qb *TiDBQueryBuilder) Delete(tables ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "DELETE") - if len(tables) != 0 { - qb.Tokens = append(qb.Tokens, strings.Join(tables, CommaSpace)) - } - return qb -} - -// InsertInto join the insert SQL -func (qb *TiDBQueryBuilder) InsertInto(table string, fields ...string) QueryBuilder { - qb.Tokens = append(qb.Tokens, "INSERT INTO", table) - if len(fields) != 0 { - fieldsStr := strings.Join(fields, CommaSpace) - qb.Tokens = append(qb.Tokens, "(", fieldsStr, ")") - } - return qb -} - -// Values join the Values(vals) -func (qb *TiDBQueryBuilder) Values(vals ...string) QueryBuilder { - valsStr := strings.Join(vals, CommaSpace) - qb.Tokens = append(qb.Tokens, "VALUES", "(", valsStr, ")") - return qb -} - -// Subquery join the sub as alias -func (qb *TiDBQueryBuilder) Subquery(sub string, alias string) string { - return fmt.Sprintf("(%s) AS %s", sub, alias) -} - -// String join all Tokens -func (qb *TiDBQueryBuilder) String() string { - return strings.Join(qb.Tokens, " ") -} diff --git a/vendor/github.com/astaxie/beego/orm/types.go b/vendor/github.com/astaxie/beego/orm/types.go deleted file mode 100644 index 2fd10774..00000000 --- a/vendor/github.com/astaxie/beego/orm/types.go +++ /dev/null @@ -1,473 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "context" - "database/sql" - "reflect" - "time" -) - -// Driver define database driver -type Driver interface { - Name() string - Type() DriverType -} - -// Fielder define field info -type Fielder interface { - String() string - FieldType() int - SetRaw(interface{}) error - RawValue() interface{} -} - -// Ormer define the orm interface -type Ormer interface { - // read data to model - // for example: - // this will find User by Id field - // u = &User{Id: user.Id} - // err = Ormer.Read(u) - // this will find User by UserName field - // u = &User{UserName: "astaxie", Password: "pass"} - // err = Ormer.Read(u, "UserName") - Read(md interface{}, cols ...string) error - // Like Read(), but with "FOR UPDATE" clause, useful in transaction. - // Some databases are not support this feature. - ReadForUpdate(md interface{}, cols ...string) error - // Try to read a row from the database, or insert one if it doesn't exist - ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) - // insert model data to database - // for example: - // user := new(User) - // id, err = Ormer.Insert(user) - // user must be a pointer and Insert will set user's pk field - Insert(interface{}) (int64, error) - // mysql:InsertOrUpdate(model) or InsertOrUpdate(model,"colu=colu+value") - // if colu type is integer : can use(+-*/), string : convert(colu,"value") - // postgres: InsertOrUpdate(model,"conflictColumnName") or InsertOrUpdate(model,"conflictColumnName","colu=colu+value") - // if colu type is integer : can use(+-*/), string : colu || "value" - InsertOrUpdate(md interface{}, colConflitAndArgs ...string) (int64, error) - // insert some models to database - InsertMulti(bulk int, mds interface{}) (int64, error) - // update model to database. - // cols set the columns those want to update. - // find model by Id(pk) field and update columns specified by fields, if cols is null then update all columns - // for example: - // user := User{Id: 2} - // user.Langs = append(user.Langs, "zh-CN", "en-US") - // user.Extra.Name = "beego" - // user.Extra.Data = "orm" - // num, err = Ormer.Update(&user, "Langs", "Extra") - Update(md interface{}, cols ...string) (int64, error) - // delete model in database - Delete(md interface{}, cols ...string) (int64, error) - // load related models to md model. - // args are limit, offset int and order string. - // - // example: - // Ormer.LoadRelated(post,"Tags") - // for _,tag := range post.Tags{...} - //args[0] bool true useDefaultRelsDepth ; false depth 0 - //args[0] int loadRelationDepth - //args[1] int limit default limit 1000 - //args[2] int offset default offset 0 - //args[3] string order for example : "-Id" - // make sure the relation is defined in model struct tags. - LoadRelated(md interface{}, name string, args ...interface{}) (int64, error) - // create a models to models queryer - // for example: - // post := Post{Id: 4} - // m2m := Ormer.QueryM2M(&post, "Tags") - QueryM2M(md interface{}, name string) QueryM2Mer - // return a QuerySeter for table operations. - // table name can be string or struct. - // e.g. QueryTable("user"), QueryTable(&user{}) or QueryTable((*User)(nil)), - QueryTable(ptrStructOrTableName interface{}) QuerySeter - // switch to another registered database driver by given name. - Using(name string) error - // begin transaction - // for example: - // o := NewOrm() - // err := o.Begin() - // ... - // err = o.Rollback() - Begin() error - // begin transaction with provided context and option - // the provided context is used until the transaction is committed or rolled back. - // if the context is canceled, the transaction will be rolled back. - // the provided TxOptions is optional and may be nil if defaults should be used. - // if a non-default isolation level is used that the driver doesn't support, an error will be returned. - // for example: - // o := NewOrm() - // err := o.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelRepeatableRead}) - // ... - // err = o.Rollback() - BeginTx(ctx context.Context, opts *sql.TxOptions) error - // commit transaction - Commit() error - // rollback transaction - Rollback() error - // return a raw query seter for raw sql string. - // for example: - // ormer.Raw("UPDATE `user` SET `user_name` = ? WHERE `user_name` = ?", "slene", "testing").Exec() - // // update user testing's name to slene - Raw(query string, args ...interface{}) RawSeter - Driver() Driver - DBStats() *sql.DBStats -} - -// Inserter insert prepared statement -type Inserter interface { - Insert(interface{}) (int64, error) - Close() error -} - -// QuerySeter query seter -type QuerySeter interface { - // add condition expression to QuerySeter. - // for example: - // filter by UserName == 'slene' - // qs.Filter("UserName", "slene") - // sql : left outer join profile on t0.id1==t1.id2 where t1.age == 28 - // Filter("profile__Age", 28) - // // time compare - // qs.Filter("created", time.Now()) - Filter(string, ...interface{}) QuerySeter - // add raw sql to querySeter. - // for example: - // qs.FilterRaw("user_id IN (SELECT id FROM profile WHERE age>=18)") - // //sql-> WHERE user_id IN (SELECT id FROM profile WHERE age>=18) - FilterRaw(string, string) QuerySeter - // add NOT condition to querySeter. - // have the same usage as Filter - Exclude(string, ...interface{}) QuerySeter - // set condition to QuerySeter. - // sql's where condition - // cond := orm.NewCondition() - // cond1 := cond.And("profile__isnull", false).AndNot("status__in", 1).Or("profile__age__gt", 2000) - // //sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` > 2000 - // num, err := qs.SetCond(cond1).Count() - SetCond(*Condition) QuerySeter - // get condition from QuerySeter. - // sql's where condition - // cond := orm.NewCondition() - // cond = cond.And("profile__isnull", false).AndNot("status__in", 1) - // qs = qs.SetCond(cond) - // cond = qs.GetCond() - // cond := cond.Or("profile__age__gt", 2000) - // //sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` > 2000 - // num, err := qs.SetCond(cond).Count() - GetCond() *Condition - // add LIMIT value. - // args[0] means offset, e.g. LIMIT num,offset. - // if Limit <= 0 then Limit will be set to default limit ,eg 1000 - // if QuerySeter doesn't call Limit, the sql's Limit will be set to default limit, eg 1000 - // for example: - // qs.Limit(10, 2) - // // sql-> limit 10 offset 2 - Limit(limit interface{}, args ...interface{}) QuerySeter - // add OFFSET value - // same as Limit function's args[0] - Offset(offset interface{}) QuerySeter - // add GROUP BY expression - // for example: - // qs.GroupBy("id") - GroupBy(exprs ...string) QuerySeter - // add ORDER expression. - // "column" means ASC, "-column" means DESC. - // for example: - // qs.OrderBy("-status") - OrderBy(exprs ...string) QuerySeter - // set relation model to query together. - // it will query relation models and assign to parent model. - // for example: - // // will load all related fields use left join . - // qs.RelatedSel().One(&user) - // // will load related field only profile - // qs.RelatedSel("profile").One(&user) - // user.Profile.Age = 32 - RelatedSel(params ...interface{}) QuerySeter - // Set Distinct - // for example: - // o.QueryTable("policy").Filter("Groups__Group__Users__User", user). - // Distinct(). - // All(&permissions) - Distinct() QuerySeter - // set FOR UPDATE to query. - // for example: - // o.QueryTable("user").Filter("uid", uid).ForUpdate().All(&users) - ForUpdate() QuerySeter - // return QuerySeter execution result number - // for example: - // num, err = qs.Filter("profile__age__gt", 28).Count() - Count() (int64, error) - // check result empty or not after QuerySeter executed - // the same as QuerySeter.Count > 0 - Exist() bool - // execute update with parameters - // for example: - // num, err = qs.Filter("user_name", "slene").Update(Params{ - // "Nums": ColValue(Col_Minus, 50), - // }) // user slene's Nums will minus 50 - // num, err = qs.Filter("UserName", "slene").Update(Params{ - // "user_name": "slene2" - // }) // user slene's name will change to slene2 - Update(values Params) (int64, error) - // delete from table - //for example: - // num ,err = qs.Filter("user_name__in", "testing1", "testing2").Delete() - // //delete two user who's name is testing1 or testing2 - Delete() (int64, error) - // return a insert queryer. - // it can be used in times. - // example: - // i,err := sq.PrepareInsert() - // num, err = i.Insert(&user1) // user table will add one record user1 at once - // num, err = i.Insert(&user2) // user table will add one record user2 at once - // err = i.Close() //don't forget call Close - PrepareInsert() (Inserter, error) - // query all data and map to containers. - // cols means the columns when querying. - // for example: - // var users []*User - // qs.All(&users) // users[0],users[1],users[2] ... - All(container interface{}, cols ...string) (int64, error) - // query one row data and map to containers. - // cols means the columns when querying. - // for example: - // var user User - // qs.One(&user) //user.UserName == "slene" - One(container interface{}, cols ...string) error - // query all data and map to []map[string]interface. - // expres means condition expression. - // it converts data to []map[column]value. - // for example: - // var maps []Params - // qs.Values(&maps) //maps[0]["UserName"]=="slene" - Values(results *[]Params, exprs ...string) (int64, error) - // query all data and map to [][]interface - // it converts data to [][column_index]value - // for example: - // var list []ParamsList - // qs.ValuesList(&list) // list[0][1] == "slene" - ValuesList(results *[]ParamsList, exprs ...string) (int64, error) - // query all data and map to []interface. - // it's designed for one column record set, auto change to []value, not [][column]value. - // for example: - // var list ParamsList - // qs.ValuesFlat(&list, "UserName") // list[0] == "slene" - ValuesFlat(result *ParamsList, expr string) (int64, error) - // query all rows into map[string]interface with specify key and value column name. - // keyCol = "name", valueCol = "value" - // table data - // name | value - // total | 100 - // found | 200 - // to map[string]interface{}{ - // "total": 100, - // "found": 200, - // } - RowsToMap(result *Params, keyCol, valueCol string) (int64, error) - // query all rows into struct with specify key and value column name. - // keyCol = "name", valueCol = "value" - // table data - // name | value - // total | 100 - // found | 200 - // to struct { - // Total int - // Found int - // } - RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) -} - -// QueryM2Mer model to model query struct -// all operations are on the m2m table only, will not affect the origin model table -type QueryM2Mer interface { - // add models to origin models when creating queryM2M. - // example: - // m2m := orm.QueryM2M(post,"Tag") - // m2m.Add(&Tag1{},&Tag2{}) - // for _,tag := range post.Tags{}{ ... } - // param could also be any of the follow - // []*Tag{{Id:3,Name: "TestTag1"}, {Id:4,Name: "TestTag2"}} - // &Tag{Id:5,Name: "TestTag3"} - // []interface{}{&Tag{Id:6,Name: "TestTag4"}} - // insert one or more rows to m2m table - // make sure the relation is defined in post model struct tag. - Add(...interface{}) (int64, error) - // remove models following the origin model relationship - // only delete rows from m2m table - // for example: - //tag3 := &Tag{Id:5,Name: "TestTag3"} - //num, err = m2m.Remove(tag3) - Remove(...interface{}) (int64, error) - // check model is existed in relationship of origin model - Exist(interface{}) bool - // clean all models in related of origin model - Clear() (int64, error) - // count all related models of origin model - Count() (int64, error) -} - -// RawPreparer raw query statement -type RawPreparer interface { - Exec(...interface{}) (sql.Result, error) - Close() error -} - -// RawSeter raw query seter -// create From Ormer.Raw -// for example: -// sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q) -// rs := Ormer.Raw(sql, 1) -type RawSeter interface { - //execute sql and get result - Exec() (sql.Result, error) - //query data and map to container - //for example: - // var name string - // var id int - // rs.QueryRow(&id,&name) // id==2 name=="slene" - QueryRow(containers ...interface{}) error - - // query data rows and map to container - // var ids []int - // var names []int - // query = fmt.Sprintf("SELECT 'id','name' FROM %suser%s", Q, Q) - // num, err = dORM.Raw(query).QueryRows(&ids,&names) // ids=>{1,2},names=>{"nobody","slene"} - QueryRows(containers ...interface{}) (int64, error) - SetArgs(...interface{}) RawSeter - // query data to []map[string]interface - // see QuerySeter's Values - Values(container *[]Params, cols ...string) (int64, error) - // query data to [][]interface - // see QuerySeter's ValuesList - ValuesList(container *[]ParamsList, cols ...string) (int64, error) - // query data to []interface - // see QuerySeter's ValuesFlat - ValuesFlat(container *ParamsList, cols ...string) (int64, error) - // query all rows into map[string]interface with specify key and value column name. - // keyCol = "name", valueCol = "value" - // table data - // name | value - // total | 100 - // found | 200 - // to map[string]interface{}{ - // "total": 100, - // "found": 200, - // } - RowsToMap(result *Params, keyCol, valueCol string) (int64, error) - // query all rows into struct with specify key and value column name. - // keyCol = "name", valueCol = "value" - // table data - // name | value - // total | 100 - // found | 200 - // to struct { - // Total int - // Found int - // } - RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) - - // return prepared raw statement for used in times. - // for example: - // pre, err := dORM.Raw("INSERT INTO tag (name) VALUES (?)").Prepare() - // r, err := pre.Exec("name1") // INSERT INTO tag (name) VALUES (`name1`) - Prepare() (RawPreparer, error) -} - -// stmtQuerier statement querier -type stmtQuerier interface { - Close() error - Exec(args ...interface{}) (sql.Result, error) - //ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) - Query(args ...interface{}) (*sql.Rows, error) - //QueryContext(args ...interface{}) (*sql.Rows, error) - QueryRow(args ...interface{}) *sql.Row - //QueryRowContext(ctx context.Context, args ...interface{}) *sql.Row -} - -// db querier -type dbQuerier interface { - Prepare(query string) (*sql.Stmt, error) - PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) - Exec(query string, args ...interface{}) (sql.Result, error) - ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) - Query(query string, args ...interface{}) (*sql.Rows, error) - QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) - QueryRow(query string, args ...interface{}) *sql.Row - QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row -} - -// type DB interface { -// Begin() (*sql.Tx, error) -// Prepare(query string) (stmtQuerier, error) -// Exec(query string, args ...interface{}) (sql.Result, error) -// Query(query string, args ...interface{}) (*sql.Rows, error) -// QueryRow(query string, args ...interface{}) *sql.Row -// } - -// transaction beginner -type txer interface { - Begin() (*sql.Tx, error) - BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) -} - -// transaction ending -type txEnder interface { - Commit() error - Rollback() error -} - -// base database struct -type dbBaser interface { - Read(dbQuerier, *modelInfo, reflect.Value, *time.Location, []string, bool) error - Insert(dbQuerier, *modelInfo, reflect.Value, *time.Location) (int64, error) - InsertOrUpdate(dbQuerier, *modelInfo, reflect.Value, *alias, ...string) (int64, error) - InsertMulti(dbQuerier, *modelInfo, reflect.Value, int, *time.Location) (int64, error) - InsertValue(dbQuerier, *modelInfo, bool, []string, []interface{}) (int64, error) - InsertStmt(stmtQuerier, *modelInfo, reflect.Value, *time.Location) (int64, error) - Update(dbQuerier, *modelInfo, reflect.Value, *time.Location, []string) (int64, error) - Delete(dbQuerier, *modelInfo, reflect.Value, *time.Location, []string) (int64, error) - ReadBatch(dbQuerier, *querySet, *modelInfo, *Condition, interface{}, *time.Location, []string) (int64, error) - SupportUpdateJoin() bool - UpdateBatch(dbQuerier, *querySet, *modelInfo, *Condition, Params, *time.Location) (int64, error) - DeleteBatch(dbQuerier, *querySet, *modelInfo, *Condition, *time.Location) (int64, error) - Count(dbQuerier, *querySet, *modelInfo, *Condition, *time.Location) (int64, error) - OperatorSQL(string) string - GenerateOperatorSQL(*modelInfo, *fieldInfo, string, []interface{}, *time.Location) (string, []interface{}) - GenerateOperatorLeftCol(*fieldInfo, string, *string) - PrepareInsert(dbQuerier, *modelInfo) (stmtQuerier, string, error) - ReadValues(dbQuerier, *querySet, *modelInfo, *Condition, []string, interface{}, *time.Location) (int64, error) - RowsTo(dbQuerier, *querySet, *modelInfo, *Condition, interface{}, string, string, *time.Location) (int64, error) - MaxLimit() uint64 - TableQuote() string - ReplaceMarks(*string) - HasReturningID(*modelInfo, *string) bool - TimeFromDB(*time.Time, *time.Location) - TimeToDB(*time.Time, *time.Location) - DbTypes() map[string]string - GetTables(dbQuerier) (map[string]bool, error) - GetColumns(dbQuerier, string) (map[string][3]string, error) - ShowTablesQuery() string - ShowColumnsQuery(string) string - IndexExists(dbQuerier, string, string) bool - collectFieldValue(*modelInfo, *fieldInfo, reflect.Value, bool, *time.Location) (interface{}, error) - setval(dbQuerier, *modelInfo, []string) error -} diff --git a/vendor/github.com/astaxie/beego/orm/utils.go b/vendor/github.com/astaxie/beego/orm/utils.go deleted file mode 100644 index 3ff76772..00000000 --- a/vendor/github.com/astaxie/beego/orm/utils.go +++ /dev/null @@ -1,319 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package orm - -import ( - "fmt" - "math/big" - "reflect" - "strconv" - "strings" - "time" -) - -type fn func(string) string - -var ( - nameStrategyMap = map[string]fn{ - defaultNameStrategy: snakeString, - SnakeAcronymNameStrategy: snakeStringWithAcronym, - } - defaultNameStrategy = "snakeString" - SnakeAcronymNameStrategy = "snakeStringWithAcronym" - nameStrategy = defaultNameStrategy -) - -// StrTo is the target string -type StrTo string - -// Set string -func (f *StrTo) Set(v string) { - if v != "" { - *f = StrTo(v) - } else { - f.Clear() - } -} - -// Clear string -func (f *StrTo) Clear() { - *f = StrTo(0x1E) -} - -// Exist check string exist -func (f StrTo) Exist() bool { - return string(f) != string(0x1E) -} - -// Bool string to bool -func (f StrTo) Bool() (bool, error) { - return strconv.ParseBool(f.String()) -} - -// Float32 string to float32 -func (f StrTo) Float32() (float32, error) { - v, err := strconv.ParseFloat(f.String(), 32) - return float32(v), err -} - -// Float64 string to float64 -func (f StrTo) Float64() (float64, error) { - return strconv.ParseFloat(f.String(), 64) -} - -// Int string to int -func (f StrTo) Int() (int, error) { - v, err := strconv.ParseInt(f.String(), 10, 32) - return int(v), err -} - -// Int8 string to int8 -func (f StrTo) Int8() (int8, error) { - v, err := strconv.ParseInt(f.String(), 10, 8) - return int8(v), err -} - -// Int16 string to int16 -func (f StrTo) Int16() (int16, error) { - v, err := strconv.ParseInt(f.String(), 10, 16) - return int16(v), err -} - -// Int32 string to int32 -func (f StrTo) Int32() (int32, error) { - v, err := strconv.ParseInt(f.String(), 10, 32) - return int32(v), err -} - -// Int64 string to int64 -func (f StrTo) Int64() (int64, error) { - v, err := strconv.ParseInt(f.String(), 10, 64) - if err != nil { - i := new(big.Int) - ni, ok := i.SetString(f.String(), 10) // octal - if !ok { - return v, err - } - return ni.Int64(), nil - } - return v, err -} - -// Uint string to uint -func (f StrTo) Uint() (uint, error) { - v, err := strconv.ParseUint(f.String(), 10, 32) - return uint(v), err -} - -// Uint8 string to uint8 -func (f StrTo) Uint8() (uint8, error) { - v, err := strconv.ParseUint(f.String(), 10, 8) - return uint8(v), err -} - -// Uint16 string to uint16 -func (f StrTo) Uint16() (uint16, error) { - v, err := strconv.ParseUint(f.String(), 10, 16) - return uint16(v), err -} - -// Uint32 string to uint32 -func (f StrTo) Uint32() (uint32, error) { - v, err := strconv.ParseUint(f.String(), 10, 32) - return uint32(v), err -} - -// Uint64 string to uint64 -func (f StrTo) Uint64() (uint64, error) { - v, err := strconv.ParseUint(f.String(), 10, 64) - if err != nil { - i := new(big.Int) - ni, ok := i.SetString(f.String(), 10) - if !ok { - return v, err - } - return ni.Uint64(), nil - } - return v, err -} - -// String string to string -func (f StrTo) String() string { - if f.Exist() { - return string(f) - } - return "" -} - -// ToStr interface to string -func ToStr(value interface{}, args ...int) (s string) { - switch v := value.(type) { - case bool: - s = strconv.FormatBool(v) - case float32: - s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32)) - case float64: - s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64)) - case int: - s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) - case int8: - s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) - case int16: - s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) - case int32: - s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) - case int64: - s = strconv.FormatInt(v, argInt(args).Get(0, 10)) - case uint: - s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) - case uint8: - s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) - case uint16: - s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) - case uint32: - s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) - case uint64: - s = strconv.FormatUint(v, argInt(args).Get(0, 10)) - case string: - s = v - case []byte: - s = string(v) - default: - s = fmt.Sprintf("%v", v) - } - return s -} - -// ToInt64 interface to int64 -func ToInt64(value interface{}) (d int64) { - val := reflect.ValueOf(value) - switch value.(type) { - case int, int8, int16, int32, int64: - d = val.Int() - case uint, uint8, uint16, uint32, uint64: - d = int64(val.Uint()) - default: - panic(fmt.Errorf("ToInt64 need numeric not `%T`", value)) - } - return -} - -func snakeStringWithAcronym(s string) string { - data := make([]byte, 0, len(s)*2) - num := len(s) - for i := 0; i < num; i++ { - d := s[i] - before := false - after := false - if i > 0 { - before = s[i-1] >= 'a' && s[i-1] <= 'z' - } - if i+1 < num { - after = s[i+1] >= 'a' && s[i+1] <= 'z' - } - if i > 0 && d >= 'A' && d <= 'Z' && (before || after) { - data = append(data, '_') - } - data = append(data, d) - } - return strings.ToLower(string(data[:])) -} - -// snake string, XxYy to xx_yy , XxYY to xx_y_y -func snakeString(s string) string { - data := make([]byte, 0, len(s)*2) - j := false - num := len(s) - for i := 0; i < num; i++ { - d := s[i] - if i > 0 && d >= 'A' && d <= 'Z' && j { - data = append(data, '_') - } - if d != '_' { - j = true - } - data = append(data, d) - } - return strings.ToLower(string(data[:])) -} - -// SetNameStrategy set different name strategy -func SetNameStrategy(s string) { - if SnakeAcronymNameStrategy != s { - nameStrategy = defaultNameStrategy - } - nameStrategy = s -} - -// camel string, xx_yy to XxYy -func camelString(s string) string { - data := make([]byte, 0, len(s)) - flag, num := true, len(s)-1 - for i := 0; i <= num; i++ { - d := s[i] - if d == '_' { - flag = true - continue - } else if flag { - if d >= 'a' && d <= 'z' { - d = d - 32 - } - flag = false - } - data = append(data, d) - } - return string(data[:]) -} - -type argString []string - -// get string by index from string slice -func (a argString) Get(i int, args ...string) (r string) { - if i >= 0 && i < len(a) { - r = a[i] - } else if len(args) > 0 { - r = args[0] - } - return -} - -type argInt []int - -// get int by index from int slice -func (a argInt) Get(i int, args ...int) (r int) { - if i >= 0 && i < len(a) { - r = a[i] - } - if len(args) > 0 { - r = args[0] - } - return -} - -// parse time to string with location -func timeParse(dateString, format string) (time.Time, error) { - tp, err := time.ParseInLocation(format, dateString, DefaultTimeLoc) - return tp, err -} - -// get pointer indirect type -func indirectType(v reflect.Type) reflect.Type { - switch v.Kind() { - case reflect.Ptr: - return indirectType(v.Elem()) - default: - return v - } -} diff --git a/vendor/github.com/astaxie/beego/parser.go b/vendor/github.com/astaxie/beego/parser.go deleted file mode 100644 index 3a311894..00000000 --- a/vendor/github.com/astaxie/beego/parser.go +++ /dev/null @@ -1,591 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "encoding/json" - "errors" - "fmt" - "go/ast" - "go/parser" - "go/token" - "io/ioutil" - "os" - "path/filepath" - "regexp" - "sort" - "strconv" - "strings" - "unicode" - - "github.com/astaxie/beego/context/param" - "github.com/astaxie/beego/logs" - "github.com/astaxie/beego/utils" -) - -var globalRouterTemplate = `package {{.routersDir}} - -import ( - "github.com/astaxie/beego" - "github.com/astaxie/beego/context/param"{{.globalimport}} -) - -func init() { -{{.globalinfo}} -} -` - -var ( - lastupdateFilename = "lastupdate.tmp" - commentFilename string - pkgLastupdate map[string]int64 - genInfoList map[string][]ControllerComments - - routerHooks = map[string]int{ - "beego.BeforeStatic": BeforeStatic, - "beego.BeforeRouter": BeforeRouter, - "beego.BeforeExec": BeforeExec, - "beego.AfterExec": AfterExec, - "beego.FinishRouter": FinishRouter, - } - - routerHooksMapping = map[int]string{ - BeforeStatic: "beego.BeforeStatic", - BeforeRouter: "beego.BeforeRouter", - BeforeExec: "beego.BeforeExec", - AfterExec: "beego.AfterExec", - FinishRouter: "beego.FinishRouter", - } -) - -const commentPrefix = "commentsRouter_" - -func init() { - pkgLastupdate = make(map[string]int64) -} - -func parserPkg(pkgRealpath, pkgpath string) error { - rep := strings.NewReplacer("\\", "_", "/", "_", ".", "_") - commentFilename, _ = filepath.Rel(AppPath, pkgRealpath) - commentFilename = commentPrefix + rep.Replace(commentFilename) + ".go" - if !compareFile(pkgRealpath) { - logs.Info(pkgRealpath + " no changed") - return nil - } - genInfoList = make(map[string][]ControllerComments) - fileSet := token.NewFileSet() - astPkgs, err := parser.ParseDir(fileSet, pkgRealpath, func(info os.FileInfo) bool { - name := info.Name() - return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") - }, parser.ParseComments) - - if err != nil { - return err - } - for _, pkg := range astPkgs { - for _, fl := range pkg.Files { - for _, d := range fl.Decls { - switch specDecl := d.(type) { - case *ast.FuncDecl: - if specDecl.Recv != nil { - exp, ok := specDecl.Recv.List[0].Type.(*ast.StarExpr) // Check that the type is correct first beforing throwing to parser - if ok { - parserComments(specDecl, fmt.Sprint(exp.X), pkgpath) - } - } - } - } - } - } - genRouterCode(pkgRealpath) - savetoFile(pkgRealpath) - return nil -} - -type parsedComment struct { - routerPath string - methods []string - params map[string]parsedParam - filters []parsedFilter - imports []parsedImport -} - -type parsedImport struct { - importPath string - importAlias string -} - -type parsedFilter struct { - pattern string - pos int - filter string - params []bool -} - -type parsedParam struct { - name string - datatype string - location string - defValue string - required bool -} - -func parserComments(f *ast.FuncDecl, controllerName, pkgpath string) error { - if f.Doc != nil { - parsedComments, err := parseComment(f.Doc.List) - if err != nil { - return err - } - for _, parsedComment := range parsedComments { - if parsedComment.routerPath != "" { - key := pkgpath + ":" + controllerName - cc := ControllerComments{} - cc.Method = f.Name.String() - cc.Router = parsedComment.routerPath - cc.AllowHTTPMethods = parsedComment.methods - cc.MethodParams = buildMethodParams(f.Type.Params.List, parsedComment) - cc.FilterComments = buildFilters(parsedComment.filters) - cc.ImportComments = buildImports(parsedComment.imports) - genInfoList[key] = append(genInfoList[key], cc) - } - } - } - return nil -} - -func buildImports(pis []parsedImport) []*ControllerImportComments { - var importComments []*ControllerImportComments - - for _, pi := range pis { - importComments = append(importComments, &ControllerImportComments{ - ImportPath: pi.importPath, - ImportAlias: pi.importAlias, - }) - } - - return importComments -} - -func buildFilters(pfs []parsedFilter) []*ControllerFilterComments { - var filterComments []*ControllerFilterComments - - for _, pf := range pfs { - var ( - returnOnOutput bool - resetParams bool - ) - - if len(pf.params) >= 1 { - returnOnOutput = pf.params[0] - } - - if len(pf.params) >= 2 { - resetParams = pf.params[1] - } - - filterComments = append(filterComments, &ControllerFilterComments{ - Filter: pf.filter, - Pattern: pf.pattern, - Pos: pf.pos, - ReturnOnOutput: returnOnOutput, - ResetParams: resetParams, - }) - } - - return filterComments -} - -func buildMethodParams(funcParams []*ast.Field, pc *parsedComment) []*param.MethodParam { - result := make([]*param.MethodParam, 0, len(funcParams)) - for _, fparam := range funcParams { - for _, pName := range fparam.Names { - methodParam := buildMethodParam(fparam, pName.Name, pc) - result = append(result, methodParam) - } - } - return result -} - -func buildMethodParam(fparam *ast.Field, name string, pc *parsedComment) *param.MethodParam { - options := []param.MethodParamOption{} - if cparam, ok := pc.params[name]; ok { - //Build param from comment info - name = cparam.name - if cparam.required { - options = append(options, param.IsRequired) - } - switch cparam.location { - case "body": - options = append(options, param.InBody) - case "header": - options = append(options, param.InHeader) - case "path": - options = append(options, param.InPath) - } - if cparam.defValue != "" { - options = append(options, param.Default(cparam.defValue)) - } - } else { - if paramInPath(name, pc.routerPath) { - options = append(options, param.InPath) - } - } - return param.New(name, options...) -} - -func paramInPath(name, route string) bool { - return strings.HasSuffix(route, ":"+name) || - strings.Contains(route, ":"+name+"/") -} - -var routeRegex = regexp.MustCompile(`@router\s+(\S+)(?:\s+\[(\S+)\])?`) - -func parseComment(lines []*ast.Comment) (pcs []*parsedComment, err error) { - pcs = []*parsedComment{} - params := map[string]parsedParam{} - filters := []parsedFilter{} - imports := []parsedImport{} - - for _, c := range lines { - t := strings.TrimSpace(strings.TrimLeft(c.Text, "//")) - if strings.HasPrefix(t, "@Param") { - pv := getparams(strings.TrimSpace(strings.TrimLeft(t, "@Param"))) - if len(pv) < 4 { - logs.Error("Invalid @Param format. Needs at least 4 parameters") - } - p := parsedParam{} - names := strings.SplitN(pv[0], "=>", 2) - p.name = names[0] - funcParamName := p.name - if len(names) > 1 { - funcParamName = names[1] - } - p.location = pv[1] - p.datatype = pv[2] - switch len(pv) { - case 5: - p.required, _ = strconv.ParseBool(pv[3]) - case 6: - p.defValue = pv[3] - p.required, _ = strconv.ParseBool(pv[4]) - } - params[funcParamName] = p - } - } - - for _, c := range lines { - t := strings.TrimSpace(strings.TrimLeft(c.Text, "//")) - if strings.HasPrefix(t, "@Import") { - iv := getparams(strings.TrimSpace(strings.TrimLeft(t, "@Import"))) - if len(iv) == 0 || len(iv) > 2 { - logs.Error("Invalid @Import format. Only accepts 1 or 2 parameters") - continue - } - - p := parsedImport{} - p.importPath = iv[0] - - if len(iv) == 2 { - p.importAlias = iv[1] - } - - imports = append(imports, p) - } - } - -filterLoop: - for _, c := range lines { - t := strings.TrimSpace(strings.TrimLeft(c.Text, "//")) - if strings.HasPrefix(t, "@Filter") { - fv := getparams(strings.TrimSpace(strings.TrimLeft(t, "@Filter"))) - if len(fv) < 3 { - logs.Error("Invalid @Filter format. Needs at least 3 parameters") - continue filterLoop - } - - p := parsedFilter{} - p.pattern = fv[0] - posName := fv[1] - if pos, exists := routerHooks[posName]; exists { - p.pos = pos - } else { - logs.Error("Invalid @Filter pos: ", posName) - continue filterLoop - } - - p.filter = fv[2] - fvParams := fv[3:] - for _, fvParam := range fvParams { - switch fvParam { - case "true": - p.params = append(p.params, true) - case "false": - p.params = append(p.params, false) - default: - logs.Error("Invalid @Filter param: ", fvParam) - continue filterLoop - } - } - - filters = append(filters, p) - } - } - - for _, c := range lines { - var pc = &parsedComment{} - pc.params = params - pc.filters = filters - pc.imports = imports - - t := strings.TrimSpace(strings.TrimLeft(c.Text, "//")) - if strings.HasPrefix(t, "@router") { - t := strings.TrimSpace(strings.TrimLeft(c.Text, "//")) - matches := routeRegex.FindStringSubmatch(t) - if len(matches) == 3 { - pc.routerPath = matches[1] - methods := matches[2] - if methods == "" { - pc.methods = []string{"get"} - //pc.hasGet = true - } else { - pc.methods = strings.Split(methods, ",") - //pc.hasGet = strings.Contains(methods, "get") - } - pcs = append(pcs, pc) - } else { - return nil, errors.New("Router information is missing") - } - } - } - return -} - -// direct copy from bee\g_docs.go -// analysis params return []string -// @Param query form string true "The email for login" -// [query form string true "The email for login"] -func getparams(str string) []string { - var s []rune - var j int - var start bool - var r []string - var quoted int8 - for _, c := range str { - if unicode.IsSpace(c) && quoted == 0 { - if !start { - continue - } else { - start = false - j++ - r = append(r, string(s)) - s = make([]rune, 0) - continue - } - } - - start = true - if c == '"' { - quoted ^= 1 - continue - } - s = append(s, c) - } - if len(s) > 0 { - r = append(r, string(s)) - } - return r -} - -func genRouterCode(pkgRealpath string) { - os.Mkdir(getRouterDir(pkgRealpath), 0755) - logs.Info("generate router from comments") - var ( - globalinfo string - globalimport string - sortKey []string - ) - for k := range genInfoList { - sortKey = append(sortKey, k) - } - sort.Strings(sortKey) - for _, k := range sortKey { - cList := genInfoList[k] - sort.Sort(ControllerCommentsSlice(cList)) - for _, c := range cList { - allmethod := "nil" - if len(c.AllowHTTPMethods) > 0 { - allmethod = "[]string{" - for _, m := range c.AllowHTTPMethods { - allmethod += `"` + m + `",` - } - allmethod = strings.TrimRight(allmethod, ",") + "}" - } - - params := "nil" - if len(c.Params) > 0 { - params = "[]map[string]string{" - for _, p := range c.Params { - for k, v := range p { - params = params + `map[string]string{` + k + `:"` + v + `"},` - } - } - params = strings.TrimRight(params, ",") + "}" - } - - methodParams := "param.Make(" - if len(c.MethodParams) > 0 { - lines := make([]string, 0, len(c.MethodParams)) - for _, m := range c.MethodParams { - lines = append(lines, fmt.Sprint(m)) - } - methodParams += "\n " + - strings.Join(lines, ",\n ") + - ",\n " - } - methodParams += ")" - - imports := "" - if len(c.ImportComments) > 0 { - for _, i := range c.ImportComments { - var s string - if i.ImportAlias != "" { - s = fmt.Sprintf(` - %s "%s"`, i.ImportAlias, i.ImportPath) - } else { - s = fmt.Sprintf(` - "%s"`, i.ImportPath) - } - if !strings.Contains(globalimport, s) { - imports += s - } - } - } - - filters := "" - if len(c.FilterComments) > 0 { - for _, f := range c.FilterComments { - filters += fmt.Sprintf(` &beego.ControllerFilter{ - Pattern: "%s", - Pos: %s, - Filter: %s, - ReturnOnOutput: %v, - ResetParams: %v, - },`, f.Pattern, routerHooksMapping[f.Pos], f.Filter, f.ReturnOnOutput, f.ResetParams) - } - } - - if filters == "" { - filters = "nil" - } else { - filters = fmt.Sprintf(`[]*beego.ControllerFilter{ -%s - }`, filters) - } - - globalimport += imports - - globalinfo = globalinfo + ` - beego.GlobalControllerRouter["` + k + `"] = append(beego.GlobalControllerRouter["` + k + `"], - beego.ControllerComments{ - Method: "` + strings.TrimSpace(c.Method) + `", - ` + `Router: "` + c.Router + `"` + `, - AllowHTTPMethods: ` + allmethod + `, - MethodParams: ` + methodParams + `, - Filters: ` + filters + `, - Params: ` + params + `}) -` - } - } - - if globalinfo != "" { - f, err := os.Create(filepath.Join(getRouterDir(pkgRealpath), commentFilename)) - if err != nil { - panic(err) - } - defer f.Close() - - routersDir := AppConfig.DefaultString("routersdir", "routers") - content := strings.Replace(globalRouterTemplate, "{{.globalinfo}}", globalinfo, -1) - content = strings.Replace(content, "{{.routersDir}}", routersDir, -1) - content = strings.Replace(content, "{{.globalimport}}", globalimport, -1) - f.WriteString(content) - } -} - -func compareFile(pkgRealpath string) bool { - if !utils.FileExists(filepath.Join(getRouterDir(pkgRealpath), commentFilename)) { - return true - } - if utils.FileExists(lastupdateFilename) { - content, err := ioutil.ReadFile(lastupdateFilename) - if err != nil { - return true - } - json.Unmarshal(content, &pkgLastupdate) - lastupdate, err := getpathTime(pkgRealpath) - if err != nil { - return true - } - if v, ok := pkgLastupdate[pkgRealpath]; ok { - if lastupdate <= v { - return false - } - } - } - return true -} - -func savetoFile(pkgRealpath string) { - lastupdate, err := getpathTime(pkgRealpath) - if err != nil { - return - } - pkgLastupdate[pkgRealpath] = lastupdate - d, err := json.Marshal(pkgLastupdate) - if err != nil { - return - } - ioutil.WriteFile(lastupdateFilename, d, os.ModePerm) -} - -func getpathTime(pkgRealpath string) (lastupdate int64, err error) { - fl, err := ioutil.ReadDir(pkgRealpath) - if err != nil { - return lastupdate, err - } - for _, f := range fl { - if lastupdate < f.ModTime().UnixNano() { - lastupdate = f.ModTime().UnixNano() - } - } - return lastupdate, nil -} - -func getRouterDir(pkgRealpath string) string { - dir := filepath.Dir(pkgRealpath) - for { - routersDir := AppConfig.DefaultString("routersdir", "routers") - d := filepath.Join(dir, routersDir) - if utils.FileExists(d) { - return d - } - - if r, _ := filepath.Rel(dir, AppPath); r == "." { - return d - } - // Parent dir. - dir = filepath.Dir(dir) - } -} diff --git a/vendor/github.com/astaxie/beego/policy.go b/vendor/github.com/astaxie/beego/policy.go deleted file mode 100644 index ab23f927..00000000 --- a/vendor/github.com/astaxie/beego/policy.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2016 beego authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "strings" - - "github.com/astaxie/beego/context" -) - -// PolicyFunc defines a policy function which is invoked before the controller handler is executed. -type PolicyFunc func(*context.Context) - -// FindPolicy Find Router info for URL -func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc { - var urlPath = cont.Input.URL() - if !BConfig.RouterCaseSensitive { - urlPath = strings.ToLower(urlPath) - } - httpMethod := cont.Input.Method() - isWildcard := false - // Find policy for current method - t, ok := p.policies[httpMethod] - // If not found - find policy for whole controller - if !ok { - t, ok = p.policies["*"] - isWildcard = true - } - if ok { - runObjects := t.Match(urlPath, cont) - if r, ok := runObjects.([]PolicyFunc); ok { - return r - } else if !isWildcard { - // If no policies found and we checked not for "*" method - try to find it - t, ok = p.policies["*"] - if ok { - runObjects = t.Match(urlPath, cont) - if r, ok = runObjects.([]PolicyFunc); ok { - return r - } - } - } - } - return nil -} - -func (p *ControllerRegister) addToPolicy(method, pattern string, r ...PolicyFunc) { - method = strings.ToUpper(method) - p.enablePolicy = true - if !BConfig.RouterCaseSensitive { - pattern = strings.ToLower(pattern) - } - if t, ok := p.policies[method]; ok { - t.AddRouter(pattern, r) - } else { - t := NewTree() - t.AddRouter(pattern, r) - p.policies[method] = t - } -} - -// Policy Register new policy in beego -func Policy(pattern, method string, policy ...PolicyFunc) { - BeeApp.Handlers.addToPolicy(method, pattern, policy...) -} - -// Find policies and execute if were found -func (p *ControllerRegister) execPolicy(cont *context.Context, urlPath string) (started bool) { - if !p.enablePolicy { - return false - } - // Find Policy for method - policyList := p.FindPolicy(cont) - if len(policyList) > 0 { - // Run policies - for _, runPolicy := range policyList { - runPolicy(cont) - if cont.ResponseWriter.Started { - return true - } - } - return false - } - return false -} diff --git a/vendor/github.com/astaxie/beego/router.go b/vendor/github.com/astaxie/beego/router.go deleted file mode 100644 index a993a1af..00000000 --- a/vendor/github.com/astaxie/beego/router.go +++ /dev/null @@ -1,1052 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "errors" - "fmt" - "net/http" - "os" - "path" - "path/filepath" - "reflect" - "strconv" - "strings" - "sync" - "time" - - beecontext "github.com/astaxie/beego/context" - "github.com/astaxie/beego/context/param" - "github.com/astaxie/beego/logs" - "github.com/astaxie/beego/toolbox" - "github.com/astaxie/beego/utils" -) - -// default filter execution points -const ( - BeforeStatic = iota - BeforeRouter - BeforeExec - AfterExec - FinishRouter -) - -const ( - routerTypeBeego = iota - routerTypeRESTFul - routerTypeHandler -) - -var ( - // HTTPMETHOD list the supported http methods. - HTTPMETHOD = map[string]bool{ - "GET": true, - "POST": true, - "PUT": true, - "DELETE": true, - "PATCH": true, - "OPTIONS": true, - "HEAD": true, - "TRACE": true, - "CONNECT": true, - "MKCOL": true, - "COPY": true, - "MOVE": true, - "PROPFIND": true, - "PROPPATCH": true, - "LOCK": true, - "UNLOCK": true, - } - // these beego.Controller's methods shouldn't reflect to AutoRouter - exceptMethod = []string{"Init", "Prepare", "Finish", "Render", "RenderString", - "RenderBytes", "Redirect", "Abort", "StopRun", "UrlFor", "ServeJSON", "ServeJSONP", - "ServeYAML", "ServeXML", "Input", "ParseForm", "GetString", "GetStrings", "GetInt", "GetBool", - "GetFloat", "GetFile", "SaveToFile", "StartSession", "SetSession", "GetSession", - "DelSession", "SessionRegenerateID", "DestroySession", "IsAjax", "GetSecureCookie", - "SetSecureCookie", "XsrfToken", "CheckXsrfCookie", "XsrfFormHtml", - "GetControllerAndAction", "ServeFormatted"} - - urlPlaceholder = "{{placeholder}}" - // DefaultAccessLogFilter will skip the accesslog if return true - DefaultAccessLogFilter FilterHandler = &logFilter{} -) - -// FilterHandler is an interface for -type FilterHandler interface { - Filter(*beecontext.Context) bool -} - -// default log filter static file will not show -type logFilter struct { -} - -func (l *logFilter) Filter(ctx *beecontext.Context) bool { - requestPath := path.Clean(ctx.Request.URL.Path) - if requestPath == "/favicon.ico" || requestPath == "/robots.txt" { - return true - } - for prefix := range BConfig.WebConfig.StaticDir { - if strings.HasPrefix(requestPath, prefix) { - return true - } - } - return false -} - -// ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter -func ExceptMethodAppend(action string) { - exceptMethod = append(exceptMethod, action) -} - -// ControllerInfo holds information about the controller. -type ControllerInfo struct { - pattern string - controllerType reflect.Type - methods map[string]string - handler http.Handler - runFunction FilterFunc - routerType int - initialize func() ControllerInterface - methodParams []*param.MethodParam -} - -func (c *ControllerInfo) GetPattern() string { - return c.pattern -} - -// ControllerRegister containers registered router rules, controller handlers and filters. -type ControllerRegister struct { - routers map[string]*Tree - enablePolicy bool - policies map[string]*Tree - enableFilter bool - filters [FinishRouter + 1][]*FilterRouter - pool sync.Pool -} - -// NewControllerRegister returns a new ControllerRegister. -func NewControllerRegister() *ControllerRegister { - return &ControllerRegister{ - routers: make(map[string]*Tree), - policies: make(map[string]*Tree), - pool: sync.Pool{ - New: func() interface{} { - return beecontext.NewContext() - }, - }, - } -} - -// Add controller handler and pattern rules to ControllerRegister. -// usage: -// default methods is the same name as method -// Add("/user",&UserController{}) -// Add("/api/list",&RestController{},"*:ListFood") -// Add("/api/create",&RestController{},"post:CreateFood") -// Add("/api/update",&RestController{},"put:UpdateFood") -// Add("/api/delete",&RestController{},"delete:DeleteFood") -// Add("/api",&RestController{},"get,post:ApiFunc" -// Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc") -func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string) { - p.addWithMethodParams(pattern, c, nil, mappingMethods...) -} - -func (p *ControllerRegister) addWithMethodParams(pattern string, c ControllerInterface, methodParams []*param.MethodParam, mappingMethods ...string) { - reflectVal := reflect.ValueOf(c) - t := reflect.Indirect(reflectVal).Type() - methods := make(map[string]string) - if len(mappingMethods) > 0 { - semi := strings.Split(mappingMethods[0], ";") - for _, v := range semi { - colon := strings.Split(v, ":") - if len(colon) != 2 { - panic("method mapping format is invalid") - } - comma := strings.Split(colon[0], ",") - for _, m := range comma { - if m == "*" || HTTPMETHOD[strings.ToUpper(m)] { - if val := reflectVal.MethodByName(colon[1]); val.IsValid() { - methods[strings.ToUpper(m)] = colon[1] - } else { - panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name()) - } - } else { - panic(v + " is an invalid method mapping. Method doesn't exist " + m) - } - } - } - } - - route := &ControllerInfo{} - route.pattern = pattern - route.methods = methods - route.routerType = routerTypeBeego - route.controllerType = t - route.initialize = func() ControllerInterface { - vc := reflect.New(route.controllerType) - execController, ok := vc.Interface().(ControllerInterface) - if !ok { - panic("controller is not ControllerInterface") - } - - elemVal := reflect.ValueOf(c).Elem() - elemType := reflect.TypeOf(c).Elem() - execElem := reflect.ValueOf(execController).Elem() - - numOfFields := elemVal.NumField() - for i := 0; i < numOfFields; i++ { - fieldType := elemType.Field(i) - elemField := execElem.FieldByName(fieldType.Name) - if elemField.CanSet() { - fieldVal := elemVal.Field(i) - elemField.Set(fieldVal) - } - } - - return execController - } - - route.methodParams = methodParams - if len(methods) == 0 { - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - } - } else { - for k := range methods { - if k == "*" { - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - } - } else { - p.addToRouter(k, pattern, route) - } - } - } -} - -func (p *ControllerRegister) addToRouter(method, pattern string, r *ControllerInfo) { - if !BConfig.RouterCaseSensitive { - pattern = strings.ToLower(pattern) - } - if t, ok := p.routers[method]; ok { - t.AddRouter(pattern, r) - } else { - t := NewTree() - t.AddRouter(pattern, r) - p.routers[method] = t - } -} - -// Include only when the Runmode is dev will generate router file in the router/auto.go from the controller -// Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{}) -func (p *ControllerRegister) Include(cList ...ControllerInterface) { - if BConfig.RunMode == DEV { - skip := make(map[string]bool, 10) - wgopath := utils.GetGOPATHs() - go111module := os.Getenv(`GO111MODULE`) - for _, c := range cList { - reflectVal := reflect.ValueOf(c) - t := reflect.Indirect(reflectVal).Type() - // for go modules - if go111module == `on` { - pkgpath := filepath.Join(WorkPath, "..", t.PkgPath()) - if utils.FileExists(pkgpath) { - if pkgpath != "" { - if _, ok := skip[pkgpath]; !ok { - skip[pkgpath] = true - parserPkg(pkgpath, t.PkgPath()) - } - } - } - } else { - if len(wgopath) == 0 { - panic("you are in dev mode. So please set gopath") - } - pkgpath := "" - for _, wg := range wgopath { - wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", t.PkgPath())) - if utils.FileExists(wg) { - pkgpath = wg - break - } - } - if pkgpath != "" { - if _, ok := skip[pkgpath]; !ok { - skip[pkgpath] = true - parserPkg(pkgpath, t.PkgPath()) - } - } - } - } - } - for _, c := range cList { - reflectVal := reflect.ValueOf(c) - t := reflect.Indirect(reflectVal).Type() - key := t.PkgPath() + ":" + t.Name() - if comm, ok := GlobalControllerRouter[key]; ok { - for _, a := range comm { - for _, f := range a.Filters { - p.InsertFilter(f.Pattern, f.Pos, f.Filter, f.ReturnOnOutput, f.ResetParams) - } - - p.addWithMethodParams(a.Router, c, a.MethodParams, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method) - } - } - } -} - -// GetContext returns a context from pool, so usually you should remember to call Reset function to clean the context -// And don't forget to give back context to pool -// example: -// ctx := p.GetContext() -// ctx.Reset(w, q) -// defer p.GiveBackContext(ctx) -func (p *ControllerRegister) GetContext() *beecontext.Context { - return p.pool.Get().(*beecontext.Context) -} - -// GiveBackContext put the ctx into pool so that it could be reuse -func (p *ControllerRegister) GiveBackContext(ctx *beecontext.Context) { - p.pool.Put(ctx) -} - -// Get add get method -// usage: -// Get("/", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Get(pattern string, f FilterFunc) { - p.AddMethod("get", pattern, f) -} - -// Post add post method -// usage: -// Post("/api", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Post(pattern string, f FilterFunc) { - p.AddMethod("post", pattern, f) -} - -// Put add put method -// usage: -// Put("/api/:id", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Put(pattern string, f FilterFunc) { - p.AddMethod("put", pattern, f) -} - -// Delete add delete method -// usage: -// Delete("/api/:id", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Delete(pattern string, f FilterFunc) { - p.AddMethod("delete", pattern, f) -} - -// Head add head method -// usage: -// Head("/api/:id", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Head(pattern string, f FilterFunc) { - p.AddMethod("head", pattern, f) -} - -// Patch add patch method -// usage: -// Patch("/api/:id", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Patch(pattern string, f FilterFunc) { - p.AddMethod("patch", pattern, f) -} - -// Options add options method -// usage: -// Options("/api/:id", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Options(pattern string, f FilterFunc) { - p.AddMethod("options", pattern, f) -} - -// Any add all method -// usage: -// Any("/api/:id", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) Any(pattern string, f FilterFunc) { - p.AddMethod("*", pattern, f) -} - -// AddMethod add http method router -// usage: -// AddMethod("get","/api/:id", func(ctx *context.Context){ -// ctx.Output.Body("hello world") -// }) -func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) { - method = strings.ToUpper(method) - if method != "*" && !HTTPMETHOD[method] { - panic("not support http method: " + method) - } - route := &ControllerInfo{} - route.pattern = pattern - route.routerType = routerTypeRESTFul - route.runFunction = f - methods := make(map[string]string) - if method == "*" { - for val := range HTTPMETHOD { - methods[val] = val - } - } else { - methods[method] = method - } - route.methods = methods - for k := range methods { - if k == "*" { - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - } - } else { - p.addToRouter(k, pattern, route) - } - } -} - -// Handler add user defined Handler -func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{}) { - route := &ControllerInfo{} - route.pattern = pattern - route.routerType = routerTypeHandler - route.handler = h - if len(options) > 0 { - if _, ok := options[0].(bool); ok { - pattern = path.Join(pattern, "?:all(.*)") - } - } - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - } -} - -// AddAuto router to ControllerRegister. -// example beego.AddAuto(&MainContorlller{}), -// MainController has method List and Page. -// visit the url /main/list to execute List function -// /main/page to execute Page function. -func (p *ControllerRegister) AddAuto(c ControllerInterface) { - p.AddAutoPrefix("/", c) -} - -// AddAutoPrefix Add auto router to ControllerRegister with prefix. -// example beego.AddAutoPrefix("/admin",&MainContorlller{}), -// MainController has method List and Page. -// visit the url /admin/main/list to execute List function -// /admin/main/page to execute Page function. -func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface) { - reflectVal := reflect.ValueOf(c) - rt := reflectVal.Type() - ct := reflect.Indirect(reflectVal).Type() - controllerName := strings.TrimSuffix(ct.Name(), "Controller") - for i := 0; i < rt.NumMethod(); i++ { - if !utils.InSlice(rt.Method(i).Name, exceptMethod) { - route := &ControllerInfo{} - route.routerType = routerTypeBeego - route.methods = map[string]string{"*": rt.Method(i).Name} - route.controllerType = ct - pattern := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name), "*") - patternInit := path.Join(prefix, controllerName, rt.Method(i).Name, "*") - patternFix := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name)) - patternFixInit := path.Join(prefix, controllerName, rt.Method(i).Name) - route.pattern = pattern - for m := range HTTPMETHOD { - p.addToRouter(m, pattern, route) - p.addToRouter(m, patternInit, route) - p.addToRouter(m, patternFix, route) - p.addToRouter(m, patternFixInit, route) - } - } - } -} - -// InsertFilter Add a FilterFunc with pattern rule and action constant. -// params is for: -// 1. setting the returnOnOutput value (false allows multiple filters to execute) -// 2. determining whether or not params need to be reset. -func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error { - mr := &FilterRouter{ - tree: NewTree(), - pattern: pattern, - filterFunc: filter, - returnOnOutput: true, - } - if !BConfig.RouterCaseSensitive { - mr.pattern = strings.ToLower(pattern) - } - - paramsLen := len(params) - if paramsLen > 0 { - mr.returnOnOutput = params[0] - } - if paramsLen > 1 { - mr.resetParams = params[1] - } - mr.tree.AddRouter(pattern, true) - return p.insertFilterRouter(pos, mr) -} - -// add Filter into -func (p *ControllerRegister) insertFilterRouter(pos int, mr *FilterRouter) (err error) { - if pos < BeforeStatic || pos > FinishRouter { - return errors.New("can not find your filter position") - } - p.enableFilter = true - p.filters[pos] = append(p.filters[pos], mr) - return nil -} - -// URLFor does another controller handler in this request function. -// it can access any controller method. -func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string { - paths := strings.Split(endpoint, ".") - if len(paths) <= 1 { - logs.Warn("urlfor endpoint must like path.controller.method") - return "" - } - if len(values)%2 != 0 { - logs.Warn("urlfor params must key-value pair") - return "" - } - params := make(map[string]string) - if len(values) > 0 { - key := "" - for k, v := range values { - if k%2 == 0 { - key = fmt.Sprint(v) - } else { - params[key] = fmt.Sprint(v) - } - } - } - controllerName := strings.Join(paths[:len(paths)-1], "/") - methodName := paths[len(paths)-1] - for m, t := range p.routers { - ok, url := p.getURL(t, "/", controllerName, methodName, params, m) - if ok { - return url - } - } - return "" -} - -func (p *ControllerRegister) getURL(t *Tree, url, controllerName, methodName string, params map[string]string, httpMethod string) (bool, string) { - for _, subtree := range t.fixrouters { - u := path.Join(url, subtree.prefix) - ok, u := p.getURL(subtree, u, controllerName, methodName, params, httpMethod) - if ok { - return ok, u - } - } - if t.wildcard != nil { - u := path.Join(url, urlPlaceholder) - ok, u := p.getURL(t.wildcard, u, controllerName, methodName, params, httpMethod) - if ok { - return ok, u - } - } - for _, l := range t.leaves { - if c, ok := l.runObject.(*ControllerInfo); ok { - if c.routerType == routerTypeBeego && - strings.HasSuffix(path.Join(c.controllerType.PkgPath(), c.controllerType.Name()), controllerName) { - find := false - if HTTPMETHOD[strings.ToUpper(methodName)] { - if len(c.methods) == 0 { - find = true - } else if m, ok := c.methods[strings.ToUpper(methodName)]; ok && m == strings.ToUpper(methodName) { - find = true - } else if m, ok = c.methods["*"]; ok && m == methodName { - find = true - } - } - if !find { - for m, md := range c.methods { - if (m == "*" || m == httpMethod) && md == methodName { - find = true - } - } - } - if find { - if l.regexps == nil { - if len(l.wildcards) == 0 { - return true, strings.Replace(url, "/"+urlPlaceholder, "", 1) + toURL(params) - } - if len(l.wildcards) == 1 { - if v, ok := params[l.wildcards[0]]; ok { - delete(params, l.wildcards[0]) - return true, strings.Replace(url, urlPlaceholder, v, 1) + toURL(params) - } - return false, "" - } - if len(l.wildcards) == 3 && l.wildcards[0] == "." { - if p, ok := params[":path"]; ok { - if e, isok := params[":ext"]; isok { - delete(params, ":path") - delete(params, ":ext") - return true, strings.Replace(url, urlPlaceholder, p+"."+e, -1) + toURL(params) - } - } - } - canSkip := false - for _, v := range l.wildcards { - if v == ":" { - canSkip = true - continue - } - if u, ok := params[v]; ok { - delete(params, v) - url = strings.Replace(url, urlPlaceholder, u, 1) - } else { - if canSkip { - canSkip = false - continue - } - return false, "" - } - } - return true, url + toURL(params) - } - var i int - var startReg bool - regURL := "" - for _, v := range strings.Trim(l.regexps.String(), "^$") { - if v == '(' { - startReg = true - continue - } else if v == ')' { - startReg = false - if v, ok := params[l.wildcards[i]]; ok { - delete(params, l.wildcards[i]) - regURL = regURL + v - i++ - } else { - break - } - } else if !startReg { - regURL = string(append([]rune(regURL), v)) - } - } - if l.regexps.MatchString(regURL) { - ps := strings.Split(regURL, "/") - for _, p := range ps { - url = strings.Replace(url, urlPlaceholder, p, 1) - } - return true, url + toURL(params) - } - } - } - } - } - - return false, "" -} - -func (p *ControllerRegister) execFilter(context *beecontext.Context, urlPath string, pos int) (started bool) { - var preFilterParams map[string]string - for _, filterR := range p.filters[pos] { - if filterR.returnOnOutput && context.ResponseWriter.Started { - return true - } - if filterR.resetParams { - preFilterParams = context.Input.Params() - } - if ok := filterR.ValidRouter(urlPath, context); ok { - filterR.filterFunc(context) - if filterR.resetParams { - context.Input.ResetParams() - for k, v := range preFilterParams { - context.Input.SetParam(k, v) - } - } - } - if filterR.returnOnOutput && context.ResponseWriter.Started { - return true - } - } - return false -} - -// Implement http.Handler interface. -func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - startTime := time.Now() - var ( - runRouter reflect.Type - findRouter bool - runMethod string - methodParams []*param.MethodParam - routerInfo *ControllerInfo - isRunnable bool - ) - context := p.GetContext() - - context.Reset(rw, r) - - defer p.GiveBackContext(context) - if BConfig.RecoverFunc != nil { - defer BConfig.RecoverFunc(context) - } - - context.Output.EnableGzip = BConfig.EnableGzip - - if BConfig.RunMode == DEV { - context.Output.Header("Server", BConfig.ServerName) - } - - var urlPath = r.URL.Path - - if !BConfig.RouterCaseSensitive { - urlPath = strings.ToLower(urlPath) - } - - // filter wrong http method - if !HTTPMETHOD[r.Method] { - exception("405", context) - goto Admin - } - - // filter for static file - if len(p.filters[BeforeStatic]) > 0 && p.execFilter(context, urlPath, BeforeStatic) { - goto Admin - } - - serverStaticRouter(context) - - if context.ResponseWriter.Started { - findRouter = true - goto Admin - } - - if r.Method != http.MethodGet && r.Method != http.MethodHead { - if BConfig.CopyRequestBody && !context.Input.IsUpload() { - // connection will close if the incoming data are larger (RFC 7231, 6.5.11) - if r.ContentLength > BConfig.MaxMemory { - logs.Error(errors.New("payload too large")) - exception("413", context) - goto Admin - } - context.Input.CopyBody(BConfig.MaxMemory) - } - context.Input.ParseFormOrMulitForm(BConfig.MaxMemory) - } - - // session init - if BConfig.WebConfig.Session.SessionOn { - var err error - context.Input.CruSession, err = GlobalSessions.SessionStart(rw, r) - if err != nil { - logs.Error(err) - exception("503", context) - goto Admin - } - defer func() { - if context.Input.CruSession != nil { - context.Input.CruSession.SessionRelease(rw) - } - }() - } - if len(p.filters[BeforeRouter]) > 0 && p.execFilter(context, urlPath, BeforeRouter) { - goto Admin - } - // User can define RunController and RunMethod in filter - if context.Input.RunController != nil && context.Input.RunMethod != "" { - findRouter = true - runMethod = context.Input.RunMethod - runRouter = context.Input.RunController - } else { - routerInfo, findRouter = p.FindRouter(context) - } - - // if no matches to url, throw a not found exception - if !findRouter { - exception("404", context) - goto Admin - } - if splat := context.Input.Param(":splat"); splat != "" { - for k, v := range strings.Split(splat, "/") { - context.Input.SetParam(strconv.Itoa(k), v) - } - } - - if routerInfo != nil { - // store router pattern into context - context.Input.SetData("RouterPattern", routerInfo.pattern) - } - - // execute middleware filters - if len(p.filters[BeforeExec]) > 0 && p.execFilter(context, urlPath, BeforeExec) { - goto Admin - } - - // check policies - if p.execPolicy(context, urlPath) { - goto Admin - } - - if routerInfo != nil { - if routerInfo.routerType == routerTypeRESTFul { - if _, ok := routerInfo.methods[r.Method]; ok { - isRunnable = true - routerInfo.runFunction(context) - } else { - exception("405", context) - goto Admin - } - } else if routerInfo.routerType == routerTypeHandler { - isRunnable = true - routerInfo.handler.ServeHTTP(context.ResponseWriter, context.Request) - } else { - runRouter = routerInfo.controllerType - methodParams = routerInfo.methodParams - method := r.Method - if r.Method == http.MethodPost && context.Input.Query("_method") == http.MethodPut { - method = http.MethodPut - } - if r.Method == http.MethodPost && context.Input.Query("_method") == http.MethodDelete { - method = http.MethodDelete - } - if m, ok := routerInfo.methods[method]; ok { - runMethod = m - } else if m, ok = routerInfo.methods["*"]; ok { - runMethod = m - } else { - runMethod = method - } - } - } - - // also defined runRouter & runMethod from filter - if !isRunnable { - // Invoke the request handler - var execController ControllerInterface - if routerInfo != nil && routerInfo.initialize != nil { - execController = routerInfo.initialize() - } else { - vc := reflect.New(runRouter) - var ok bool - execController, ok = vc.Interface().(ControllerInterface) - if !ok { - panic("controller is not ControllerInterface") - } - } - - // call the controller init function - execController.Init(context, runRouter.Name(), runMethod, execController) - - // call prepare function - execController.Prepare() - - // if XSRF is Enable then check cookie where there has any cookie in the request's cookie _csrf - if BConfig.WebConfig.EnableXSRF { - execController.XSRFToken() - if r.Method == http.MethodPost || r.Method == http.MethodDelete || r.Method == http.MethodPut || - (r.Method == http.MethodPost && (context.Input.Query("_method") == http.MethodDelete || context.Input.Query("_method") == http.MethodPut)) { - execController.CheckXSRFCookie() - } - } - - execController.URLMapping() - - if !context.ResponseWriter.Started { - // exec main logic - switch runMethod { - case http.MethodGet: - execController.Get() - case http.MethodPost: - execController.Post() - case http.MethodDelete: - execController.Delete() - case http.MethodPut: - execController.Put() - case http.MethodHead: - execController.Head() - case http.MethodPatch: - execController.Patch() - case http.MethodOptions: - execController.Options() - case http.MethodTrace: - execController.Trace() - default: - if !execController.HandlerFunc(runMethod) { - vc := reflect.ValueOf(execController) - method := vc.MethodByName(runMethod) - in := param.ConvertParams(methodParams, method.Type(), context) - out := method.Call(in) - - // For backward compatibility we only handle response if we had incoming methodParams - if methodParams != nil { - p.handleParamResponse(context, execController, out) - } - } - } - - // render template - if !context.ResponseWriter.Started && context.Output.Status == 0 { - if BConfig.WebConfig.AutoRender { - if err := execController.Render(); err != nil { - logs.Error(err) - } - } - } - } - - // finish all runRouter. release resource - execController.Finish() - } - - // execute middleware filters - if len(p.filters[AfterExec]) > 0 && p.execFilter(context, urlPath, AfterExec) { - goto Admin - } - - if len(p.filters[FinishRouter]) > 0 && p.execFilter(context, urlPath, FinishRouter) { - goto Admin - } - -Admin: - // admin module record QPS - - statusCode := context.ResponseWriter.Status - if statusCode == 0 { - statusCode = 200 - } - - LogAccess(context, &startTime, statusCode) - - timeDur := time.Since(startTime) - context.ResponseWriter.Elapsed = timeDur - if BConfig.Listen.EnableAdmin { - pattern := "" - if routerInfo != nil { - pattern = routerInfo.pattern - } - - if FilterMonitorFunc(r.Method, r.URL.Path, timeDur, pattern, statusCode) { - routerName := "" - if runRouter != nil { - routerName = runRouter.Name() - } - go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, routerName, timeDur) - } - } - - if BConfig.RunMode == DEV && !BConfig.Log.AccessLogs { - match := map[bool]string{true: "match", false: "nomatch"} - devInfo := fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s", - context.Input.IP(), - logs.ColorByStatus(statusCode), statusCode, logs.ResetColor(), - timeDur.String(), - match[findRouter], - logs.ColorByMethod(r.Method), r.Method, logs.ResetColor(), - r.URL.Path) - if routerInfo != nil { - devInfo += fmt.Sprintf(" r:%s", routerInfo.pattern) - } - - logs.Debug(devInfo) - } - // Call WriteHeader if status code has been set changed - if context.Output.Status != 0 { - context.ResponseWriter.WriteHeader(context.Output.Status) - } -} - -func (p *ControllerRegister) handleParamResponse(context *beecontext.Context, execController ControllerInterface, results []reflect.Value) { - // looping in reverse order for the case when both error and value are returned and error sets the response status code - for i := len(results) - 1; i >= 0; i-- { - result := results[i] - if result.Kind() != reflect.Interface || !result.IsNil() { - resultValue := result.Interface() - context.RenderMethodResult(resultValue) - } - } - if !context.ResponseWriter.Started && len(results) > 0 && context.Output.Status == 0 { - context.Output.SetStatus(200) - } -} - -// FindRouter Find Router info for URL -func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) { - var urlPath = context.Input.URL() - if !BConfig.RouterCaseSensitive { - urlPath = strings.ToLower(urlPath) - } - httpMethod := context.Input.Method() - if t, ok := p.routers[httpMethod]; ok { - runObject := t.Match(urlPath, context) - if r, ok := runObject.(*ControllerInfo); ok { - return r, true - } - } - return -} - -func toURL(params map[string]string) string { - if len(params) == 0 { - return "" - } - u := "?" - for k, v := range params { - u += k + "=" + v + "&" - } - return strings.TrimRight(u, "&") -} - -// LogAccess logging info HTTP Access -func LogAccess(ctx *beecontext.Context, startTime *time.Time, statusCode int) { - // Skip logging if AccessLogs config is false - if !BConfig.Log.AccessLogs { - return - } - // Skip logging static requests unless EnableStaticLogs config is true - if !BConfig.Log.EnableStaticLogs && DefaultAccessLogFilter.Filter(ctx) { - return - } - var ( - requestTime time.Time - elapsedTime time.Duration - r = ctx.Request - ) - if startTime != nil { - requestTime = *startTime - elapsedTime = time.Since(*startTime) - } - record := &logs.AccessLogRecord{ - RemoteAddr: ctx.Input.IP(), - RequestTime: requestTime, - RequestMethod: r.Method, - Request: fmt.Sprintf("%s %s %s", r.Method, r.RequestURI, r.Proto), - ServerProtocol: r.Proto, - Host: r.Host, - Status: statusCode, - ElapsedTime: elapsedTime, - HTTPReferrer: r.Header.Get("Referer"), - HTTPUserAgent: r.Header.Get("User-Agent"), - RemoteUser: r.Header.Get("Remote-User"), - BodyBytesSent: 0, // @todo this one is missing! - } - logs.AccessLog(record, BConfig.Log.AccessLogsFormat) -} diff --git a/vendor/github.com/astaxie/beego/session/README.md b/vendor/github.com/astaxie/beego/session/README.md deleted file mode 100644 index 6d0a297e..00000000 --- a/vendor/github.com/astaxie/beego/session/README.md +++ /dev/null @@ -1,114 +0,0 @@ -session -============== - -session is a Go session manager. It can use many session providers. Just like the `database/sql` and `database/sql/driver`. - -## How to install? - - go get github.com/astaxie/beego/session - - -## What providers are supported? - -As of now this session manager support memory, file, Redis and MySQL. - - -## How to use it? - -First you must import it - - import ( - "github.com/astaxie/beego/session" - ) - -Then in you web app init the global session manager - - var globalSessions *session.Manager - -* Use **memory** as provider: - - func init() { - globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid","gclifetime":3600}`) - go globalSessions.GC() - } - -* Use **file** as provider, the last param is the path where you want file to be stored: - - func init() { - globalSessions, _ = session.NewManager("file",`{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"./tmp"}`) - go globalSessions.GC() - } - -* Use **Redis** as provider, the last param is the Redis conn address,poolsize,password: - - func init() { - globalSessions, _ = session.NewManager("redis", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:6379,100,astaxie"}`) - go globalSessions.GC() - } - -* Use **MySQL** as provider, the last param is the DSN, learn more from [mysql](https://github.com/go-sql-driver/mysql#dsn-data-source-name): - - func init() { - globalSessions, _ = session.NewManager( - "mysql", `{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"username:password@protocol(address)/dbname?param=value"}`) - go globalSessions.GC() - } - -* Use **Cookie** as provider: - - func init() { - globalSessions, _ = session.NewManager( - "cookie", `{"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}`) - go globalSessions.GC() - } - - -Finally in the handlerfunc you can use it like this - - func login(w http.ResponseWriter, r *http.Request) { - sess := globalSessions.SessionStart(w, r) - defer sess.SessionRelease(w) - username := sess.Get("username") - fmt.Println(username) - if r.Method == "GET" { - t, _ := template.ParseFiles("login.gtpl") - t.Execute(w, nil) - } else { - fmt.Println("username:", r.Form["username"]) - sess.Set("username", r.Form["username"]) - fmt.Println("password:", r.Form["password"]) - } - } - - -## How to write own provider? - -When you develop a web app, maybe you want to write own provider because you must meet the requirements. - -Writing a provider is easy. You only need to define two struct types -(Session and Provider), which satisfy the interface definition. -Maybe you will find the **memory** provider is a good example. - - type SessionStore interface { - Set(key, value interface{}) error //set session value - Get(key interface{}) interface{} //get session value - Delete(key interface{}) error //delete session value - SessionID() string //back current sessionID - SessionRelease(w http.ResponseWriter) // release the resource & save data to provider & return the data - Flush() error //delete all data - } - - type Provider interface { - SessionInit(gclifetime int64, config string) error - SessionRead(sid string) (SessionStore, error) - SessionExist(sid string) bool - SessionRegenerate(oldsid, sid string) (SessionStore, error) - SessionDestroy(sid string) error - SessionAll() int //get all active session - SessionGC() - } - - -## LICENSE - -BSD License http://creativecommons.org/licenses/BSD/ diff --git a/vendor/github.com/astaxie/beego/session/sess_cookie.go b/vendor/github.com/astaxie/beego/session/sess_cookie.go deleted file mode 100644 index 6ad5debc..00000000 --- a/vendor/github.com/astaxie/beego/session/sess_cookie.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package session - -import ( - "crypto/aes" - "crypto/cipher" - "encoding/json" - "net/http" - "net/url" - "sync" -) - -var cookiepder = &CookieProvider{} - -// CookieSessionStore Cookie SessionStore -type CookieSessionStore struct { - sid string - values map[interface{}]interface{} // session data - lock sync.RWMutex -} - -// Set value to cookie session. -// the value are encoded as gob with hash block string. -func (st *CookieSessionStore) Set(key, value interface{}) error { - st.lock.Lock() - defer st.lock.Unlock() - st.values[key] = value - return nil -} - -// Get value from cookie session -func (st *CookieSessionStore) Get(key interface{}) interface{} { - st.lock.RLock() - defer st.lock.RUnlock() - if v, ok := st.values[key]; ok { - return v - } - return nil -} - -// Delete value in cookie session -func (st *CookieSessionStore) Delete(key interface{}) error { - st.lock.Lock() - defer st.lock.Unlock() - delete(st.values, key) - return nil -} - -// Flush Clean all values in cookie session -func (st *CookieSessionStore) Flush() error { - st.lock.Lock() - defer st.lock.Unlock() - st.values = make(map[interface{}]interface{}) - return nil -} - -// SessionID Return id of this cookie session -func (st *CookieSessionStore) SessionID() string { - return st.sid -} - -// SessionRelease Write cookie session to http response cookie -func (st *CookieSessionStore) SessionRelease(w http.ResponseWriter) { - st.lock.Lock() - encodedCookie, err := encodeCookie(cookiepder.block, cookiepder.config.SecurityKey, cookiepder.config.SecurityName, st.values) - st.lock.Unlock() - if err == nil { - cookie := &http.Cookie{Name: cookiepder.config.CookieName, - Value: url.QueryEscape(encodedCookie), - Path: "/", - HttpOnly: true, - Secure: cookiepder.config.Secure, - MaxAge: cookiepder.config.Maxage} - http.SetCookie(w, cookie) - } -} - -type cookieConfig struct { - SecurityKey string `json:"securityKey"` - BlockKey string `json:"blockKey"` - SecurityName string `json:"securityName"` - CookieName string `json:"cookieName"` - Secure bool `json:"secure"` - Maxage int `json:"maxage"` -} - -// CookieProvider Cookie session provider -type CookieProvider struct { - maxlifetime int64 - config *cookieConfig - block cipher.Block -} - -// SessionInit Init cookie session provider with max lifetime and config json. -// maxlifetime is ignored. -// json config: -// securityKey - hash string -// blockKey - gob encode hash string. it's saved as aes crypto. -// securityName - recognized name in encoded cookie string -// cookieName - cookie name -// maxage - cookie max life time. -func (pder *CookieProvider) SessionInit(maxlifetime int64, config string) error { - pder.config = &cookieConfig{} - err := json.Unmarshal([]byte(config), pder.config) - if err != nil { - return err - } - if pder.config.BlockKey == "" { - pder.config.BlockKey = string(generateRandomKey(16)) - } - if pder.config.SecurityName == "" { - pder.config.SecurityName = string(generateRandomKey(20)) - } - pder.block, err = aes.NewCipher([]byte(pder.config.BlockKey)) - if err != nil { - return err - } - pder.maxlifetime = maxlifetime - return nil -} - -// SessionRead Get SessionStore in cooke. -// decode cooke string to map and put into SessionStore with sid. -func (pder *CookieProvider) SessionRead(sid string) (Store, error) { - maps, _ := decodeCookie(pder.block, - pder.config.SecurityKey, - pder.config.SecurityName, - sid, pder.maxlifetime) - if maps == nil { - maps = make(map[interface{}]interface{}) - } - rs := &CookieSessionStore{sid: sid, values: maps} - return rs, nil -} - -// SessionExist Cookie session is always existed -func (pder *CookieProvider) SessionExist(sid string) bool { - return true -} - -// SessionRegenerate Implement method, no used. -func (pder *CookieProvider) SessionRegenerate(oldsid, sid string) (Store, error) { - return nil, nil -} - -// SessionDestroy Implement method, no used. -func (pder *CookieProvider) SessionDestroy(sid string) error { - return nil -} - -// SessionGC Implement method, no used. -func (pder *CookieProvider) SessionGC() { -} - -// SessionAll Implement method, return 0. -func (pder *CookieProvider) SessionAll() int { - return 0 -} - -// SessionUpdate Implement method, no used. -func (pder *CookieProvider) SessionUpdate(sid string) error { - return nil -} - -func init() { - Register("cookie", cookiepder) -} diff --git a/vendor/github.com/astaxie/beego/session/sess_file.go b/vendor/github.com/astaxie/beego/session/sess_file.go deleted file mode 100644 index 47ad54a7..00000000 --- a/vendor/github.com/astaxie/beego/session/sess_file.go +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package session - -import ( - "errors" - "fmt" - "io/ioutil" - "net/http" - "os" - "path" - "path/filepath" - "strings" - "sync" - "time" -) - -var ( - filepder = &FileProvider{} - gcmaxlifetime int64 -) - -// FileSessionStore File session store -type FileSessionStore struct { - sid string - lock sync.RWMutex - values map[interface{}]interface{} -} - -// Set value to file session -func (fs *FileSessionStore) Set(key, value interface{}) error { - fs.lock.Lock() - defer fs.lock.Unlock() - fs.values[key] = value - return nil -} - -// Get value from file session -func (fs *FileSessionStore) Get(key interface{}) interface{} { - fs.lock.RLock() - defer fs.lock.RUnlock() - if v, ok := fs.values[key]; ok { - return v - } - return nil -} - -// Delete value in file session by given key -func (fs *FileSessionStore) Delete(key interface{}) error { - fs.lock.Lock() - defer fs.lock.Unlock() - delete(fs.values, key) - return nil -} - -// Flush Clean all values in file session -func (fs *FileSessionStore) Flush() error { - fs.lock.Lock() - defer fs.lock.Unlock() - fs.values = make(map[interface{}]interface{}) - return nil -} - -// SessionID Get file session store id -func (fs *FileSessionStore) SessionID() string { - return fs.sid -} - -// SessionRelease Write file session to local file with Gob string -func (fs *FileSessionStore) SessionRelease(w http.ResponseWriter) { - filepder.lock.Lock() - defer filepder.lock.Unlock() - b, err := EncodeGob(fs.values) - if err != nil { - SLogger.Println(err) - return - } - _, err = os.Stat(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid)) - var f *os.File - if err == nil { - f, err = os.OpenFile(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid), os.O_RDWR, 0777) - if err != nil { - SLogger.Println(err) - return - } - } else if os.IsNotExist(err) { - f, err = os.Create(path.Join(filepder.savePath, string(fs.sid[0]), string(fs.sid[1]), fs.sid)) - if err != nil { - SLogger.Println(err) - return - } - } else { - return - } - f.Truncate(0) - f.Seek(0, 0) - f.Write(b) - f.Close() -} - -// FileProvider File session provider -type FileProvider struct { - lock sync.RWMutex - maxlifetime int64 - savePath string -} - -// SessionInit Init file session provider. -// savePath sets the session files path. -func (fp *FileProvider) SessionInit(maxlifetime int64, savePath string) error { - fp.maxlifetime = maxlifetime - fp.savePath = savePath - return nil -} - -// SessionRead Read file session by sid. -// if file is not exist, create it. -// the file path is generated from sid string. -func (fp *FileProvider) SessionRead(sid string) (Store, error) { - invalidChars := "./" - if strings.ContainsAny(sid, invalidChars) { - return nil, errors.New("the sid shouldn't have following characters: " + invalidChars) - } - if len(sid) < 2 { - return nil, errors.New("length of the sid is less than 2") - } - filepder.lock.Lock() - defer filepder.lock.Unlock() - - err := os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0755) - if err != nil { - SLogger.Println(err.Error()) - } - _, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid)) - var f *os.File - if err == nil { - f, err = os.OpenFile(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), os.O_RDWR, 0777) - } else if os.IsNotExist(err) { - f, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid)) - } else { - return nil, err - } - - defer f.Close() - - os.Chtimes(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), time.Now(), time.Now()) - var kv map[interface{}]interface{} - b, err := ioutil.ReadAll(f) - if err != nil { - return nil, err - } - if len(b) == 0 { - kv = make(map[interface{}]interface{}) - } else { - kv, err = DecodeGob(b) - if err != nil { - return nil, err - } - } - - ss := &FileSessionStore{sid: sid, values: kv} - return ss, nil -} - -// SessionExist Check file session exist. -// it checks the file named from sid exist or not. -func (fp *FileProvider) SessionExist(sid string) bool { - filepder.lock.Lock() - defer filepder.lock.Unlock() - - if len(sid) < 2 { - SLogger.Println("min length of session id is 2", sid) - return false - } - - _, err := os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid)) - return err == nil -} - -// SessionDestroy Remove all files in this save path -func (fp *FileProvider) SessionDestroy(sid string) error { - filepder.lock.Lock() - defer filepder.lock.Unlock() - os.Remove(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid)) - return nil -} - -// SessionGC Recycle files in save path -func (fp *FileProvider) SessionGC() { - filepder.lock.Lock() - defer filepder.lock.Unlock() - - gcmaxlifetime = fp.maxlifetime - filepath.Walk(fp.savePath, gcpath) -} - -// SessionAll Get active file session number. -// it walks save path to count files. -func (fp *FileProvider) SessionAll() int { - a := &activeSession{} - err := filepath.Walk(fp.savePath, func(path string, f os.FileInfo, err error) error { - return a.visit(path, f, err) - }) - if err != nil { - SLogger.Printf("filepath.Walk() returned %v\n", err) - return 0 - } - return a.total -} - -// SessionRegenerate Generate new sid for file session. -// it delete old file and create new file named from new sid. -func (fp *FileProvider) SessionRegenerate(oldsid, sid string) (Store, error) { - filepder.lock.Lock() - defer filepder.lock.Unlock() - - oldPath := path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1])) - oldSidFile := path.Join(oldPath, oldsid) - newPath := path.Join(fp.savePath, string(sid[0]), string(sid[1])) - newSidFile := path.Join(newPath, sid) - - // new sid file is exist - _, err := os.Stat(newSidFile) - if err == nil { - return nil, fmt.Errorf("newsid %s exist", newSidFile) - } - - err = os.MkdirAll(newPath, 0755) - if err != nil { - SLogger.Println(err.Error()) - } - - // if old sid file exist - // 1.read and parse file content - // 2.write content to new sid file - // 3.remove old sid file, change new sid file atime and ctime - // 4.return FileSessionStore - _, err = os.Stat(oldSidFile) - if err == nil { - b, err := ioutil.ReadFile(oldSidFile) - if err != nil { - return nil, err - } - - var kv map[interface{}]interface{} - if len(b) == 0 { - kv = make(map[interface{}]interface{}) - } else { - kv, err = DecodeGob(b) - if err != nil { - return nil, err - } - } - - ioutil.WriteFile(newSidFile, b, 0777) - os.Remove(oldSidFile) - os.Chtimes(newSidFile, time.Now(), time.Now()) - ss := &FileSessionStore{sid: sid, values: kv} - return ss, nil - } - - // if old sid file not exist, just create new sid file and return - newf, err := os.Create(newSidFile) - if err != nil { - return nil, err - } - newf.Close() - ss := &FileSessionStore{sid: sid, values: make(map[interface{}]interface{})} - return ss, nil -} - -// remove file in save path if expired -func gcpath(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if info.IsDir() { - return nil - } - if (info.ModTime().Unix() + gcmaxlifetime) < time.Now().Unix() { - os.Remove(path) - } - return nil -} - -type activeSession struct { - total int -} - -func (as *activeSession) visit(paths string, f os.FileInfo, err error) error { - if err != nil { - return err - } - if f.IsDir() { - return nil - } - as.total = as.total + 1 - return nil -} - -func init() { - Register("file", filepder) -} diff --git a/vendor/github.com/astaxie/beego/session/sess_mem.go b/vendor/github.com/astaxie/beego/session/sess_mem.go deleted file mode 100644 index 64d8b056..00000000 --- a/vendor/github.com/astaxie/beego/session/sess_mem.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package session - -import ( - "container/list" - "net/http" - "sync" - "time" -) - -var mempder = &MemProvider{list: list.New(), sessions: make(map[string]*list.Element)} - -// MemSessionStore memory session store. -// it saved sessions in a map in memory. -type MemSessionStore struct { - sid string //session id - timeAccessed time.Time //last access time - value map[interface{}]interface{} //session store - lock sync.RWMutex -} - -// Set value to memory session -func (st *MemSessionStore) Set(key, value interface{}) error { - st.lock.Lock() - defer st.lock.Unlock() - st.value[key] = value - return nil -} - -// Get value from memory session by key -func (st *MemSessionStore) Get(key interface{}) interface{} { - st.lock.RLock() - defer st.lock.RUnlock() - if v, ok := st.value[key]; ok { - return v - } - return nil -} - -// Delete in memory session by key -func (st *MemSessionStore) Delete(key interface{}) error { - st.lock.Lock() - defer st.lock.Unlock() - delete(st.value, key) - return nil -} - -// Flush clear all values in memory session -func (st *MemSessionStore) Flush() error { - st.lock.Lock() - defer st.lock.Unlock() - st.value = make(map[interface{}]interface{}) - return nil -} - -// SessionID get this id of memory session store -func (st *MemSessionStore) SessionID() string { - return st.sid -} - -// SessionRelease Implement method, no used. -func (st *MemSessionStore) SessionRelease(w http.ResponseWriter) { -} - -// MemProvider Implement the provider interface -type MemProvider struct { - lock sync.RWMutex // locker - sessions map[string]*list.Element // map in memory - list *list.List // for gc - maxlifetime int64 - savePath string -} - -// SessionInit init memory session -func (pder *MemProvider) SessionInit(maxlifetime int64, savePath string) error { - pder.maxlifetime = maxlifetime - pder.savePath = savePath - return nil -} - -// SessionRead get memory session store by sid -func (pder *MemProvider) SessionRead(sid string) (Store, error) { - pder.lock.RLock() - if element, ok := pder.sessions[sid]; ok { - go pder.SessionUpdate(sid) - pder.lock.RUnlock() - return element.Value.(*MemSessionStore), nil - } - pder.lock.RUnlock() - pder.lock.Lock() - newsess := &MemSessionStore{sid: sid, timeAccessed: time.Now(), value: make(map[interface{}]interface{})} - element := pder.list.PushFront(newsess) - pder.sessions[sid] = element - pder.lock.Unlock() - return newsess, nil -} - -// SessionExist check session store exist in memory session by sid -func (pder *MemProvider) SessionExist(sid string) bool { - pder.lock.RLock() - defer pder.lock.RUnlock() - if _, ok := pder.sessions[sid]; ok { - return true - } - return false -} - -// SessionRegenerate generate new sid for session store in memory session -func (pder *MemProvider) SessionRegenerate(oldsid, sid string) (Store, error) { - pder.lock.RLock() - if element, ok := pder.sessions[oldsid]; ok { - go pder.SessionUpdate(oldsid) - pder.lock.RUnlock() - pder.lock.Lock() - element.Value.(*MemSessionStore).sid = sid - pder.sessions[sid] = element - delete(pder.sessions, oldsid) - pder.lock.Unlock() - return element.Value.(*MemSessionStore), nil - } - pder.lock.RUnlock() - pder.lock.Lock() - newsess := &MemSessionStore{sid: sid, timeAccessed: time.Now(), value: make(map[interface{}]interface{})} - element := pder.list.PushFront(newsess) - pder.sessions[sid] = element - pder.lock.Unlock() - return newsess, nil -} - -// SessionDestroy delete session store in memory session by id -func (pder *MemProvider) SessionDestroy(sid string) error { - pder.lock.Lock() - defer pder.lock.Unlock() - if element, ok := pder.sessions[sid]; ok { - delete(pder.sessions, sid) - pder.list.Remove(element) - return nil - } - return nil -} - -// SessionGC clean expired session stores in memory session -func (pder *MemProvider) SessionGC() { - pder.lock.RLock() - for { - element := pder.list.Back() - if element == nil { - break - } - if (element.Value.(*MemSessionStore).timeAccessed.Unix() + pder.maxlifetime) < time.Now().Unix() { - pder.lock.RUnlock() - pder.lock.Lock() - pder.list.Remove(element) - delete(pder.sessions, element.Value.(*MemSessionStore).sid) - pder.lock.Unlock() - pder.lock.RLock() - } else { - break - } - } - pder.lock.RUnlock() -} - -// SessionAll get count number of memory session -func (pder *MemProvider) SessionAll() int { - return pder.list.Len() -} - -// SessionUpdate expand time of session store by id in memory session -func (pder *MemProvider) SessionUpdate(sid string) error { - pder.lock.Lock() - defer pder.lock.Unlock() - if element, ok := pder.sessions[sid]; ok { - element.Value.(*MemSessionStore).timeAccessed = time.Now() - pder.list.MoveToFront(element) - return nil - } - return nil -} - -func init() { - Register("memory", mempder) -} diff --git a/vendor/github.com/astaxie/beego/session/sess_utils.go b/vendor/github.com/astaxie/beego/session/sess_utils.go deleted file mode 100644 index 20915bb6..00000000 --- a/vendor/github.com/astaxie/beego/session/sess_utils.go +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package session - -import ( - "bytes" - "crypto/cipher" - "crypto/hmac" - "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "encoding/base64" - "encoding/gob" - "errors" - "fmt" - "io" - "strconv" - "time" - - "github.com/astaxie/beego/utils" -) - -func init() { - gob.Register([]interface{}{}) - gob.Register(map[int]interface{}{}) - gob.Register(map[string]interface{}{}) - gob.Register(map[interface{}]interface{}{}) - gob.Register(map[string]string{}) - gob.Register(map[int]string{}) - gob.Register(map[int]int{}) - gob.Register(map[int]int64{}) -} - -// EncodeGob encode the obj to gob -func EncodeGob(obj map[interface{}]interface{}) ([]byte, error) { - for _, v := range obj { - gob.Register(v) - } - buf := bytes.NewBuffer(nil) - enc := gob.NewEncoder(buf) - err := enc.Encode(obj) - if err != nil { - return []byte(""), err - } - return buf.Bytes(), nil -} - -// DecodeGob decode data to map -func DecodeGob(encoded []byte) (map[interface{}]interface{}, error) { - buf := bytes.NewBuffer(encoded) - dec := gob.NewDecoder(buf) - var out map[interface{}]interface{} - err := dec.Decode(&out) - if err != nil { - return nil, err - } - return out, nil -} - -// generateRandomKey creates a random key with the given strength. -func generateRandomKey(strength int) []byte { - k := make([]byte, strength) - if n, err := io.ReadFull(rand.Reader, k); n != strength || err != nil { - return utils.RandomCreateBytes(strength) - } - return k -} - -// Encryption ----------------------------------------------------------------- - -// encrypt encrypts a value using the given block in counter mode. -// -// A random initialization vector (http://goo.gl/zF67k) with the length of the -// block size is prepended to the resulting ciphertext. -func encrypt(block cipher.Block, value []byte) ([]byte, error) { - iv := generateRandomKey(block.BlockSize()) - if iv == nil { - return nil, errors.New("encrypt: failed to generate random iv") - } - // Encrypt it. - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(value, value) - // Return iv + ciphertext. - return append(iv, value...), nil -} - -// decrypt decrypts a value using the given block in counter mode. -// -// The value to be decrypted must be prepended by a initialization vector -// (http://goo.gl/zF67k) with the length of the block size. -func decrypt(block cipher.Block, value []byte) ([]byte, error) { - size := block.BlockSize() - if len(value) > size { - // Extract iv. - iv := value[:size] - // Extract ciphertext. - value = value[size:] - // Decrypt it. - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(value, value) - return value, nil - } - return nil, errors.New("decrypt: the value could not be decrypted") -} - -func encodeCookie(block cipher.Block, hashKey, name string, value map[interface{}]interface{}) (string, error) { - var err error - var b []byte - // 1. EncodeGob. - if b, err = EncodeGob(value); err != nil { - return "", err - } - // 2. Encrypt (optional). - if b, err = encrypt(block, b); err != nil { - return "", err - } - b = encode(b) - // 3. Create MAC for "name|date|value". Extra pipe to be used later. - b = []byte(fmt.Sprintf("%s|%d|%s|", name, time.Now().UTC().Unix(), b)) - h := hmac.New(sha256.New, []byte(hashKey)) - h.Write(b) - sig := h.Sum(nil) - // Append mac, remove name. - b = append(b, sig...)[len(name)+1:] - // 4. Encode to base64. - b = encode(b) - // Done. - return string(b), nil -} - -func decodeCookie(block cipher.Block, hashKey, name, value string, gcmaxlifetime int64) (map[interface{}]interface{}, error) { - // 1. Decode from base64. - b, err := decode([]byte(value)) - if err != nil { - return nil, err - } - // 2. Verify MAC. Value is "date|value|mac". - parts := bytes.SplitN(b, []byte("|"), 3) - if len(parts) != 3 { - return nil, errors.New("Decode: invalid value format") - } - - b = append([]byte(name+"|"), b[:len(b)-len(parts[2])]...) - h := hmac.New(sha256.New, []byte(hashKey)) - h.Write(b) - sig := h.Sum(nil) - if len(sig) != len(parts[2]) || subtle.ConstantTimeCompare(sig, parts[2]) != 1 { - return nil, errors.New("Decode: the value is not valid") - } - // 3. Verify date ranges. - var t1 int64 - if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil { - return nil, errors.New("Decode: invalid timestamp") - } - t2 := time.Now().UTC().Unix() - if t1 > t2 { - return nil, errors.New("Decode: timestamp is too new") - } - if t1 < t2-gcmaxlifetime { - return nil, errors.New("Decode: expired timestamp") - } - // 4. Decrypt (optional). - b, err = decode(parts[1]) - if err != nil { - return nil, err - } - if b, err = decrypt(block, b); err != nil { - return nil, err - } - // 5. DecodeGob. - dst, err := DecodeGob(b) - if err != nil { - return nil, err - } - return dst, nil -} - -// Encoding ------------------------------------------------------------------- - -// encode encodes a value using base64. -func encode(value []byte) []byte { - encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value))) - base64.URLEncoding.Encode(encoded, value) - return encoded -} - -// decode decodes a cookie using base64. -func decode(value []byte) ([]byte, error) { - decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value))) - b, err := base64.URLEncoding.Decode(decoded, value) - if err != nil { - return nil, err - } - return decoded[:b], nil -} diff --git a/vendor/github.com/astaxie/beego/session/session.go b/vendor/github.com/astaxie/beego/session/session.go deleted file mode 100644 index 4532a959..00000000 --- a/vendor/github.com/astaxie/beego/session/session.go +++ /dev/null @@ -1,382 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package session provider -// -// Usage: -// import( -// "github.com/astaxie/beego/session" -// ) -// -// func init() { -// globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) -// go globalSessions.GC() -// } -// -// more docs: http://beego.me/docs/module/session.md -package session - -import ( - "crypto/rand" - "encoding/hex" - "errors" - "fmt" - "io" - "log" - "net/http" - "net/textproto" - "net/url" - "os" - "time" -) - -// Store contains all data for one session process with specific id. -type Store interface { - Set(key, value interface{}) error //set session value - Get(key interface{}) interface{} //get session value - Delete(key interface{}) error //delete session value - SessionID() string //back current sessionID - SessionRelease(w http.ResponseWriter) // release the resource & save data to provider & return the data - Flush() error //delete all data -} - -// Provider contains global session methods and saved SessionStores. -// it can operate a SessionStore by its id. -type Provider interface { - SessionInit(gclifetime int64, config string) error - SessionRead(sid string) (Store, error) - SessionExist(sid string) bool - SessionRegenerate(oldsid, sid string) (Store, error) - SessionDestroy(sid string) error - SessionAll() int //get all active session - SessionGC() -} - -var provides = make(map[string]Provider) - -// SLogger a helpful variable to log information about session -var SLogger = NewSessionLog(os.Stderr) - -// Register makes a session provide available by the provided name. -// If Register is called twice with the same name or if driver is nil, -// it panics. -func Register(name string, provide Provider) { - if provide == nil { - panic("session: Register provide is nil") - } - if _, dup := provides[name]; dup { - panic("session: Register called twice for provider " + name) - } - provides[name] = provide -} - -//GetProvider -func GetProvider(name string) (Provider, error) { - provider, ok := provides[name] - if !ok { - return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", name) - } - return provider, nil -} - -// ManagerConfig define the session config -type ManagerConfig struct { - CookieName string `json:"cookieName"` - EnableSetCookie bool `json:"enableSetCookie,omitempty"` - Gclifetime int64 `json:"gclifetime"` - Maxlifetime int64 `json:"maxLifetime"` - DisableHTTPOnly bool `json:"disableHTTPOnly"` - Secure bool `json:"secure"` - CookieLifeTime int `json:"cookieLifeTime"` - ProviderConfig string `json:"providerConfig"` - Domain string `json:"domain"` - SessionIDLength int64 `json:"sessionIDLength"` - EnableSidInHTTPHeader bool `json:"EnableSidInHTTPHeader"` - SessionNameInHTTPHeader string `json:"SessionNameInHTTPHeader"` - EnableSidInURLQuery bool `json:"EnableSidInURLQuery"` - SessionIDPrefix string `json:"sessionIDPrefix"` - CookieSameSite http.SameSite `json:"cookieSameSite"` -} - -// Manager contains Provider and its configuration. -type Manager struct { - provider Provider - config *ManagerConfig -} - -// NewManager Create new Manager with provider name and json config string. -// provider name: -// 1. cookie -// 2. file -// 3. memory -// 4. redis -// 5. mysql -// json config: -// 1. is https default false -// 2. hashfunc default sha1 -// 3. hashkey default beegosessionkey -// 4. maxage default is none -func NewManager(provideName string, cf *ManagerConfig) (*Manager, error) { - provider, ok := provides[provideName] - if !ok { - return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName) - } - - if cf.Maxlifetime == 0 { - cf.Maxlifetime = cf.Gclifetime - } - - if cf.EnableSidInHTTPHeader { - if cf.SessionNameInHTTPHeader == "" { - panic(errors.New("SessionNameInHTTPHeader is empty")) - } - - strMimeHeader := textproto.CanonicalMIMEHeaderKey(cf.SessionNameInHTTPHeader) - if cf.SessionNameInHTTPHeader != strMimeHeader { - strErrMsg := "SessionNameInHTTPHeader (" + cf.SessionNameInHTTPHeader + ") has the wrong format, it should be like this : " + strMimeHeader - panic(errors.New(strErrMsg)) - } - } - - err := provider.SessionInit(cf.Maxlifetime, cf.ProviderConfig) - if err != nil { - return nil, err - } - - if cf.SessionIDLength == 0 { - cf.SessionIDLength = 16 - } - - return &Manager{ - provider, - cf, - }, nil -} - -// GetProvider return current manager's provider -func (manager *Manager) GetProvider() Provider { - return manager.provider -} - -// getSid retrieves session identifier from HTTP Request. -// First try to retrieve id by reading from cookie, session cookie name is configurable, -// if not exist, then retrieve id from querying parameters. -// -// error is not nil when there is anything wrong. -// sid is empty when need to generate a new session id -// otherwise return an valid session id. -func (manager *Manager) getSid(r *http.Request) (string, error) { - cookie, errs := r.Cookie(manager.config.CookieName) - if errs != nil || cookie.Value == "" { - var sid string - if manager.config.EnableSidInURLQuery { - errs := r.ParseForm() - if errs != nil { - return "", errs - } - - sid = r.FormValue(manager.config.CookieName) - } - - // if not found in Cookie / param, then read it from request headers - if manager.config.EnableSidInHTTPHeader && sid == "" { - sids, isFound := r.Header[manager.config.SessionNameInHTTPHeader] - if isFound && len(sids) != 0 { - return sids[0], nil - } - } - - return sid, nil - } - - // HTTP Request contains cookie for sessionid info. - return url.QueryUnescape(cookie.Value) -} - -// SessionStart generate or read the session id from http request. -// if session id exists, return SessionStore with this id. -func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Store, err error) { - sid, errs := manager.getSid(r) - if errs != nil { - return nil, errs - } - - if sid != "" && manager.provider.SessionExist(sid) { - return manager.provider.SessionRead(sid) - } - - // Generate a new session - sid, errs = manager.sessionID() - if errs != nil { - return nil, errs - } - - session, err = manager.provider.SessionRead(sid) - if err != nil { - return nil, err - } - cookie := &http.Cookie{ - Name: manager.config.CookieName, - Value: url.QueryEscape(sid), - Path: "/", - HttpOnly: !manager.config.DisableHTTPOnly, - Secure: manager.isSecure(r), - Domain: manager.config.Domain, - SameSite: manager.config.CookieSameSite, - } - if manager.config.CookieLifeTime > 0 { - cookie.MaxAge = manager.config.CookieLifeTime - cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second) - } - if manager.config.EnableSetCookie { - http.SetCookie(w, cookie) - } - r.AddCookie(cookie) - - if manager.config.EnableSidInHTTPHeader { - r.Header.Set(manager.config.SessionNameInHTTPHeader, sid) - w.Header().Set(manager.config.SessionNameInHTTPHeader, sid) - } - - return -} - -// SessionDestroy Destroy session by its id in http request cookie. -func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request) { - if manager.config.EnableSidInHTTPHeader { - r.Header.Del(manager.config.SessionNameInHTTPHeader) - w.Header().Del(manager.config.SessionNameInHTTPHeader) - } - - cookie, err := r.Cookie(manager.config.CookieName) - if err != nil || cookie.Value == "" { - return - } - - sid, _ := url.QueryUnescape(cookie.Value) - manager.provider.SessionDestroy(sid) - if manager.config.EnableSetCookie { - expiration := time.Now() - cookie = &http.Cookie{Name: manager.config.CookieName, - Path: "/", - HttpOnly: !manager.config.DisableHTTPOnly, - Expires: expiration, - MaxAge: -1, - Domain: manager.config.Domain, - SameSite: manager.config.CookieSameSite, - } - - http.SetCookie(w, cookie) - } -} - -// GetSessionStore Get SessionStore by its id. -func (manager *Manager) GetSessionStore(sid string) (sessions Store, err error) { - sessions, err = manager.provider.SessionRead(sid) - return -} - -// GC Start session gc process. -// it can do gc in times after gc lifetime. -func (manager *Manager) GC() { - manager.provider.SessionGC() - time.AfterFunc(time.Duration(manager.config.Gclifetime)*time.Second, func() { manager.GC() }) -} - -// SessionRegenerateID Regenerate a session id for this SessionStore who's id is saving in http request. -func (manager *Manager) SessionRegenerateID(w http.ResponseWriter, r *http.Request) (session Store) { - sid, err := manager.sessionID() - if err != nil { - return - } - cookie, err := r.Cookie(manager.config.CookieName) - if err != nil || cookie.Value == "" { - //delete old cookie - session, _ = manager.provider.SessionRead(sid) - cookie = &http.Cookie{Name: manager.config.CookieName, - Value: url.QueryEscape(sid), - Path: "/", - HttpOnly: !manager.config.DisableHTTPOnly, - Secure: manager.isSecure(r), - Domain: manager.config.Domain, - SameSite: manager.config.CookieSameSite, - } - } else { - oldsid, _ := url.QueryUnescape(cookie.Value) - session, _ = manager.provider.SessionRegenerate(oldsid, sid) - cookie.Value = url.QueryEscape(sid) - cookie.HttpOnly = true - cookie.Path = "/" - } - if manager.config.CookieLifeTime > 0 { - cookie.MaxAge = manager.config.CookieLifeTime - cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second) - } - if manager.config.EnableSetCookie { - http.SetCookie(w, cookie) - } - r.AddCookie(cookie) - - if manager.config.EnableSidInHTTPHeader { - r.Header.Set(manager.config.SessionNameInHTTPHeader, sid) - w.Header().Set(manager.config.SessionNameInHTTPHeader, sid) - } - - return -} - -// GetActiveSession Get all active sessions count number. -func (manager *Manager) GetActiveSession() int { - return manager.provider.SessionAll() -} - -// SetSecure Set cookie with https. -func (manager *Manager) SetSecure(secure bool) { - manager.config.Secure = secure -} - -func (manager *Manager) sessionID() (string, error) { - b := make([]byte, manager.config.SessionIDLength) - n, err := rand.Read(b) - if n != len(b) || err != nil { - return "", fmt.Errorf("Could not successfully read from the system CSPRNG") - } - return manager.config.SessionIDPrefix + hex.EncodeToString(b), nil -} - -// Set cookie with https. -func (manager *Manager) isSecure(req *http.Request) bool { - if !manager.config.Secure { - return false - } - if req.URL.Scheme != "" { - return req.URL.Scheme == "https" - } - if req.TLS == nil { - return false - } - return true -} - -// Log implement the log.Logger -type Log struct { - *log.Logger -} - -// NewSessionLog set io.Writer to create a Logger for session. -func NewSessionLog(out io.Writer) *Log { - sl := new(Log) - sl.Logger = log.New(out, "[SESSION]", 1e9) - return sl -} diff --git a/vendor/github.com/astaxie/beego/staticfile.go b/vendor/github.com/astaxie/beego/staticfile.go deleted file mode 100644 index e26776c5..00000000 --- a/vendor/github.com/astaxie/beego/staticfile.go +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "bytes" - "errors" - "net/http" - "os" - "path" - "path/filepath" - "strconv" - "strings" - "sync" - "time" - - "github.com/astaxie/beego/context" - "github.com/astaxie/beego/logs" - "github.com/hashicorp/golang-lru" -) - -var errNotStaticRequest = errors.New("request not a static file request") - -func serverStaticRouter(ctx *context.Context) { - if ctx.Input.Method() != "GET" && ctx.Input.Method() != "HEAD" { - return - } - - forbidden, filePath, fileInfo, err := lookupFile(ctx) - if err == errNotStaticRequest { - return - } - - if forbidden { - exception("403", ctx) - return - } - - if filePath == "" || fileInfo == nil { - if BConfig.RunMode == DEV { - logs.Warn("Can't find/open the file:", filePath, err) - } - http.NotFound(ctx.ResponseWriter, ctx.Request) - return - } - if fileInfo.IsDir() { - requestURL := ctx.Input.URL() - if requestURL[len(requestURL)-1] != '/' { - redirectURL := requestURL + "/" - if ctx.Request.URL.RawQuery != "" { - redirectURL = redirectURL + "?" + ctx.Request.URL.RawQuery - } - ctx.Redirect(302, redirectURL) - } else { - //serveFile will list dir - http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath) - } - return - } else if fileInfo.Size() > int64(BConfig.WebConfig.StaticCacheFileSize) { - //over size file serve with http module - http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath) - return - } - - var enableCompress = BConfig.EnableGzip && isStaticCompress(filePath) - var acceptEncoding string - if enableCompress { - acceptEncoding = context.ParseEncoding(ctx.Request) - } - b, n, sch, reader, err := openFile(filePath, fileInfo, acceptEncoding) - if err != nil { - if BConfig.RunMode == DEV { - logs.Warn("Can't compress the file:", filePath, err) - } - http.NotFound(ctx.ResponseWriter, ctx.Request) - return - } - - if b { - ctx.Output.Header("Content-Encoding", n) - } else { - ctx.Output.Header("Content-Length", strconv.FormatInt(sch.size, 10)) - } - - http.ServeContent(ctx.ResponseWriter, ctx.Request, filePath, sch.modTime, reader) -} - -type serveContentHolder struct { - data []byte - modTime time.Time - size int64 - originSize int64 //original file size:to judge file changed - encoding string -} - -type serveContentReader struct { - *bytes.Reader -} - -var ( - staticFileLruCache *lru.Cache - lruLock sync.RWMutex -) - -func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, *serveContentReader, error) { - if staticFileLruCache == nil { - //avoid lru cache error - if BConfig.WebConfig.StaticCacheFileNum >= 1 { - staticFileLruCache, _ = lru.New(BConfig.WebConfig.StaticCacheFileNum) - } else { - staticFileLruCache, _ = lru.New(1) - } - } - mapKey := acceptEncoding + ":" + filePath - lruLock.RLock() - var mapFile *serveContentHolder - if cacheItem, ok := staticFileLruCache.Get(mapKey); ok { - mapFile = cacheItem.(*serveContentHolder) - } - lruLock.RUnlock() - if isOk(mapFile, fi) { - reader := &serveContentReader{Reader: bytes.NewReader(mapFile.data)} - return mapFile.encoding != "", mapFile.encoding, mapFile, reader, nil - } - lruLock.Lock() - defer lruLock.Unlock() - if cacheItem, ok := staticFileLruCache.Get(mapKey); ok { - mapFile = cacheItem.(*serveContentHolder) - } - if !isOk(mapFile, fi) { - file, err := os.Open(filePath) - if err != nil { - return false, "", nil, nil, err - } - defer file.Close() - var bufferWriter bytes.Buffer - _, n, err := context.WriteFile(acceptEncoding, &bufferWriter, file) - if err != nil { - return false, "", nil, nil, err - } - mapFile = &serveContentHolder{data: bufferWriter.Bytes(), modTime: fi.ModTime(), size: int64(bufferWriter.Len()), originSize: fi.Size(), encoding: n} - if isOk(mapFile, fi) { - staticFileLruCache.Add(mapKey, mapFile) - } - } - - reader := &serveContentReader{Reader: bytes.NewReader(mapFile.data)} - return mapFile.encoding != "", mapFile.encoding, mapFile, reader, nil -} - -func isOk(s *serveContentHolder, fi os.FileInfo) bool { - if s == nil { - return false - } else if s.size > int64(BConfig.WebConfig.StaticCacheFileSize) { - return false - } - return s.modTime == fi.ModTime() && s.originSize == fi.Size() -} - -// isStaticCompress detect static files -func isStaticCompress(filePath string) bool { - for _, statExtension := range BConfig.WebConfig.StaticExtensionsToGzip { - if strings.HasSuffix(strings.ToLower(filePath), strings.ToLower(statExtension)) { - return true - } - } - return false -} - -// searchFile search the file by url path -// if none the static file prefix matches ,return notStaticRequestErr -func searchFile(ctx *context.Context) (string, os.FileInfo, error) { - requestPath := filepath.ToSlash(filepath.Clean(ctx.Request.URL.Path)) - // special processing : favicon.ico/robots.txt can be in any static dir - if requestPath == "/favicon.ico" || requestPath == "/robots.txt" { - file := path.Join(".", requestPath) - if fi, _ := os.Stat(file); fi != nil { - return file, fi, nil - } - for _, staticDir := range BConfig.WebConfig.StaticDir { - filePath := path.Join(staticDir, requestPath) - if fi, _ := os.Stat(filePath); fi != nil { - return filePath, fi, nil - } - } - return "", nil, errNotStaticRequest - } - - for prefix, staticDir := range BConfig.WebConfig.StaticDir { - if !strings.Contains(requestPath, prefix) { - continue - } - if prefix != "/" && len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' { - continue - } - filePath := path.Join(staticDir, requestPath[len(prefix):]) - if fi, err := os.Stat(filePath); fi != nil { - return filePath, fi, err - } - } - return "", nil, errNotStaticRequest -} - -// lookupFile find the file to serve -// if the file is dir ,search the index.html as default file( MUST NOT A DIR also) -// if the index.html not exist or is a dir, give a forbidden response depending on DirectoryIndex -func lookupFile(ctx *context.Context) (bool, string, os.FileInfo, error) { - fp, fi, err := searchFile(ctx) - if fp == "" || fi == nil { - return false, "", nil, err - } - if !fi.IsDir() { - return false, fp, fi, err - } - if requestURL := ctx.Input.URL(); requestURL[len(requestURL)-1] == '/' { - ifp := filepath.Join(fp, "index.html") - if ifi, _ := os.Stat(ifp); ifi != nil && ifi.Mode().IsRegular() { - return false, ifp, ifi, err - } - } - return !BConfig.WebConfig.DirectoryIndex, fp, fi, err -} diff --git a/vendor/github.com/astaxie/beego/template.go b/vendor/github.com/astaxie/beego/template.go deleted file mode 100644 index 59875be7..00000000 --- a/vendor/github.com/astaxie/beego/template.go +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "errors" - "fmt" - "html/template" - "io" - "io/ioutil" - "net/http" - "os" - "path/filepath" - "regexp" - "strings" - "sync" - - "github.com/astaxie/beego/logs" - "github.com/astaxie/beego/utils" -) - -var ( - beegoTplFuncMap = make(template.FuncMap) - beeViewPathTemplateLocked = false - // beeViewPathTemplates caching map and supported template file extensions per view - beeViewPathTemplates = make(map[string]map[string]*template.Template) - templatesLock sync.RWMutex - // beeTemplateExt stores the template extension which will build - beeTemplateExt = []string{"tpl", "html", "gohtml"} - // beeTemplatePreprocessors stores associations of extension -> preprocessor handler - beeTemplateEngines = map[string]templatePreProcessor{} - beeTemplateFS = defaultFSFunc -) - -// ExecuteTemplate applies the template with name to the specified data object, -// writing the output to wr. -// A template will be executed safely in parallel. -func ExecuteTemplate(wr io.Writer, name string, data interface{}) error { - return ExecuteViewPathTemplate(wr, name, BConfig.WebConfig.ViewsPath, data) -} - -// ExecuteViewPathTemplate applies the template with name and from specific viewPath to the specified data object, -// writing the output to wr. -// A template will be executed safely in parallel. -func ExecuteViewPathTemplate(wr io.Writer, name string, viewPath string, data interface{}) error { - if BConfig.RunMode == DEV { - templatesLock.RLock() - defer templatesLock.RUnlock() - } - if beeTemplates, ok := beeViewPathTemplates[viewPath]; ok { - if t, ok := beeTemplates[name]; ok { - var err error - if t.Lookup(name) != nil { - err = t.ExecuteTemplate(wr, name, data) - } else { - err = t.Execute(wr, data) - } - if err != nil { - logs.Trace("template Execute err:", err) - } - return err - } - panic("can't find templatefile in the path:" + viewPath + "/" + name) - } - panic("Unknown view path:" + viewPath) -} - -func init() { - beegoTplFuncMap["dateformat"] = DateFormat - beegoTplFuncMap["date"] = Date - beegoTplFuncMap["compare"] = Compare - beegoTplFuncMap["compare_not"] = CompareNot - beegoTplFuncMap["not_nil"] = NotNil - beegoTplFuncMap["not_null"] = NotNil - beegoTplFuncMap["substr"] = Substr - beegoTplFuncMap["html2str"] = HTML2str - beegoTplFuncMap["str2html"] = Str2html - beegoTplFuncMap["htmlquote"] = Htmlquote - beegoTplFuncMap["htmlunquote"] = Htmlunquote - beegoTplFuncMap["renderform"] = RenderForm - beegoTplFuncMap["assets_js"] = AssetsJs - beegoTplFuncMap["assets_css"] = AssetsCSS - beegoTplFuncMap["config"] = GetConfig - beegoTplFuncMap["map_get"] = MapGet - - // Comparisons - beegoTplFuncMap["eq"] = eq // == - beegoTplFuncMap["ge"] = ge // >= - beegoTplFuncMap["gt"] = gt // > - beegoTplFuncMap["le"] = le // <= - beegoTplFuncMap["lt"] = lt // < - beegoTplFuncMap["ne"] = ne // != - - beegoTplFuncMap["urlfor"] = URLFor // build a URL to match a Controller and it's method -} - -// AddFuncMap let user to register a func in the template. -func AddFuncMap(key string, fn interface{}) error { - beegoTplFuncMap[key] = fn - return nil -} - -type templatePreProcessor func(root, path string, funcs template.FuncMap) (*template.Template, error) - -type templateFile struct { - root string - files map[string][]string -} - -// visit will make the paths into two part,the first is subDir (without tf.root),the second is full path(without tf.root). -// if tf.root="views" and -// paths is "views/errors/404.html",the subDir will be "errors",the file will be "errors/404.html" -// paths is "views/admin/errors/404.html",the subDir will be "admin/errors",the file will be "admin/errors/404.html" -func (tf *templateFile) visit(paths string, f os.FileInfo, err error) error { - if f == nil { - return err - } - if f.IsDir() || (f.Mode()&os.ModeSymlink) > 0 { - return nil - } - if !HasTemplateExt(paths) { - return nil - } - - replace := strings.NewReplacer("\\", "/") - file := strings.TrimLeft(replace.Replace(paths[len(tf.root):]), "/") - subDir := filepath.Dir(file) - - tf.files[subDir] = append(tf.files[subDir], file) - return nil -} - -// HasTemplateExt return this path contains supported template extension of beego or not. -func HasTemplateExt(paths string) bool { - for _, v := range beeTemplateExt { - if strings.HasSuffix(paths, "."+v) { - return true - } - } - return false -} - -// AddTemplateExt add new extension for template. -func AddTemplateExt(ext string) { - for _, v := range beeTemplateExt { - if v == ext { - return - } - } - beeTemplateExt = append(beeTemplateExt, ext) -} - -// AddViewPath adds a new path to the supported view paths. -//Can later be used by setting a controller ViewPath to this folder -//will panic if called after beego.Run() -func AddViewPath(viewPath string) error { - if beeViewPathTemplateLocked { - if _, exist := beeViewPathTemplates[viewPath]; exist { - return nil //Ignore if viewpath already exists - } - panic("Can not add new view paths after beego.Run()") - } - beeViewPathTemplates[viewPath] = make(map[string]*template.Template) - return BuildTemplate(viewPath) -} - -func lockViewPaths() { - beeViewPathTemplateLocked = true -} - -// BuildTemplate will build all template files in a directory. -// it makes beego can render any template file in view directory. -func BuildTemplate(dir string, files ...string) error { - var err error - fs := beeTemplateFS() - f, err := fs.Open(dir) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return errors.New("dir open err") - } - defer f.Close() - - beeTemplates, ok := beeViewPathTemplates[dir] - if !ok { - panic("Unknown view path: " + dir) - } - self := &templateFile{ - root: dir, - files: make(map[string][]string), - } - err = Walk(fs, dir, func(path string, f os.FileInfo, err error) error { - return self.visit(path, f, err) - }) - if err != nil { - fmt.Printf("Walk() returned %v\n", err) - return err - } - buildAllFiles := len(files) == 0 - for _, v := range self.files { - for _, file := range v { - if buildAllFiles || utils.InSlice(file, files) { - templatesLock.Lock() - ext := filepath.Ext(file) - var t *template.Template - if len(ext) == 0 { - t, err = getTemplate(self.root, fs, file, v...) - } else if fn, ok := beeTemplateEngines[ext[1:]]; ok { - t, err = fn(self.root, file, beegoTplFuncMap) - } else { - t, err = getTemplate(self.root, fs, file, v...) - } - if err != nil { - logs.Error("parse template err:", file, err) - templatesLock.Unlock() - return err - } - beeTemplates[file] = t - templatesLock.Unlock() - } - } - } - return nil -} - -func getTplDeep(root string, fs http.FileSystem, file string, parent string, t *template.Template) (*template.Template, [][]string, error) { - var fileAbsPath string - var rParent string - var err error - if strings.HasPrefix(file, "../") { - rParent = filepath.Join(filepath.Dir(parent), file) - fileAbsPath = filepath.Join(root, filepath.Dir(parent), file) - } else { - rParent = file - fileAbsPath = filepath.Join(root, file) - } - f, err := fs.Open(fileAbsPath) - if err != nil { - panic("can't find template file:" + file) - } - defer f.Close() - data, err := ioutil.ReadAll(f) - if err != nil { - return nil, [][]string{}, err - } - t, err = t.New(file).Parse(string(data)) - if err != nil { - return nil, [][]string{}, err - } - reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*template[ ]+\"([^\"]+)\"") - allSub := reg.FindAllStringSubmatch(string(data), -1) - for _, m := range allSub { - if len(m) == 2 { - tl := t.Lookup(m[1]) - if tl != nil { - continue - } - if !HasTemplateExt(m[1]) { - continue - } - _, _, err = getTplDeep(root, fs, m[1], rParent, t) - if err != nil { - return nil, [][]string{}, err - } - } - } - return t, allSub, nil -} - -func getTemplate(root string, fs http.FileSystem, file string, others ...string) (t *template.Template, err error) { - t = template.New(file).Delims(BConfig.WebConfig.TemplateLeft, BConfig.WebConfig.TemplateRight).Funcs(beegoTplFuncMap) - var subMods [][]string - t, subMods, err = getTplDeep(root, fs, file, "", t) - if err != nil { - return nil, err - } - t, err = _getTemplate(t, root, fs, subMods, others...) - - if err != nil { - return nil, err - } - return -} - -func _getTemplate(t0 *template.Template, root string, fs http.FileSystem, subMods [][]string, others ...string) (t *template.Template, err error) { - t = t0 - for _, m := range subMods { - if len(m) == 2 { - tpl := t.Lookup(m[1]) - if tpl != nil { - continue - } - //first check filename - for _, otherFile := range others { - if otherFile == m[1] { - var subMods1 [][]string - t, subMods1, err = getTplDeep(root, fs, otherFile, "", t) - if err != nil { - logs.Trace("template parse file err:", err) - } else if len(subMods1) > 0 { - t, err = _getTemplate(t, root, fs, subMods1, others...) - } - break - } - } - //second check define - for _, otherFile := range others { - var data []byte - fileAbsPath := filepath.Join(root, otherFile) - f, err := fs.Open(fileAbsPath) - if err != nil { - f.Close() - logs.Trace("template file parse error, not success open file:", err) - continue - } - data, err = ioutil.ReadAll(f) - f.Close() - if err != nil { - logs.Trace("template file parse error, not success read file:", err) - continue - } - reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*define[ ]+\"([^\"]+)\"") - allSub := reg.FindAllStringSubmatch(string(data), -1) - for _, sub := range allSub { - if len(sub) == 2 && sub[1] == m[1] { - var subMods1 [][]string - t, subMods1, err = getTplDeep(root, fs, otherFile, "", t) - if err != nil { - logs.Trace("template parse file err:", err) - } else if len(subMods1) > 0 { - t, err = _getTemplate(t, root, fs, subMods1, others...) - if err != nil { - logs.Trace("template parse file err:", err) - } - } - break - } - } - } - } - - } - return -} - -type templateFSFunc func() http.FileSystem - -func defaultFSFunc() http.FileSystem { - return FileSystem{} -} - -// SetTemplateFSFunc set default filesystem function -func SetTemplateFSFunc(fnt templateFSFunc) { - beeTemplateFS = fnt -} - -// SetViewsPath sets view directory path in beego application. -func SetViewsPath(path string) *App { - BConfig.WebConfig.ViewsPath = path - return BeeApp -} - -// SetStaticPath sets static directory path and proper url pattern in beego application. -// if beego.SetStaticPath("static","public"), visit /static/* to load static file in folder "public". -func SetStaticPath(url string, path string) *App { - if !strings.HasPrefix(url, "/") { - url = "/" + url - } - if url != "/" { - url = strings.TrimRight(url, "/") - } - BConfig.WebConfig.StaticDir[url] = path - return BeeApp -} - -// DelStaticPath removes the static folder setting in this url pattern in beego application. -func DelStaticPath(url string) *App { - if !strings.HasPrefix(url, "/") { - url = "/" + url - } - if url != "/" { - url = strings.TrimRight(url, "/") - } - delete(BConfig.WebConfig.StaticDir, url) - return BeeApp -} - -// AddTemplateEngine add a new templatePreProcessor which support extension -func AddTemplateEngine(extension string, fn templatePreProcessor) *App { - AddTemplateExt(extension) - beeTemplateEngines[extension] = fn - return BeeApp -} diff --git a/vendor/github.com/astaxie/beego/templatefunc.go b/vendor/github.com/astaxie/beego/templatefunc.go deleted file mode 100644 index 6f02b8d6..00000000 --- a/vendor/github.com/astaxie/beego/templatefunc.go +++ /dev/null @@ -1,780 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "errors" - "fmt" - "html" - "html/template" - "net/url" - "reflect" - "regexp" - "strconv" - "strings" - "time" -) - -const ( - formatTime = "15:04:05" - formatDate = "2006-01-02" - formatDateTime = "2006-01-02 15:04:05" - formatDateTimeT = "2006-01-02T15:04:05" -) - -// Substr returns the substr from start to length. -func Substr(s string, start, length int) string { - bt := []rune(s) - if start < 0 { - start = 0 - } - if start > len(bt) { - start = start % len(bt) - } - var end int - if (start + length) > (len(bt) - 1) { - end = len(bt) - } else { - end = start + length - } - return string(bt[start:end]) -} - -// HTML2str returns escaping text convert from html. -func HTML2str(html string) string { - - re := regexp.MustCompile(`\<[\S\s]+?\>`) - html = re.ReplaceAllStringFunc(html, strings.ToLower) - - //remove STYLE - re = regexp.MustCompile(`\`) - html = re.ReplaceAllString(html, "") - - //remove SCRIPT - re = regexp.MustCompile(`\`) - html = re.ReplaceAllString(html, "") - - re = regexp.MustCompile(`\<[\S\s]+?\>`) - html = re.ReplaceAllString(html, "\n") - - re = regexp.MustCompile(`\s{2,}`) - html = re.ReplaceAllString(html, "\n") - - return strings.TrimSpace(html) -} - -// DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat" -func DateFormat(t time.Time, layout string) (datestring string) { - datestring = t.Format(layout) - return -} - -// DateFormat pattern rules. -var datePatterns = []string{ - // year - "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003 - "y", "06", //A two digit representation of a year Examples: 99 or 03 - - // month - "m", "01", // Numeric representation of a month, with leading zeros 01 through 12 - "n", "1", // Numeric representation of a month, without leading zeros 1 through 12 - "M", "Jan", // A short textual representation of a month, three letters Jan through Dec - "F", "January", // A full textual representation of a month, such as January or March January through December - - // day - "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31 - "j", "2", // Day of the month without leading zeros 1 to 31 - - // week - "D", "Mon", // A textual representation of a day, three letters Mon through Sun - "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday - - // time - "g", "3", // 12-hour format of an hour without leading zeros 1 through 12 - "G", "15", // 24-hour format of an hour without leading zeros 0 through 23 - "h", "03", // 12-hour format of an hour with leading zeros 01 through 12 - "H", "15", // 24-hour format of an hour with leading zeros 00 through 23 - - "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm - "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM - - "i", "04", // Minutes with leading zeros 00 to 59 - "s", "05", // Seconds, with leading zeros 00 through 59 - - // time zone - "T", "MST", - "P", "-07:00", - "O", "-0700", - - // RFC 2822 - "r", time.RFC1123Z, -} - -// DateParse Parse Date use PHP time format. -func DateParse(dateString, format string) (time.Time, error) { - replacer := strings.NewReplacer(datePatterns...) - format = replacer.Replace(format) - return time.ParseInLocation(format, dateString, time.Local) -} - -// Date takes a PHP like date func to Go's time format. -func Date(t time.Time, format string) string { - replacer := strings.NewReplacer(datePatterns...) - format = replacer.Replace(format) - return t.Format(format) -} - -// Compare is a quick and dirty comparison function. It will convert whatever you give it to strings and see if the two values are equal. -// Whitespace is trimmed. Used by the template parser as "eq". -func Compare(a, b interface{}) (equal bool) { - equal = false - if strings.TrimSpace(fmt.Sprintf("%v", a)) == strings.TrimSpace(fmt.Sprintf("%v", b)) { - equal = true - } - return -} - -// CompareNot !Compare -func CompareNot(a, b interface{}) (equal bool) { - return !Compare(a, b) -} - -// NotNil the same as CompareNot -func NotNil(a interface{}) (isNil bool) { - return CompareNot(a, nil) -} - -// GetConfig get the Appconfig -func GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error) { - switch returnType { - case "String": - value = AppConfig.String(key) - case "Bool": - value, err = AppConfig.Bool(key) - case "Int": - value, err = AppConfig.Int(key) - case "Int64": - value, err = AppConfig.Int64(key) - case "Float": - value, err = AppConfig.Float(key) - case "DIY": - value, err = AppConfig.DIY(key) - default: - err = errors.New("config keys must be of type String, Bool, Int, Int64, Float, or DIY") - } - - if err != nil { - if reflect.TypeOf(returnType) != reflect.TypeOf(defaultVal) { - err = errors.New("defaultVal type does not match returnType") - } else { - value, err = defaultVal, nil - } - } else if reflect.TypeOf(value).Kind() == reflect.String { - if value == "" { - if reflect.TypeOf(defaultVal).Kind() != reflect.String { - err = errors.New("defaultVal type must be a String if the returnType is a String") - } else { - value = defaultVal.(string) - } - } - } - - return -} - -// Str2html Convert string to template.HTML type. -func Str2html(raw string) template.HTML { - return template.HTML(raw) -} - -// Htmlquote returns quoted html string. -func Htmlquote(text string) string { - //HTML编码为实体符号 - /* - Encodes `text` for raw use in HTML. - >>> htmlquote("<'&\\">") - '<'&">' - */ - - text = html.EscapeString(text) - text = strings.NewReplacer( - `“`, "“", - `”`, "”", - ` `, " ", - ).Replace(text) - - return strings.TrimSpace(text) -} - -// Htmlunquote returns unquoted html string. -func Htmlunquote(text string) string { - //实体符号解释为HTML - /* - Decodes `text` that's HTML quoted. - >>> htmlunquote('<'&">') - '<\\'&">' - */ - - text = html.UnescapeString(text) - - return strings.TrimSpace(text) -} - -// URLFor returns url string with another registered controller handler with params. -// usage: -// -// URLFor(".index") -// print URLFor("index") -// router /login -// print URLFor("login") -// print URLFor("login", "next","/"") -// router /profile/:username -// print UrlFor("profile", ":username","John Doe") -// result: -// / -// /login -// /login?next=/ -// /user/John%20Doe -// -// more detail http://beego.me/docs/mvc/controller/urlbuilding.md -func URLFor(endpoint string, values ...interface{}) string { - return BeeApp.Handlers.URLFor(endpoint, values...) -} - -// AssetsJs returns script tag with src string. -func AssetsJs(text string) template.HTML { - - text = "" - - return template.HTML(text) -} - -// AssetsCSS returns stylesheet link tag with src string. -func AssetsCSS(text string) template.HTML { - - text = "" - - return template.HTML(text) -} - -// ParseForm will parse form values to struct via tag. -// Support for anonymous struct. -func parseFormToStruct(form url.Values, objT reflect.Type, objV reflect.Value) error { - for i := 0; i < objT.NumField(); i++ { - fieldV := objV.Field(i) - if !fieldV.CanSet() { - continue - } - - fieldT := objT.Field(i) - if fieldT.Anonymous && fieldT.Type.Kind() == reflect.Struct { - err := parseFormToStruct(form, fieldT.Type, fieldV) - if err != nil { - return err - } - continue - } - - tags := strings.Split(fieldT.Tag.Get("form"), ",") - var tag string - if len(tags) == 0 || len(tags[0]) == 0 { - tag = fieldT.Name - } else if tags[0] == "-" { - continue - } else { - tag = tags[0] - } - - formValues := form[tag] - var value string - if len(formValues) == 0 { - defaultValue := fieldT.Tag.Get("default") - if defaultValue != "" { - value = defaultValue - } else { - continue - } - } - if len(formValues) == 1 { - value = formValues[0] - if value == "" { - continue - } - } - - switch fieldT.Type.Kind() { - case reflect.Bool: - if strings.ToLower(value) == "on" || strings.ToLower(value) == "1" || strings.ToLower(value) == "yes" { - fieldV.SetBool(true) - continue - } - if strings.ToLower(value) == "off" || strings.ToLower(value) == "0" || strings.ToLower(value) == "no" { - fieldV.SetBool(false) - continue - } - b, err := strconv.ParseBool(value) - if err != nil { - return err - } - fieldV.SetBool(b) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - x, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - fieldV.SetInt(x) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - x, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - fieldV.SetUint(x) - case reflect.Float32, reflect.Float64: - x, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - fieldV.SetFloat(x) - case reflect.Interface: - fieldV.Set(reflect.ValueOf(value)) - case reflect.String: - fieldV.SetString(value) - case reflect.Struct: - switch fieldT.Type.String() { - case "time.Time": - var ( - t time.Time - err error - ) - if len(value) >= 25 { - value = value[:25] - t, err = time.ParseInLocation(time.RFC3339, value, time.Local) - } else if strings.HasSuffix(strings.ToUpper(value), "Z") { - t, err = time.ParseInLocation(time.RFC3339, value, time.Local) - } else if len(value) >= 19 { - if strings.Contains(value, "T") { - value = value[:19] - t, err = time.ParseInLocation(formatDateTimeT, value, time.Local) - } else { - value = value[:19] - t, err = time.ParseInLocation(formatDateTime, value, time.Local) - } - } else if len(value) >= 10 { - if len(value) > 10 { - value = value[:10] - } - t, err = time.ParseInLocation(formatDate, value, time.Local) - } else if len(value) >= 8 { - if len(value) > 8 { - value = value[:8] - } - t, err = time.ParseInLocation(formatTime, value, time.Local) - } - if err != nil { - return err - } - fieldV.Set(reflect.ValueOf(t)) - } - case reflect.Slice: - if fieldT.Type == sliceOfInts { - formVals := form[tag] - fieldV.Set(reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(int(1))), len(formVals), len(formVals))) - for i := 0; i < len(formVals); i++ { - val, err := strconv.Atoi(formVals[i]) - if err != nil { - return err - } - fieldV.Index(i).SetInt(int64(val)) - } - } else if fieldT.Type == sliceOfStrings { - formVals := form[tag] - fieldV.Set(reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf("")), len(formVals), len(formVals))) - for i := 0; i < len(formVals); i++ { - fieldV.Index(i).SetString(formVals[i]) - } - } - } - } - return nil -} - -// ParseForm will parse form values to struct via tag. -func ParseForm(form url.Values, obj interface{}) error { - objT := reflect.TypeOf(obj) - objV := reflect.ValueOf(obj) - if !isStructPtr(objT) { - return fmt.Errorf("%v must be a struct pointer", obj) - } - objT = objT.Elem() - objV = objV.Elem() - - return parseFormToStruct(form, objT, objV) -} - -var sliceOfInts = reflect.TypeOf([]int(nil)) -var sliceOfStrings = reflect.TypeOf([]string(nil)) - -var unKind = map[reflect.Kind]bool{ - reflect.Uintptr: true, - reflect.Complex64: true, - reflect.Complex128: true, - reflect.Array: true, - reflect.Chan: true, - reflect.Func: true, - reflect.Map: true, - reflect.Ptr: true, - reflect.Slice: true, - reflect.Struct: true, - reflect.UnsafePointer: true, -} - -// RenderForm will render object to form html. -// obj must be a struct pointer. -func RenderForm(obj interface{}) template.HTML { - objT := reflect.TypeOf(obj) - objV := reflect.ValueOf(obj) - if !isStructPtr(objT) { - return template.HTML("") - } - objT = objT.Elem() - objV = objV.Elem() - - var raw []string - for i := 0; i < objT.NumField(); i++ { - fieldV := objV.Field(i) - if !fieldV.CanSet() || unKind[fieldV.Kind()] { - continue - } - - fieldT := objT.Field(i) - - label, name, fType, id, class, ignored, required := parseFormTag(fieldT) - if ignored { - continue - } - - raw = append(raw, renderFormField(label, name, fType, fieldV.Interface(), id, class, required)) - } - return template.HTML(strings.Join(raw, "
")) -} - -// renderFormField returns a string containing HTML of a single form field. -func renderFormField(label, name, fType string, value interface{}, id string, class string, required bool) string { - if id != "" { - id = " id=\"" + id + "\"" - } - - if class != "" { - class = " class=\"" + class + "\"" - } - - requiredString := "" - if required { - requiredString = " required" - } - - if isValidForInput(fType) { - return fmt.Sprintf(`%v`, label, id, class, name, fType, value, requiredString) - } - - return fmt.Sprintf(`%v<%v%v%v name="%v"%v>%v`, label, fType, id, class, name, requiredString, value, fType) -} - -// isValidForInput checks if fType is a valid value for the `type` property of an HTML input element. -func isValidForInput(fType string) bool { - validInputTypes := strings.Fields("text password checkbox radio submit reset hidden image file button search email url tel number range date month week time datetime datetime-local color") - for _, validType := range validInputTypes { - if fType == validType { - return true - } - } - return false -} - -// parseFormTag takes the stuct-tag of a StructField and parses the `form` value. -// returned are the form label, name-property, type and wether the field should be ignored. -func parseFormTag(fieldT reflect.StructField) (label, name, fType string, id string, class string, ignored bool, required bool) { - tags := strings.Split(fieldT.Tag.Get("form"), ",") - label = fieldT.Name + ": " - name = fieldT.Name - fType = "text" - ignored = false - id = fieldT.Tag.Get("id") - class = fieldT.Tag.Get("class") - - required = false - requiredField := fieldT.Tag.Get("required") - if requiredField != "-" && requiredField != "" { - required, _ = strconv.ParseBool(requiredField) - } - - switch len(tags) { - case 1: - if tags[0] == "-" { - ignored = true - } - if len(tags[0]) > 0 { - name = tags[0] - } - case 2: - if len(tags[0]) > 0 { - name = tags[0] - } - if len(tags[1]) > 0 { - fType = tags[1] - } - case 3: - if len(tags[0]) > 0 { - name = tags[0] - } - if len(tags[1]) > 0 { - fType = tags[1] - } - if len(tags[2]) > 0 { - label = tags[2] - } - } - - return -} - -func isStructPtr(t reflect.Type) bool { - return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct -} - -// go1.2 added template funcs. begin -var ( - errBadComparisonType = errors.New("invalid type for comparison") - errBadComparison = errors.New("incompatible types for comparison") - errNoComparison = errors.New("missing argument for comparison") -) - -type kind int - -const ( - invalidKind kind = iota - boolKind - complexKind - intKind - floatKind - stringKind - uintKind -) - -func basicKind(v reflect.Value) (kind, error) { - switch v.Kind() { - case reflect.Bool: - return boolKind, nil - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return intKind, nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return uintKind, nil - case reflect.Float32, reflect.Float64: - return floatKind, nil - case reflect.Complex64, reflect.Complex128: - return complexKind, nil - case reflect.String: - return stringKind, nil - } - return invalidKind, errBadComparisonType -} - -// eq evaluates the comparison a == b || a == c || ... -func eq(arg1 interface{}, arg2 ...interface{}) (bool, error) { - v1 := reflect.ValueOf(arg1) - k1, err := basicKind(v1) - if err != nil { - return false, err - } - if len(arg2) == 0 { - return false, errNoComparison - } - for _, arg := range arg2 { - v2 := reflect.ValueOf(arg) - k2, err := basicKind(v2) - if err != nil { - return false, err - } - if k1 != k2 { - return false, errBadComparison - } - truth := false - switch k1 { - case boolKind: - truth = v1.Bool() == v2.Bool() - case complexKind: - truth = v1.Complex() == v2.Complex() - case floatKind: - truth = v1.Float() == v2.Float() - case intKind: - truth = v1.Int() == v2.Int() - case stringKind: - truth = v1.String() == v2.String() - case uintKind: - truth = v1.Uint() == v2.Uint() - default: - panic("invalid kind") - } - if truth { - return true, nil - } - } - return false, nil -} - -// ne evaluates the comparison a != b. -func ne(arg1, arg2 interface{}) (bool, error) { - // != is the inverse of ==. - equal, err := eq(arg1, arg2) - return !equal, err -} - -// lt evaluates the comparison a < b. -func lt(arg1, arg2 interface{}) (bool, error) { - v1 := reflect.ValueOf(arg1) - k1, err := basicKind(v1) - if err != nil { - return false, err - } - v2 := reflect.ValueOf(arg2) - k2, err := basicKind(v2) - if err != nil { - return false, err - } - if k1 != k2 { - return false, errBadComparison - } - truth := false - switch k1 { - case boolKind, complexKind: - return false, errBadComparisonType - case floatKind: - truth = v1.Float() < v2.Float() - case intKind: - truth = v1.Int() < v2.Int() - case stringKind: - truth = v1.String() < v2.String() - case uintKind: - truth = v1.Uint() < v2.Uint() - default: - panic("invalid kind") - } - return truth, nil -} - -// le evaluates the comparison <= b. -func le(arg1, arg2 interface{}) (bool, error) { - // <= is < or ==. - lessThan, err := lt(arg1, arg2) - if lessThan || err != nil { - return lessThan, err - } - return eq(arg1, arg2) -} - -// gt evaluates the comparison a > b. -func gt(arg1, arg2 interface{}) (bool, error) { - // > is the inverse of <=. - lessOrEqual, err := le(arg1, arg2) - if err != nil { - return false, err - } - return !lessOrEqual, nil -} - -// ge evaluates the comparison a >= b. -func ge(arg1, arg2 interface{}) (bool, error) { - // >= is the inverse of <. - lessThan, err := lt(arg1, arg2) - if err != nil { - return false, err - } - return !lessThan, nil -} - -// MapGet getting value from map by keys -// usage: -// Data["m"] = M{ -// "a": 1, -// "1": map[string]float64{ -// "c": 4, -// }, -// } -// -// {{ map_get m "a" }} // return 1 -// {{ map_get m 1 "c" }} // return 4 -func MapGet(arg1 interface{}, arg2 ...interface{}) (interface{}, error) { - arg1Type := reflect.TypeOf(arg1) - arg1Val := reflect.ValueOf(arg1) - - if arg1Type.Kind() == reflect.Map && len(arg2) > 0 { - // check whether arg2[0] type equals to arg1 key type - // if they are different, make conversion - arg2Val := reflect.ValueOf(arg2[0]) - arg2Type := reflect.TypeOf(arg2[0]) - if arg2Type.Kind() != arg1Type.Key().Kind() { - // convert arg2Value to string - var arg2ConvertedVal interface{} - arg2String := fmt.Sprintf("%v", arg2[0]) - - // convert string representation to any other type - switch arg1Type.Key().Kind() { - case reflect.Bool: - arg2ConvertedVal, _ = strconv.ParseBool(arg2String) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - arg2ConvertedVal, _ = strconv.ParseInt(arg2String, 0, 64) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - arg2ConvertedVal, _ = strconv.ParseUint(arg2String, 0, 64) - case reflect.Float32, reflect.Float64: - arg2ConvertedVal, _ = strconv.ParseFloat(arg2String, 64) - case reflect.String: - arg2ConvertedVal = arg2String - default: - arg2ConvertedVal = arg2Val.Interface() - } - arg2Val = reflect.ValueOf(arg2ConvertedVal) - } - - storedVal := arg1Val.MapIndex(arg2Val) - - if storedVal.IsValid() { - var result interface{} - - switch arg1Type.Elem().Kind() { - case reflect.Bool: - result = storedVal.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - result = storedVal.Int() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - result = storedVal.Uint() - case reflect.Float32, reflect.Float64: - result = storedVal.Float() - case reflect.String: - result = storedVal.String() - default: - result = storedVal.Interface() - } - - // if there is more keys, handle this recursively - if len(arg2) > 1 { - return MapGet(result, arg2[1:]...) - } - return result, nil - } - return nil, nil - - } - return nil, nil -} diff --git a/vendor/github.com/astaxie/beego/toolbox/healthcheck.go b/vendor/github.com/astaxie/beego/toolbox/healthcheck.go deleted file mode 100644 index e3544b3a..00000000 --- a/vendor/github.com/astaxie/beego/toolbox/healthcheck.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package toolbox healthcheck -// -// type DatabaseCheck struct { -// } -// -// func (dc *DatabaseCheck) Check() error { -// if dc.isConnected() { -// return nil -// } else { -// return errors.New("can't connect database") -// } -// } -// -// AddHealthCheck("database",&DatabaseCheck{}) -// -// more docs: http://beego.me/docs/module/toolbox.md -package toolbox - -// AdminCheckList holds health checker map -var AdminCheckList map[string]HealthChecker - -// HealthChecker health checker interface -type HealthChecker interface { - Check() error -} - -// AddHealthCheck add health checker with name string -func AddHealthCheck(name string, hc HealthChecker) { - AdminCheckList[name] = hc -} - -func init() { - AdminCheckList = make(map[string]HealthChecker) -} diff --git a/vendor/github.com/astaxie/beego/toolbox/profile.go b/vendor/github.com/astaxie/beego/toolbox/profile.go deleted file mode 100644 index 06e40ede..00000000 --- a/vendor/github.com/astaxie/beego/toolbox/profile.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package toolbox - -import ( - "fmt" - "io" - "log" - "os" - "path" - "runtime" - "runtime/debug" - "runtime/pprof" - "strconv" - "time" -) - -var startTime = time.Now() -var pid int - -func init() { - pid = os.Getpid() -} - -// ProcessInput parse input command string -func ProcessInput(input string, w io.Writer) { - switch input { - case "lookup goroutine": - p := pprof.Lookup("goroutine") - p.WriteTo(w, 2) - case "lookup heap": - p := pprof.Lookup("heap") - p.WriteTo(w, 2) - case "lookup threadcreate": - p := pprof.Lookup("threadcreate") - p.WriteTo(w, 2) - case "lookup block": - p := pprof.Lookup("block") - p.WriteTo(w, 2) - case "get cpuprof": - GetCPUProfile(w) - case "get memprof": - MemProf(w) - case "gc summary": - PrintGCSummary(w) - } -} - -// MemProf record memory profile in pprof -func MemProf(w io.Writer) { - filename := "mem-" + strconv.Itoa(pid) + ".memprof" - if f, err := os.Create(filename); err != nil { - fmt.Fprintf(w, "create file %s error %s\n", filename, err.Error()) - log.Fatal("record heap profile failed: ", err) - } else { - runtime.GC() - pprof.WriteHeapProfile(f) - f.Close() - fmt.Fprintf(w, "create heap profile %s \n", filename) - _, fl := path.Split(os.Args[0]) - fmt.Fprintf(w, "Now you can use this to check it: go tool pprof %s %s\n", fl, filename) - } -} - -// GetCPUProfile start cpu profile monitor -func GetCPUProfile(w io.Writer) { - sec := 30 - filename := "cpu-" + strconv.Itoa(pid) + ".pprof" - f, err := os.Create(filename) - if err != nil { - fmt.Fprintf(w, "Could not enable CPU profiling: %s\n", err) - log.Fatal("record cpu profile failed: ", err) - } - pprof.StartCPUProfile(f) - time.Sleep(time.Duration(sec) * time.Second) - pprof.StopCPUProfile() - - fmt.Fprintf(w, "create cpu profile %s \n", filename) - _, fl := path.Split(os.Args[0]) - fmt.Fprintf(w, "Now you can use this to check it: go tool pprof %s %s\n", fl, filename) -} - -// PrintGCSummary print gc information to io.Writer -func PrintGCSummary(w io.Writer) { - memStats := &runtime.MemStats{} - runtime.ReadMemStats(memStats) - gcstats := &debug.GCStats{PauseQuantiles: make([]time.Duration, 100)} - debug.ReadGCStats(gcstats) - - printGC(memStats, gcstats, w) -} - -func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) { - - if gcstats.NumGC > 0 { - lastPause := gcstats.Pause[0] - elapsed := time.Now().Sub(startTime) - overhead := float64(gcstats.PauseTotal) / float64(elapsed) * 100 - allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds() - - fmt.Fprintf(w, "NumGC:%d Pause:%s Pause(Avg):%s Overhead:%3.2f%% Alloc:%s Sys:%s Alloc(Rate):%s/s Histogram:%s %s %s \n", - gcstats.NumGC, - toS(lastPause), - toS(avg(gcstats.Pause)), - overhead, - toH(memStats.Alloc), - toH(memStats.Sys), - toH(uint64(allocatedRate)), - toS(gcstats.PauseQuantiles[94]), - toS(gcstats.PauseQuantiles[98]), - toS(gcstats.PauseQuantiles[99])) - } else { - // while GC has disabled - elapsed := time.Now().Sub(startTime) - allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds() - - fmt.Fprintf(w, "Alloc:%s Sys:%s Alloc(Rate):%s/s\n", - toH(memStats.Alloc), - toH(memStats.Sys), - toH(uint64(allocatedRate))) - } -} - -func avg(items []time.Duration) time.Duration { - var sum time.Duration - for _, item := range items { - sum += item - } - return time.Duration(int64(sum) / int64(len(items))) -} - -// format bytes number friendly -func toH(bytes uint64) string { - switch { - case bytes < 1024: - return fmt.Sprintf("%dB", bytes) - case bytes < 1024*1024: - return fmt.Sprintf("%.2fK", float64(bytes)/1024) - case bytes < 1024*1024*1024: - return fmt.Sprintf("%.2fM", float64(bytes)/1024/1024) - default: - return fmt.Sprintf("%.2fG", float64(bytes)/1024/1024/1024) - } -} - -// short string format -func toS(d time.Duration) string { - - u := uint64(d) - if u < uint64(time.Second) { - switch { - case u == 0: - return "0" - case u < uint64(time.Microsecond): - return fmt.Sprintf("%.2fns", float64(u)) - case u < uint64(time.Millisecond): - return fmt.Sprintf("%.2fus", float64(u)/1000) - default: - return fmt.Sprintf("%.2fms", float64(u)/1000/1000) - } - } else { - switch { - case u < uint64(time.Minute): - return fmt.Sprintf("%.2fs", float64(u)/1000/1000/1000) - case u < uint64(time.Hour): - return fmt.Sprintf("%.2fm", float64(u)/1000/1000/1000/60) - default: - return fmt.Sprintf("%.2fh", float64(u)/1000/1000/1000/60/60) - } - } - -} diff --git a/vendor/github.com/astaxie/beego/toolbox/statistics.go b/vendor/github.com/astaxie/beego/toolbox/statistics.go deleted file mode 100644 index fd73dfb3..00000000 --- a/vendor/github.com/astaxie/beego/toolbox/statistics.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package toolbox - -import ( - "fmt" - "sync" - "time" -) - -// Statistics struct -type Statistics struct { - RequestURL string - RequestController string - RequestNum int64 - MinTime time.Duration - MaxTime time.Duration - TotalTime time.Duration -} - -// URLMap contains several statistics struct to log different data -type URLMap struct { - lock sync.RWMutex - LengthLimit int //limit the urlmap's length if it's equal to 0 there's no limit - urlmap map[string]map[string]*Statistics -} - -// AddStatistics add statistics task. -// it needs request method, request url, request controller and statistics time duration -func (m *URLMap) AddStatistics(requestMethod, requestURL, requestController string, requesttime time.Duration) { - m.lock.Lock() - defer m.lock.Unlock() - if method, ok := m.urlmap[requestURL]; ok { - if s, ok := method[requestMethod]; ok { - s.RequestNum++ - if s.MaxTime < requesttime { - s.MaxTime = requesttime - } - if s.MinTime > requesttime { - s.MinTime = requesttime - } - s.TotalTime += requesttime - } else { - nb := &Statistics{ - RequestURL: requestURL, - RequestController: requestController, - RequestNum: 1, - MinTime: requesttime, - MaxTime: requesttime, - TotalTime: requesttime, - } - m.urlmap[requestURL][requestMethod] = nb - } - - } else { - if m.LengthLimit > 0 && m.LengthLimit <= len(m.urlmap) { - return - } - methodmap := make(map[string]*Statistics) - nb := &Statistics{ - RequestURL: requestURL, - RequestController: requestController, - RequestNum: 1, - MinTime: requesttime, - MaxTime: requesttime, - TotalTime: requesttime, - } - methodmap[requestMethod] = nb - m.urlmap[requestURL] = methodmap - } -} - -// GetMap put url statistics result in io.Writer -func (m *URLMap) GetMap() map[string]interface{} { - m.lock.RLock() - defer m.lock.RUnlock() - - var fields = []string{"requestUrl", "method", "times", "used", "max used", "min used", "avg used"} - - var resultLists [][]string - content := make(map[string]interface{}) - content["Fields"] = fields - - for k, v := range m.urlmap { - for kk, vv := range v { - result := []string{ - fmt.Sprintf("% -50s", k), - fmt.Sprintf("% -10s", kk), - fmt.Sprintf("% -16d", vv.RequestNum), - fmt.Sprintf("%d", vv.TotalTime), - fmt.Sprintf("% -16s", toS(vv.TotalTime)), - fmt.Sprintf("%d", vv.MaxTime), - fmt.Sprintf("% -16s", toS(vv.MaxTime)), - fmt.Sprintf("%d", vv.MinTime), - fmt.Sprintf("% -16s", toS(vv.MinTime)), - fmt.Sprintf("%d", time.Duration(int64(vv.TotalTime)/vv.RequestNum)), - fmt.Sprintf("% -16s", toS(time.Duration(int64(vv.TotalTime)/vv.RequestNum))), - } - resultLists = append(resultLists, result) - } - } - content["Data"] = resultLists - return content -} - -// GetMapData return all mapdata -func (m *URLMap) GetMapData() []map[string]interface{} { - m.lock.RLock() - defer m.lock.RUnlock() - - var resultLists []map[string]interface{} - - for k, v := range m.urlmap { - for kk, vv := range v { - result := map[string]interface{}{ - "request_url": k, - "method": kk, - "times": vv.RequestNum, - "total_time": toS(vv.TotalTime), - "max_time": toS(vv.MaxTime), - "min_time": toS(vv.MinTime), - "avg_time": toS(time.Duration(int64(vv.TotalTime) / vv.RequestNum)), - } - resultLists = append(resultLists, result) - } - } - return resultLists -} - -// StatisticsMap hosld global statistics data map -var StatisticsMap *URLMap - -func init() { - StatisticsMap = &URLMap{ - urlmap: make(map[string]map[string]*Statistics), - } -} diff --git a/vendor/github.com/astaxie/beego/toolbox/task.go b/vendor/github.com/astaxie/beego/toolbox/task.go deleted file mode 100644 index d2a94ba9..00000000 --- a/vendor/github.com/astaxie/beego/toolbox/task.go +++ /dev/null @@ -1,634 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package toolbox - -import ( - "log" - "math" - "sort" - "strconv" - "strings" - "sync" - "time" -) - -// bounds provides a range of acceptable values (plus a map of name to value). -type bounds struct { - min, max uint - names map[string]uint -} - -// The bounds for each field. -var ( - AdminTaskList map[string]Tasker - taskLock sync.RWMutex - stop chan bool - changed chan bool - isstart bool - seconds = bounds{0, 59, nil} - minutes = bounds{0, 59, nil} - hours = bounds{0, 23, nil} - days = bounds{1, 31, nil} - months = bounds{1, 12, map[string]uint{ - "jan": 1, - "feb": 2, - "mar": 3, - "apr": 4, - "may": 5, - "jun": 6, - "jul": 7, - "aug": 8, - "sep": 9, - "oct": 10, - "nov": 11, - "dec": 12, - }} - weeks = bounds{0, 6, map[string]uint{ - "sun": 0, - "mon": 1, - "tue": 2, - "wed": 3, - "thu": 4, - "fri": 5, - "sat": 6, - }} -) - -const ( - // Set the top bit if a star was included in the expression. - starBit = 1 << 63 -) - -// Schedule time taks schedule -type Schedule struct { - Second uint64 - Minute uint64 - Hour uint64 - Day uint64 - Month uint64 - Week uint64 -} - -// TaskFunc task func type -type TaskFunc func() error - -// Tasker task interface -type Tasker interface { - GetSpec() string - GetStatus() string - Run() error - SetNext(time.Time) - GetNext() time.Time - SetPrev(time.Time) - GetPrev() time.Time -} - -// task error -type taskerr struct { - t time.Time - errinfo string -} - -// Task task struct -type Task struct { - Taskname string - Spec *Schedule - SpecStr string - DoFunc TaskFunc - Prev time.Time - Next time.Time - Errlist []*taskerr // like errtime:errinfo - ErrLimit int // max length for the errlist, 0 stand for no limit -} - -// NewTask add new task with name, time and func -func NewTask(tname string, spec string, f TaskFunc) *Task { - - task := &Task{ - Taskname: tname, - DoFunc: f, - ErrLimit: 100, - SpecStr: spec, - } - task.SetCron(spec) - return task -} - -// GetSpec get spec string -func (t *Task) GetSpec() string { - return t.SpecStr -} - -// GetStatus get current task status -func (t *Task) GetStatus() string { - var str string - for _, v := range t.Errlist { - str += v.t.String() + ":" + v.errinfo + "
" - } - return str -} - -// Run run all tasks -func (t *Task) Run() error { - err := t.DoFunc() - if err != nil { - if t.ErrLimit > 0 && t.ErrLimit > len(t.Errlist) { - t.Errlist = append(t.Errlist, &taskerr{t: t.Next, errinfo: err.Error()}) - } - } - return err -} - -// SetNext set next time for this task -func (t *Task) SetNext(now time.Time) { - t.Next = t.Spec.Next(now) -} - -// GetNext get the next call time of this task -func (t *Task) GetNext() time.Time { - return t.Next -} - -// SetPrev set prev time of this task -func (t *Task) SetPrev(now time.Time) { - t.Prev = now -} - -// GetPrev get prev time of this task -func (t *Task) GetPrev() time.Time { - return t.Prev -} - -// six columns mean: -// second:0-59 -// minute:0-59 -// hour:1-23 -// day:1-31 -// month:1-12 -// week:0-6(0 means Sunday) - -// SetCron some signals: -// *: any time -// ,:  separate signal -//   -:duration -// /n : do as n times of time duration -///////////////////////////////////////////////////////// -// 0/30 * * * * * every 30s -// 0 43 21 * * * 21:43 -// 0 15 05 * * *    05:15 -// 0 0 17 * * * 17:00 -// 0 0 17 * * 1 17:00 in every Monday -// 0 0,10 17 * * 0,2,3 17:00 and 17:10 in every Sunday, Tuesday and Wednesday -// 0 0-10 17 1 * * 17:00 to 17:10 in 1 min duration each time on the first day of month -// 0 0 0 1,15 * 1 0:00 on the 1st day and 15th day of month -// 0 42 4 1 * *     4:42 on the 1st day of month -// 0 0 21 * * 1-6   21:00 from Monday to Saturday -// 0 0,10,20,30,40,50 * * * *  every 10 min duration -// 0 */10 * * * *        every 10 min duration -// 0 * 1 * * *         1:00 to 1:59 in 1 min duration each time -// 0 0 1 * * *         1:00 -// 0 0 */1 * * *        0 min of hour in 1 hour duration -// 0 0 * * * *         0 min of hour in 1 hour duration -// 0 2 8-20/3 * * *       8:02, 11:02, 14:02, 17:02, 20:02 -// 0 30 5 1,15 * *       5:30 on the 1st day and 15th day of month -func (t *Task) SetCron(spec string) { - t.Spec = t.parse(spec) -} - -func (t *Task) parse(spec string) *Schedule { - if len(spec) > 0 && spec[0] == '@' { - return t.parseSpec(spec) - } - // Split on whitespace. We require 5 or 6 fields. - // (second) (minute) (hour) (day of month) (month) (day of week, optional) - fields := strings.Fields(spec) - if len(fields) != 5 && len(fields) != 6 { - log.Panicf("Expected 5 or 6 fields, found %d: %s", len(fields), spec) - } - - // If a sixth field is not provided (DayOfWeek), then it is equivalent to star. - if len(fields) == 5 { - fields = append(fields, "*") - } - - schedule := &Schedule{ - Second: getField(fields[0], seconds), - Minute: getField(fields[1], minutes), - Hour: getField(fields[2], hours), - Day: getField(fields[3], days), - Month: getField(fields[4], months), - Week: getField(fields[5], weeks), - } - - return schedule -} - -func (t *Task) parseSpec(spec string) *Schedule { - switch spec { - case "@yearly", "@annually": - return &Schedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Day: 1 << days.min, - Month: 1 << months.min, - Week: all(weeks), - } - - case "@monthly": - return &Schedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Day: 1 << days.min, - Month: all(months), - Week: all(weeks), - } - - case "@weekly": - return &Schedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Day: all(days), - Month: all(months), - Week: 1 << weeks.min, - } - - case "@daily", "@midnight": - return &Schedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: 1 << hours.min, - Day: all(days), - Month: all(months), - Week: all(weeks), - } - - case "@hourly": - return &Schedule{ - Second: 1 << seconds.min, - Minute: 1 << minutes.min, - Hour: all(hours), - Day: all(days), - Month: all(months), - Week: all(weeks), - } - } - log.Panicf("Unrecognized descriptor: %s", spec) - return nil -} - -// Next set schedule to next time -func (s *Schedule) Next(t time.Time) time.Time { - - // Start at the earliest possible time (the upcoming second). - t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) - - // This flag indicates whether a field has been incremented. - added := false - - // If no time is found within five years, return zero. - yearLimit := t.Year() + 5 - -WRAP: - if t.Year() > yearLimit { - return time.Time{} - } - - // Find the first applicable month. - // If it's this month, then do nothing. - for 1< 0 - dowMatch = 1< 0 - ) - - if s.Day&starBit > 0 || s.Week&starBit > 0 { - return domMatch && dowMatch - } - return domMatch || dowMatch -} - -// StartTask start all tasks -func StartTask() { - taskLock.Lock() - defer taskLock.Unlock() - if isstart { - //If already started, no need to start another goroutine. - return - } - isstart = true - go run() -} - -func run() { - now := time.Now().Local() - for _, t := range AdminTaskList { - t.SetNext(now) - } - - for { - // we only use RLock here because NewMapSorter copy the reference, do not change any thing - taskLock.RLock() - sortList := NewMapSorter(AdminTaskList) - taskLock.RUnlock() - sortList.Sort() - var effective time.Time - if len(AdminTaskList) == 0 || sortList.Vals[0].GetNext().IsZero() { - // If there are no entries yet, just sleep - it still handles new entries - // and stop requests. - effective = now.AddDate(10, 0, 0) - } else { - effective = sortList.Vals[0].GetNext() - } - select { - case now = <-time.After(effective.Sub(now)): - // Run every entry whose next time was this effective time. - for _, e := range sortList.Vals { - if e.GetNext() != effective { - break - } - go e.Run() - e.SetPrev(e.GetNext()) - e.SetNext(effective) - } - continue - case <-changed: - now = time.Now().Local() - taskLock.Lock() - for _, t := range AdminTaskList { - t.SetNext(now) - } - taskLock.Unlock() - continue - case <-stop: - return - } - } -} - -// StopTask stop all tasks -func StopTask() { - taskLock.Lock() - defer taskLock.Unlock() - if isstart { - isstart = false - stop <- true - } - -} - -// AddTask add task with name -func AddTask(taskname string, t Tasker) { - taskLock.Lock() - defer taskLock.Unlock() - t.SetNext(time.Now().Local()) - AdminTaskList[taskname] = t - if isstart { - changed <- true - } -} - -// DeleteTask delete task with name -func DeleteTask(taskname string) { - taskLock.Lock() - defer taskLock.Unlock() - delete(AdminTaskList, taskname) - if isstart { - changed <- true - } -} - -// MapSorter sort map for tasker -type MapSorter struct { - Keys []string - Vals []Tasker -} - -// NewMapSorter create new tasker map -func NewMapSorter(m map[string]Tasker) *MapSorter { - ms := &MapSorter{ - Keys: make([]string, 0, len(m)), - Vals: make([]Tasker, 0, len(m)), - } - for k, v := range m { - ms.Keys = append(ms.Keys, k) - ms.Vals = append(ms.Vals, v) - } - return ms -} - -// Sort sort tasker map -func (ms *MapSorter) Sort() { - sort.Sort(ms) -} - -func (ms *MapSorter) Len() int { return len(ms.Keys) } -func (ms *MapSorter) Less(i, j int) bool { - if ms.Vals[i].GetNext().IsZero() { - return false - } - if ms.Vals[j].GetNext().IsZero() { - return true - } - return ms.Vals[i].GetNext().Before(ms.Vals[j].GetNext()) -} -func (ms *MapSorter) Swap(i, j int) { - ms.Vals[i], ms.Vals[j] = ms.Vals[j], ms.Vals[i] - ms.Keys[i], ms.Keys[j] = ms.Keys[j], ms.Keys[i] -} - -func getField(field string, r bounds) uint64 { - // list = range {"," range} - var bits uint64 - ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) - for _, expr := range ranges { - bits |= getRange(expr, r) - } - return bits -} - -// getRange returns the bits indicated by the given expression: -// number | number "-" number [ "/" number ] -func getRange(expr string, r bounds) uint64 { - - var ( - start, end, step uint - rangeAndStep = strings.Split(expr, "/") - lowAndHigh = strings.Split(rangeAndStep[0], "-") - singleDigit = len(lowAndHigh) == 1 - ) - - var extrastar uint64 - if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { - start = r.min - end = r.max - extrastar = starBit - } else { - start = parseIntOrName(lowAndHigh[0], r.names) - switch len(lowAndHigh) { - case 1: - end = start - case 2: - end = parseIntOrName(lowAndHigh[1], r.names) - default: - log.Panicf("Too many hyphens: %s", expr) - } - } - - switch len(rangeAndStep) { - case 1: - step = 1 - case 2: - step = mustParseInt(rangeAndStep[1]) - - // Special handling: "N/step" means "N-max/step". - if singleDigit { - end = r.max - } - default: - log.Panicf("Too many slashes: %s", expr) - } - - if start < r.min { - log.Panicf("Beginning of range (%d) below minimum (%d): %s", start, r.min, expr) - } - if end > r.max { - log.Panicf("End of range (%d) above maximum (%d): %s", end, r.max, expr) - } - if start > end { - log.Panicf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr) - } - - return getBits(start, end, step) | extrastar -} - -// parseIntOrName returns the (possibly-named) integer contained in expr. -func parseIntOrName(expr string, names map[string]uint) uint { - if names != nil { - if namedInt, ok := names[strings.ToLower(expr)]; ok { - return namedInt - } - } - return mustParseInt(expr) -} - -// mustParseInt parses the given expression as an int or panics. -func mustParseInt(expr string) uint { - num, err := strconv.Atoi(expr) - if err != nil { - log.Panicf("Failed to parse int from %s: %s", expr, err) - } - if num < 0 { - log.Panicf("Negative number (%d) not allowed: %s", num, expr) - } - - return uint(num) -} - -// getBits sets all bits in the range [min, max], modulo the given step size. -func getBits(min, max, step uint) uint64 { - var bits uint64 - - // If step is 1, use shifts. - if step == 1 { - return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min) - } - - // Else, use a simple loop. - for i := min; i <= max; i += step { - bits |= 1 << i - } - return bits -} - -// all returns all bits within the given bounds. (plus the star bit) -func all(r bounds) uint64 { - return getBits(r.min, r.max, 1) | starBit -} - -func init() { - AdminTaskList = make(map[string]Tasker) - stop = make(chan bool) - changed = make(chan bool) -} diff --git a/vendor/github.com/astaxie/beego/tree.go b/vendor/github.com/astaxie/beego/tree.go deleted file mode 100644 index 9e53003b..00000000 --- a/vendor/github.com/astaxie/beego/tree.go +++ /dev/null @@ -1,585 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package beego - -import ( - "path" - "regexp" - "strings" - - "github.com/astaxie/beego/context" - "github.com/astaxie/beego/utils" -) - -var ( - allowSuffixExt = []string{".json", ".xml", ".html"} -) - -// Tree has three elements: FixRouter/wildcard/leaves -// fixRouter stores Fixed Router -// wildcard stores params -// leaves store the endpoint information -type Tree struct { - //prefix set for static router - prefix string - //search fix route first - fixrouters []*Tree - //if set, failure to match fixrouters search then search wildcard - wildcard *Tree - //if set, failure to match wildcard search - leaves []*leafInfo -} - -// NewTree return a new Tree -func NewTree() *Tree { - return &Tree{} -} - -// AddTree will add tree to the exist Tree -// prefix should has no params -func (t *Tree) AddTree(prefix string, tree *Tree) { - t.addtree(splitPath(prefix), tree, nil, "") -} - -func (t *Tree) addtree(segments []string, tree *Tree, wildcards []string, reg string) { - if len(segments) == 0 { - panic("prefix should has path") - } - seg := segments[0] - iswild, params, regexpStr := splitSegment(seg) - // if it's ? meaning can igone this, so add one more rule for it - if len(params) > 0 && params[0] == ":" { - params = params[1:] - if len(segments[1:]) > 0 { - t.addtree(segments[1:], tree, append(wildcards, params...), reg) - } else { - filterTreeWithPrefix(tree, wildcards, reg) - } - } - //Rule: /login/*/access match /login/2009/11/access - //if already has *, and when loop the access, should as a regexpStr - if !iswild && utils.InSlice(":splat", wildcards) { - iswild = true - regexpStr = seg - } - //Rule: /user/:id/* - if seg == "*" && len(wildcards) > 0 && reg == "" { - regexpStr = "(.+)" - } - if len(segments) == 1 { - if iswild { - if regexpStr != "" { - if reg == "" { - rr := "" - for _, w := range wildcards { - if w == ":splat" { - rr = rr + "(.+)/" - } else { - rr = rr + "([^/]+)/" - } - } - regexpStr = rr + regexpStr - } else { - regexpStr = "/" + regexpStr - } - } else if reg != "" { - if seg == "*.*" { - regexpStr = "([^.]+).(.+)" - } else { - for _, w := range params { - if w == "." || w == ":" { - continue - } - regexpStr = "([^/]+)/" + regexpStr - } - } - } - reg = strings.Trim(reg+"/"+regexpStr, "/") - filterTreeWithPrefix(tree, append(wildcards, params...), reg) - t.wildcard = tree - } else { - reg = strings.Trim(reg+"/"+regexpStr, "/") - filterTreeWithPrefix(tree, append(wildcards, params...), reg) - tree.prefix = seg - t.fixrouters = append(t.fixrouters, tree) - } - return - } - - if iswild { - if t.wildcard == nil { - t.wildcard = NewTree() - } - if regexpStr != "" { - if reg == "" { - rr := "" - for _, w := range wildcards { - if w == ":splat" { - rr = rr + "(.+)/" - } else { - rr = rr + "([^/]+)/" - } - } - regexpStr = rr + regexpStr - } else { - regexpStr = "/" + regexpStr - } - } else if reg != "" { - if seg == "*.*" { - regexpStr = "([^.]+).(.+)" - params = params[1:] - } else { - for range params { - regexpStr = "([^/]+)/" + regexpStr - } - } - } else { - if seg == "*.*" { - params = params[1:] - } - } - reg = strings.TrimRight(strings.TrimRight(reg, "/")+"/"+regexpStr, "/") - t.wildcard.addtree(segments[1:], tree, append(wildcards, params...), reg) - } else { - subTree := NewTree() - subTree.prefix = seg - t.fixrouters = append(t.fixrouters, subTree) - subTree.addtree(segments[1:], tree, append(wildcards, params...), reg) - } -} - -func filterTreeWithPrefix(t *Tree, wildcards []string, reg string) { - for _, v := range t.fixrouters { - filterTreeWithPrefix(v, wildcards, reg) - } - if t.wildcard != nil { - filterTreeWithPrefix(t.wildcard, wildcards, reg) - } - for _, l := range t.leaves { - if reg != "" { - if l.regexps != nil { - l.wildcards = append(wildcards, l.wildcards...) - l.regexps = regexp.MustCompile("^" + reg + "/" + strings.Trim(l.regexps.String(), "^$") + "$") - } else { - for _, v := range l.wildcards { - if v == ":splat" { - reg = reg + "/(.+)" - } else { - reg = reg + "/([^/]+)" - } - } - l.regexps = regexp.MustCompile("^" + reg + "$") - l.wildcards = append(wildcards, l.wildcards...) - } - } else { - l.wildcards = append(wildcards, l.wildcards...) - if l.regexps != nil { - for _, w := range wildcards { - if w == ":splat" { - reg = "(.+)/" + reg - } else { - reg = "([^/]+)/" + reg - } - } - l.regexps = regexp.MustCompile("^" + reg + strings.Trim(l.regexps.String(), "^$") + "$") - } - } - } -} - -// AddRouter call addseg function -func (t *Tree) AddRouter(pattern string, runObject interface{}) { - t.addseg(splitPath(pattern), runObject, nil, "") -} - -// "/" -// "admin" -> -func (t *Tree) addseg(segments []string, route interface{}, wildcards []string, reg string) { - if len(segments) == 0 { - if reg != "" { - t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards, regexps: regexp.MustCompile("^" + reg + "$")}) - } else { - t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards}) - } - } else { - seg := segments[0] - iswild, params, regexpStr := splitSegment(seg) - // if it's ? meaning can igone this, so add one more rule for it - if len(params) > 0 && params[0] == ":" { - t.addseg(segments[1:], route, wildcards, reg) - params = params[1:] - } - //Rule: /login/*/access match /login/2009/11/access - //if already has *, and when loop the access, should as a regexpStr - if !iswild && utils.InSlice(":splat", wildcards) { - iswild = true - regexpStr = seg - } - //Rule: /user/:id/* - if seg == "*" && len(wildcards) > 0 && reg == "" { - regexpStr = "(.+)" - } - if iswild { - if t.wildcard == nil { - t.wildcard = NewTree() - } - if regexpStr != "" { - if reg == "" { - rr := "" - for _, w := range wildcards { - if w == ":splat" { - rr = rr + "(.+)/" - } else { - rr = rr + "([^/]+)/" - } - } - regexpStr = rr + regexpStr - } else { - regexpStr = "/" + regexpStr - } - } else if reg != "" { - if seg == "*.*" { - regexpStr = "/([^.]+).(.+)" - params = params[1:] - } else { - for range params { - regexpStr = "/([^/]+)" + regexpStr - } - } - } else { - if seg == "*.*" { - params = params[1:] - } - } - t.wildcard.addseg(segments[1:], route, append(wildcards, params...), reg+regexpStr) - } else { - var subTree *Tree - for _, sub := range t.fixrouters { - if sub.prefix == seg { - subTree = sub - break - } - } - if subTree == nil { - subTree = NewTree() - subTree.prefix = seg - t.fixrouters = append(t.fixrouters, subTree) - } - subTree.addseg(segments[1:], route, wildcards, reg) - } - } -} - -// Match router to runObject & params -func (t *Tree) Match(pattern string, ctx *context.Context) (runObject interface{}) { - if len(pattern) == 0 || pattern[0] != '/' { - return nil - } - w := make([]string, 0, 20) - return t.match(pattern[1:], pattern, w, ctx) -} - -func (t *Tree) match(treePattern string, pattern string, wildcardValues []string, ctx *context.Context) (runObject interface{}) { - if len(pattern) > 0 { - i := 0 - for ; i < len(pattern) && pattern[i] == '/'; i++ { - } - pattern = pattern[i:] - } - // Handle leaf nodes: - if len(pattern) == 0 { - for _, l := range t.leaves { - if ok := l.match(treePattern, wildcardValues, ctx); ok { - return l.runObject - } - } - if t.wildcard != nil { - for _, l := range t.wildcard.leaves { - if ok := l.match(treePattern, wildcardValues, ctx); ok { - return l.runObject - } - } - } - return nil - } - var seg string - i, l := 0, len(pattern) - for ; i < l && pattern[i] != '/'; i++ { - } - if i == 0 { - seg = pattern - pattern = "" - } else { - seg = pattern[:i] - pattern = pattern[i:] - } - for _, subTree := range t.fixrouters { - if subTree.prefix == seg { - if len(pattern) != 0 && pattern[0] == '/' { - treePattern = pattern[1:] - } else { - treePattern = pattern - } - runObject = subTree.match(treePattern, pattern, wildcardValues, ctx) - if runObject != nil { - break - } - } - } - if runObject == nil && len(t.fixrouters) > 0 { - // Filter the .json .xml .html extension - for _, str := range allowSuffixExt { - if strings.HasSuffix(seg, str) { - for _, subTree := range t.fixrouters { - if subTree.prefix == seg[:len(seg)-len(str)] { - runObject = subTree.match(treePattern, pattern, wildcardValues, ctx) - if runObject != nil { - ctx.Input.SetParam(":ext", str[1:]) - } - } - } - } - } - } - if runObject == nil && t.wildcard != nil { - runObject = t.wildcard.match(treePattern, pattern, append(wildcardValues, seg), ctx) - } - - if runObject == nil && len(t.leaves) > 0 { - wildcardValues = append(wildcardValues, seg) - start, i := 0, 0 - for ; i < len(pattern); i++ { - if pattern[i] == '/' { - if i != 0 && start < len(pattern) { - wildcardValues = append(wildcardValues, pattern[start:i]) - } - start = i + 1 - continue - } - } - if start > 0 { - wildcardValues = append(wildcardValues, pattern[start:i]) - } - for _, l := range t.leaves { - if ok := l.match(treePattern, wildcardValues, ctx); ok { - return l.runObject - } - } - } - return runObject -} - -type leafInfo struct { - // names of wildcards that lead to this leaf. eg, ["id" "name"] for the wildcard ":id" and ":name" - wildcards []string - - // if the leaf is regexp - regexps *regexp.Regexp - - runObject interface{} -} - -func (leaf *leafInfo) match(treePattern string, wildcardValues []string, ctx *context.Context) (ok bool) { - //fmt.Println("Leaf:", wildcardValues, leaf.wildcards, leaf.regexps) - if leaf.regexps == nil { - if len(wildcardValues) == 0 && len(leaf.wildcards) == 0 { // static path - return true - } - // match * - if len(leaf.wildcards) == 1 && leaf.wildcards[0] == ":splat" { - ctx.Input.SetParam(":splat", treePattern) - return true - } - // match *.* or :id - if len(leaf.wildcards) >= 2 && leaf.wildcards[len(leaf.wildcards)-2] == ":path" && leaf.wildcards[len(leaf.wildcards)-1] == ":ext" { - if len(leaf.wildcards) == 2 { - lastone := wildcardValues[len(wildcardValues)-1] - strs := strings.SplitN(lastone, ".", 2) - if len(strs) == 2 { - ctx.Input.SetParam(":ext", strs[1]) - } - ctx.Input.SetParam(":path", path.Join(path.Join(wildcardValues[:len(wildcardValues)-1]...), strs[0])) - return true - } else if len(wildcardValues) < 2 { - return false - } - var index int - for index = 0; index < len(leaf.wildcards)-2; index++ { - ctx.Input.SetParam(leaf.wildcards[index], wildcardValues[index]) - } - lastone := wildcardValues[len(wildcardValues)-1] - strs := strings.SplitN(lastone, ".", 2) - if len(strs) == 2 { - ctx.Input.SetParam(":ext", strs[1]) - } - if index > (len(wildcardValues) - 1) { - ctx.Input.SetParam(":path", "") - } else { - ctx.Input.SetParam(":path", path.Join(path.Join(wildcardValues[index:len(wildcardValues)-1]...), strs[0])) - } - return true - } - // match :id - if len(leaf.wildcards) != len(wildcardValues) { - return false - } - for j, v := range leaf.wildcards { - ctx.Input.SetParam(v, wildcardValues[j]) - } - return true - } - - if !leaf.regexps.MatchString(path.Join(wildcardValues...)) { - return false - } - matches := leaf.regexps.FindStringSubmatch(path.Join(wildcardValues...)) - for i, match := range matches[1:] { - if i < len(leaf.wildcards) { - ctx.Input.SetParam(leaf.wildcards[i], match) - } - } - return true -} - -// "/" -> [] -// "/admin" -> ["admin"] -// "/admin/" -> ["admin"] -// "/admin/users" -> ["admin", "users"] -func splitPath(key string) []string { - key = strings.Trim(key, "/ ") - if key == "" { - return []string{} - } - return strings.Split(key, "/") -} - -// "admin" -> false, nil, "" -// ":id" -> true, [:id], "" -// "?:id" -> true, [: :id], "" : meaning can empty -// ":id:int" -> true, [:id], ([0-9]+) -// ":name:string" -> true, [:name], ([\w]+) -// ":id([0-9]+)" -> true, [:id], ([0-9]+) -// ":id([0-9]+)_:name" -> true, [:id :name], ([0-9]+)_(.+) -// "cms_:id_:page.html" -> true, [:id_ :page], cms_(.+)(.+).html -// "cms_:id(.+)_:page.html" -> true, [:id :page], cms_(.+)_(.+).html -// "*" -> true, [:splat], "" -// "*.*" -> true,[. :path :ext], "" . meaning separator -func splitSegment(key string) (bool, []string, string) { - if strings.HasPrefix(key, "*") { - if key == "*.*" { - return true, []string{".", ":path", ":ext"}, "" - } - return true, []string{":splat"}, "" - } - if strings.ContainsAny(key, ":") { - var paramsNum int - var out []rune - var start bool - var startexp bool - var param []rune - var expt []rune - var skipnum int - params := []string{} - reg := regexp.MustCompile(`[a-zA-Z0-9_]+`) - for i, v := range key { - if skipnum > 0 { - skipnum-- - continue - } - if start { - //:id:int and :name:string - if v == ':' { - if len(key) >= i+4 { - if key[i+1:i+4] == "int" { - out = append(out, []rune("([0-9]+)")...) - params = append(params, ":"+string(param)) - start = false - startexp = false - skipnum = 3 - param = make([]rune, 0) - paramsNum++ - continue - } - } - if len(key) >= i+7 { - if key[i+1:i+7] == "string" { - out = append(out, []rune(`([\w]+)`)...) - params = append(params, ":"+string(param)) - paramsNum++ - start = false - startexp = false - skipnum = 6 - param = make([]rune, 0) - continue - } - } - } - // params only support a-zA-Z0-9 - if reg.MatchString(string(v)) { - param = append(param, v) - continue - } - if v != '(' { - out = append(out, []rune(`(.+)`)...) - params = append(params, ":"+string(param)) - param = make([]rune, 0) - paramsNum++ - start = false - startexp = false - } - } - if startexp { - if v != ')' { - expt = append(expt, v) - continue - } - } - // Escape Sequence '\' - if i > 0 && key[i-1] == '\\' { - out = append(out, v) - } else if v == ':' { - param = make([]rune, 0) - start = true - } else if v == '(' { - startexp = true - start = false - if len(param) > 0 { - params = append(params, ":"+string(param)) - param = make([]rune, 0) - } - paramsNum++ - expt = make([]rune, 0) - expt = append(expt, '(') - } else if v == ')' { - startexp = false - expt = append(expt, ')') - out = append(out, expt...) - param = make([]rune, 0) - } else if v == '?' { - params = append(params, ":") - } else { - out = append(out, v) - } - } - if len(param) > 0 { - if paramsNum > 0 { - out = append(out, []rune(`(.+)`)...) - } - params = append(params, ":"+string(param)) - } - return true, params, string(out) - } - return false, nil, "" -} diff --git a/vendor/github.com/astaxie/beego/utils/caller.go b/vendor/github.com/astaxie/beego/utils/caller.go deleted file mode 100644 index 73c52a62..00000000 --- a/vendor/github.com/astaxie/beego/utils/caller.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "reflect" - "runtime" -) - -// GetFuncName get function name -func GetFuncName(i interface{}) string { - return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() -} diff --git a/vendor/github.com/astaxie/beego/utils/debug.go b/vendor/github.com/astaxie/beego/utils/debug.go deleted file mode 100644 index 93c27b70..00000000 --- a/vendor/github.com/astaxie/beego/utils/debug.go +++ /dev/null @@ -1,478 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "bytes" - "fmt" - "log" - "reflect" - "runtime" -) - -var ( - dunno = []byte("???") - centerDot = []byte("·") - dot = []byte(".") -) - -type pointerInfo struct { - prev *pointerInfo - n int - addr uintptr - pos int - used []int -} - -// Display print the data in console -func Display(data ...interface{}) { - display(true, data...) -} - -// GetDisplayString return data print string -func GetDisplayString(data ...interface{}) string { - return display(false, data...) -} - -func display(displayed bool, data ...interface{}) string { - var pc, file, line, ok = runtime.Caller(2) - - if !ok { - return "" - } - - var buf = new(bytes.Buffer) - - fmt.Fprintf(buf, "[Debug] at %s() [%s:%d]\n", function(pc), file, line) - - fmt.Fprintf(buf, "\n[Variables]\n") - - for i := 0; i < len(data); i += 2 { - var output = fomateinfo(len(data[i].(string))+3, data[i+1]) - fmt.Fprintf(buf, "%s = %s", data[i], output) - } - - if displayed { - log.Print(buf) - } - return buf.String() -} - -// return data dump and format bytes -func fomateinfo(headlen int, data ...interface{}) []byte { - var buf = new(bytes.Buffer) - - if len(data) > 1 { - fmt.Fprint(buf, " ") - - fmt.Fprint(buf, "[") - - fmt.Fprintln(buf) - } - - for k, v := range data { - var buf2 = new(bytes.Buffer) - var pointers *pointerInfo - var interfaces = make([]reflect.Value, 0, 10) - - printKeyValue(buf2, reflect.ValueOf(v), &pointers, &interfaces, nil, true, " ", 1) - - if k < len(data)-1 { - fmt.Fprint(buf2, ", ") - } - - fmt.Fprintln(buf2) - - buf.Write(buf2.Bytes()) - } - - if len(data) > 1 { - fmt.Fprintln(buf) - - fmt.Fprint(buf, " ") - - fmt.Fprint(buf, "]") - } - - return buf.Bytes() -} - -// check data is golang basic type -func isSimpleType(val reflect.Value, kind reflect.Kind, pointers **pointerInfo, interfaces *[]reflect.Value) bool { - switch kind { - case reflect.Bool: - return true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return true - case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64: - return true - case reflect.Float32, reflect.Float64: - return true - case reflect.Complex64, reflect.Complex128: - return true - case reflect.String: - return true - case reflect.Chan: - return true - case reflect.Invalid: - return true - case reflect.Interface: - for _, in := range *interfaces { - if reflect.DeepEqual(in, val) { - return true - } - } - return false - case reflect.UnsafePointer: - if val.IsNil() { - return true - } - - var elem = val.Elem() - - if isSimpleType(elem, elem.Kind(), pointers, interfaces) { - return true - } - - var addr = val.Elem().UnsafeAddr() - - for p := *pointers; p != nil; p = p.prev { - if addr == p.addr { - return true - } - } - - return false - } - - return false -} - -// dump value -func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, interfaces *[]reflect.Value, structFilter func(string, string) bool, formatOutput bool, indent string, level int) { - var t = val.Kind() - - switch t { - case reflect.Bool: - fmt.Fprint(buf, val.Bool()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - fmt.Fprint(buf, val.Int()) - case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64: - fmt.Fprint(buf, val.Uint()) - case reflect.Float32, reflect.Float64: - fmt.Fprint(buf, val.Float()) - case reflect.Complex64, reflect.Complex128: - fmt.Fprint(buf, val.Complex()) - case reflect.UnsafePointer: - fmt.Fprintf(buf, "unsafe.Pointer(0x%X)", val.Pointer()) - case reflect.Ptr: - if val.IsNil() { - fmt.Fprint(buf, "nil") - return - } - - var addr = val.Elem().UnsafeAddr() - - for p := *pointers; p != nil; p = p.prev { - if addr == p.addr { - p.used = append(p.used, buf.Len()) - fmt.Fprintf(buf, "0x%X", addr) - return - } - } - - *pointers = &pointerInfo{ - prev: *pointers, - addr: addr, - pos: buf.Len(), - used: make([]int, 0), - } - - fmt.Fprint(buf, "&") - - printKeyValue(buf, val.Elem(), pointers, interfaces, structFilter, formatOutput, indent, level) - case reflect.String: - fmt.Fprint(buf, "\"", val.String(), "\"") - case reflect.Interface: - var value = val.Elem() - - if !value.IsValid() { - fmt.Fprint(buf, "nil") - } else { - for _, in := range *interfaces { - if reflect.DeepEqual(in, val) { - fmt.Fprint(buf, "repeat") - return - } - } - - *interfaces = append(*interfaces, val) - - printKeyValue(buf, value, pointers, interfaces, structFilter, formatOutput, indent, level+1) - } - case reflect.Struct: - var t = val.Type() - - fmt.Fprint(buf, t) - fmt.Fprint(buf, "{") - - for i := 0; i < val.NumField(); i++ { - if formatOutput { - fmt.Fprintln(buf) - } else { - fmt.Fprint(buf, " ") - } - - var name = t.Field(i).Name - - if formatOutput { - for ind := 0; ind < level; ind++ { - fmt.Fprint(buf, indent) - } - } - - fmt.Fprint(buf, name) - fmt.Fprint(buf, ": ") - - if structFilter != nil && structFilter(t.String(), name) { - fmt.Fprint(buf, "ignore") - } else { - printKeyValue(buf, val.Field(i), pointers, interfaces, structFilter, formatOutput, indent, level+1) - } - - fmt.Fprint(buf, ",") - } - - if formatOutput { - fmt.Fprintln(buf) - - for ind := 0; ind < level-1; ind++ { - fmt.Fprint(buf, indent) - } - } else { - fmt.Fprint(buf, " ") - } - - fmt.Fprint(buf, "}") - case reflect.Array, reflect.Slice: - fmt.Fprint(buf, val.Type()) - fmt.Fprint(buf, "{") - - var allSimple = true - - for i := 0; i < val.Len(); i++ { - var elem = val.Index(i) - - var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces) - - if !isSimple { - allSimple = false - } - - if formatOutput && !isSimple { - fmt.Fprintln(buf) - } else { - fmt.Fprint(buf, " ") - } - - if formatOutput && !isSimple { - for ind := 0; ind < level; ind++ { - fmt.Fprint(buf, indent) - } - } - - printKeyValue(buf, elem, pointers, interfaces, structFilter, formatOutput, indent, level+1) - - if i != val.Len()-1 || !allSimple { - fmt.Fprint(buf, ",") - } - } - - if formatOutput && !allSimple { - fmt.Fprintln(buf) - - for ind := 0; ind < level-1; ind++ { - fmt.Fprint(buf, indent) - } - } else { - fmt.Fprint(buf, " ") - } - - fmt.Fprint(buf, "}") - case reflect.Map: - var t = val.Type() - var keys = val.MapKeys() - - fmt.Fprint(buf, t) - fmt.Fprint(buf, "{") - - var allSimple = true - - for i := 0; i < len(keys); i++ { - var elem = val.MapIndex(keys[i]) - - var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces) - - if !isSimple { - allSimple = false - } - - if formatOutput && !isSimple { - fmt.Fprintln(buf) - } else { - fmt.Fprint(buf, " ") - } - - if formatOutput && !isSimple { - for ind := 0; ind <= level; ind++ { - fmt.Fprint(buf, indent) - } - } - - printKeyValue(buf, keys[i], pointers, interfaces, structFilter, formatOutput, indent, level+1) - fmt.Fprint(buf, ": ") - printKeyValue(buf, elem, pointers, interfaces, structFilter, formatOutput, indent, level+1) - - if i != val.Len()-1 || !allSimple { - fmt.Fprint(buf, ",") - } - } - - if formatOutput && !allSimple { - fmt.Fprintln(buf) - - for ind := 0; ind < level-1; ind++ { - fmt.Fprint(buf, indent) - } - } else { - fmt.Fprint(buf, " ") - } - - fmt.Fprint(buf, "}") - case reflect.Chan: - fmt.Fprint(buf, val.Type()) - case reflect.Invalid: - fmt.Fprint(buf, "invalid") - default: - fmt.Fprint(buf, "unknow") - } -} - -// PrintPointerInfo dump pointer value -func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) { - var anyused = false - var pointerNum = 0 - - for p := pointers; p != nil; p = p.prev { - if len(p.used) > 0 { - anyused = true - } - pointerNum++ - p.n = pointerNum - } - - if anyused { - var pointerBufs = make([][]rune, pointerNum+1) - - for i := 0; i < len(pointerBufs); i++ { - var pointerBuf = make([]rune, buf.Len()+headlen) - - for j := 0; j < len(pointerBuf); j++ { - pointerBuf[j] = ' ' - } - - pointerBufs[i] = pointerBuf - } - - for pn := 0; pn <= pointerNum; pn++ { - for p := pointers; p != nil; p = p.prev { - if len(p.used) > 0 && p.n >= pn { - if pn == p.n { - pointerBufs[pn][p.pos+headlen] = '└' - - var maxpos = 0 - - for i, pos := range p.used { - if i < len(p.used)-1 { - pointerBufs[pn][pos+headlen] = '┴' - } else { - pointerBufs[pn][pos+headlen] = '┘' - } - - maxpos = pos - } - - for i := 0; i < maxpos-p.pos-1; i++ { - if pointerBufs[pn][i+p.pos+headlen+1] == ' ' { - pointerBufs[pn][i+p.pos+headlen+1] = '─' - } - } - } else { - pointerBufs[pn][p.pos+headlen] = '│' - - for _, pos := range p.used { - if pointerBufs[pn][pos+headlen] == ' ' { - pointerBufs[pn][pos+headlen] = '│' - } else { - pointerBufs[pn][pos+headlen] = '┼' - } - } - } - } - } - - buf.WriteString(string(pointerBufs[pn]) + "\n") - } - } -} - -// Stack get stack bytes -func Stack(skip int, indent string) []byte { - var buf = new(bytes.Buffer) - - for i := skip; ; i++ { - var pc, file, line, ok = runtime.Caller(i) - - if !ok { - break - } - - buf.WriteString(indent) - - fmt.Fprintf(buf, "at %s() [%s:%d]\n", function(pc), file, line) - } - - return buf.Bytes() -} - -// return the name of the function containing the PC if possible, -func function(pc uintptr) []byte { - fn := runtime.FuncForPC(pc) - if fn == nil { - return dunno - } - name := []byte(fn.Name()) - // The name includes the path name to the package, which is unnecessary - // since the file name is already included. Plus, it has center dots. - // That is, we see - // runtime/debug.*T·ptrmethod - // and want - // *T.ptrmethod - if period := bytes.Index(name, dot); period >= 0 { - name = name[period+1:] - } - name = bytes.Replace(name, centerDot, dot, -1) - return name -} diff --git a/vendor/github.com/astaxie/beego/utils/file.go b/vendor/github.com/astaxie/beego/utils/file.go deleted file mode 100644 index 6090eb17..00000000 --- a/vendor/github.com/astaxie/beego/utils/file.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "bufio" - "errors" - "io" - "os" - "path/filepath" - "regexp" -) - -// SelfPath gets compiled executable file absolute path -func SelfPath() string { - path, _ := filepath.Abs(os.Args[0]) - return path -} - -// SelfDir gets compiled executable file directory -func SelfDir() string { - return filepath.Dir(SelfPath()) -} - -// FileExists reports whether the named file or directory exists. -func FileExists(name string) bool { - if _, err := os.Stat(name); err != nil { - if os.IsNotExist(err) { - return false - } - } - return true -} - -// SearchFile Search a file in paths. -// this is often used in search config file in /etc ~/ -func SearchFile(filename string, paths ...string) (fullpath string, err error) { - for _, path := range paths { - if fullpath = filepath.Join(path, filename); FileExists(fullpath) { - return - } - } - err = errors.New(fullpath + " not found in paths") - return -} - -// GrepFile like command grep -E -// for example: GrepFile(`^hello`, "hello.txt") -// \n is striped while read -func GrepFile(patten string, filename string) (lines []string, err error) { - re, err := regexp.Compile(patten) - if err != nil { - return - } - - fd, err := os.Open(filename) - if err != nil { - return - } - lines = make([]string, 0) - reader := bufio.NewReader(fd) - prefix := "" - var isLongLine bool - for { - byteLine, isPrefix, er := reader.ReadLine() - if er != nil && er != io.EOF { - return nil, er - } - if er == io.EOF { - break - } - line := string(byteLine) - if isPrefix { - prefix += line - continue - } else { - isLongLine = true - } - - line = prefix + line - if isLongLine { - prefix = "" - } - if re.MatchString(line) { - lines = append(lines, line) - } - } - return lines, nil -} diff --git a/vendor/github.com/astaxie/beego/utils/mail.go b/vendor/github.com/astaxie/beego/utils/mail.go deleted file mode 100644 index 80a366ca..00000000 --- a/vendor/github.com/astaxie/beego/utils/mail.go +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/mail" - "net/smtp" - "net/textproto" - "os" - "path" - "path/filepath" - "strconv" - "strings" - "sync" -) - -const ( - maxLineLength = 76 - - upperhex = "0123456789ABCDEF" -) - -// Email is the type used for email messages -type Email struct { - Auth smtp.Auth - Identity string `json:"identity"` - Username string `json:"username"` - Password string `json:"password"` - Host string `json:"host"` - Port int `json:"port"` - From string `json:"from"` - To []string - Bcc []string - Cc []string - Subject string - Text string // Plaintext message (optional) - HTML string // Html message (optional) - Headers textproto.MIMEHeader - Attachments []*Attachment - ReadReceipt []string -} - -// Attachment is a struct representing an email attachment. -// Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question -type Attachment struct { - Filename string - Header textproto.MIMEHeader - Content []byte -} - -// NewEMail create new Email struct with config json. -// config json is followed from Email struct fields. -func NewEMail(config string) *Email { - e := new(Email) - e.Headers = textproto.MIMEHeader{} - err := json.Unmarshal([]byte(config), e) - if err != nil { - return nil - } - return e -} - -// Bytes Make all send information to byte -func (e *Email) Bytes() ([]byte, error) { - buff := &bytes.Buffer{} - w := multipart.NewWriter(buff) - // Set the appropriate headers (overwriting any conflicts) - // Leave out Bcc (only included in envelope headers) - e.Headers.Set("To", strings.Join(e.To, ",")) - if e.Cc != nil { - e.Headers.Set("Cc", strings.Join(e.Cc, ",")) - } - e.Headers.Set("From", e.From) - e.Headers.Set("Subject", e.Subject) - if len(e.ReadReceipt) != 0 { - e.Headers.Set("Disposition-Notification-To", strings.Join(e.ReadReceipt, ",")) - } - e.Headers.Set("MIME-Version", "1.0") - - // Write the envelope headers (including any custom headers) - if err := headerToBytes(buff, e.Headers); err != nil { - return nil, fmt.Errorf("Failed to render message headers: %s", err) - } - - e.Headers.Set("Content-Type", fmt.Sprintf("multipart/mixed;\r\n boundary=%s\r\n", w.Boundary())) - fmt.Fprintf(buff, "%s:", "Content-Type") - fmt.Fprintf(buff, " %s\r\n", fmt.Sprintf("multipart/mixed;\r\n boundary=%s\r\n", w.Boundary())) - - // Start the multipart/mixed part - fmt.Fprintf(buff, "--%s\r\n", w.Boundary()) - header := textproto.MIMEHeader{} - // Check to see if there is a Text or HTML field - if e.Text != "" || e.HTML != "" { - subWriter := multipart.NewWriter(buff) - // Create the multipart alternative part - header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary())) - // Write the header - if err := headerToBytes(buff, header); err != nil { - return nil, fmt.Errorf("Failed to render multipart message headers: %s", err) - } - // Create the body sections - if e.Text != "" { - header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8")) - header.Set("Content-Transfer-Encoding", "quoted-printable") - if _, err := subWriter.CreatePart(header); err != nil { - return nil, err - } - // Write the text - if err := quotePrintEncode(buff, e.Text); err != nil { - return nil, err - } - } - if e.HTML != "" { - header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8")) - header.Set("Content-Transfer-Encoding", "quoted-printable") - if _, err := subWriter.CreatePart(header); err != nil { - return nil, err - } - // Write the text - if err := quotePrintEncode(buff, e.HTML); err != nil { - return nil, err - } - } - if err := subWriter.Close(); err != nil { - return nil, err - } - } - // Create attachment part, if necessary - for _, a := range e.Attachments { - ap, err := w.CreatePart(a.Header) - if err != nil { - return nil, err - } - // Write the base64Wrapped content to the part - base64Wrap(ap, a.Content) - } - if err := w.Close(); err != nil { - return nil, err - } - return buff.Bytes(), nil -} - -// AttachFile Add attach file to the send mail -func (e *Email) AttachFile(args ...string) (a *Attachment, err error) { - if len(args) < 1 || len(args) > 2 { // change && to || - err = errors.New("Must specify a file name and number of parameters can not exceed at least two") - return - } - filename := args[0] - id := "" - if len(args) > 1 { - id = args[1] - } - f, err := os.Open(filename) - if err != nil { - return - } - defer f.Close() - ct := mime.TypeByExtension(filepath.Ext(filename)) - basename := path.Base(filename) - return e.Attach(f, basename, ct, id) -} - -// Attach is used to attach content from an io.Reader to the email. -// Parameters include an io.Reader, the desired filename for the attachment, and the Content-Type. -func (e *Email) Attach(r io.Reader, filename string, args ...string) (a *Attachment, err error) { - if len(args) < 1 || len(args) > 2 { // change && to || - err = errors.New("Must specify the file type and number of parameters can not exceed at least two") - return - } - c := args[0] //Content-Type - id := "" - if len(args) > 1 { - id = args[1] //Content-ID - } - var buffer bytes.Buffer - if _, err = io.Copy(&buffer, r); err != nil { - return - } - at := &Attachment{ - Filename: filename, - Header: textproto.MIMEHeader{}, - Content: buffer.Bytes(), - } - // Get the Content-Type to be used in the MIMEHeader - if c != "" { - at.Header.Set("Content-Type", c) - } else { - // If the Content-Type is blank, set the Content-Type to "application/octet-stream" - at.Header.Set("Content-Type", "application/octet-stream") - } - if id != "" { - at.Header.Set("Content-Disposition", fmt.Sprintf("inline;\r\n filename=\"%s\"", filename)) - at.Header.Set("Content-ID", fmt.Sprintf("<%s>", id)) - } else { - at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename)) - } - at.Header.Set("Content-Transfer-Encoding", "base64") - e.Attachments = append(e.Attachments, at) - return at, nil -} - -// Send will send out the mail -func (e *Email) Send() error { - if e.Auth == nil { - e.Auth = smtp.PlainAuth(e.Identity, e.Username, e.Password, e.Host) - } - // Merge the To, Cc, and Bcc fields - to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc)) - to = append(append(append(to, e.To...), e.Cc...), e.Bcc...) - // Check to make sure there is at least one recipient and one "From" address - if len(to) == 0 { - return errors.New("Must specify at least one To address") - } - - // Use the username if no From is provided - if len(e.From) == 0 { - e.From = e.Username - } - - from, err := mail.ParseAddress(e.From) - if err != nil { - return err - } - - // use mail's RFC 2047 to encode any string - e.Subject = qEncode("utf-8", e.Subject) - - raw, err := e.Bytes() - if err != nil { - return err - } - return smtp.SendMail(e.Host+":"+strconv.Itoa(e.Port), e.Auth, from.Address, to, raw) -} - -// quotePrintEncode writes the quoted-printable text to the IO Writer (according to RFC 2045) -func quotePrintEncode(w io.Writer, s string) error { - var buf [3]byte - mc := 0 - for i := 0; i < len(s); i++ { - c := s[i] - // We're assuming Unix style text formats as input (LF line break), and - // quoted-printble uses CRLF line breaks. (Literal CRs will become - // "=0D", but probably shouldn't be there to begin with!) - if c == '\n' { - io.WriteString(w, "\r\n") - mc = 0 - continue - } - - var nextOut []byte - if isPrintable(c) { - nextOut = append(buf[:0], c) - } else { - nextOut = buf[:] - qpEscape(nextOut, c) - } - - // Add a soft line break if the next (encoded) byte would push this line - // to or past the limit. - if mc+len(nextOut) >= maxLineLength { - if _, err := io.WriteString(w, "=\r\n"); err != nil { - return err - } - mc = 0 - } - - if _, err := w.Write(nextOut); err != nil { - return err - } - mc += len(nextOut) - } - // No trailing end-of-line?? Soft line break, then. TODO: is this sane? - if mc > 0 { - io.WriteString(w, "=\r\n") - } - return nil -} - -// isPrintable returns true if the rune given is "printable" according to RFC 2045, false otherwise -func isPrintable(c byte) bool { - return (c >= '!' && c <= '<') || (c >= '>' && c <= '~') || (c == ' ' || c == '\n' || c == '\t') -} - -// qpEscape is a helper function for quotePrintEncode which escapes a -// non-printable byte. Expects len(dest) == 3. -func qpEscape(dest []byte, c byte) { - const nums = "0123456789ABCDEF" - dest[0] = '=' - dest[1] = nums[(c&0xf0)>>4] - dest[2] = nums[(c & 0xf)] -} - -// headerToBytes enumerates the key and values in the header, and writes the results to the IO Writer -func headerToBytes(w io.Writer, t textproto.MIMEHeader) error { - for k, v := range t { - // Write the header key - _, err := fmt.Fprintf(w, "%s:", k) - if err != nil { - return err - } - // Write each value in the header - for _, c := range v { - _, err := fmt.Fprintf(w, " %s\r\n", c) - if err != nil { - return err - } - } - } - return nil -} - -// base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars) -// The output is then written to the specified io.Writer -func base64Wrap(w io.Writer, b []byte) { - // 57 raw bytes per 76-byte base64 line. - const maxRaw = 57 - // Buffer for each line, including trailing CRLF. - var buffer [maxLineLength + len("\r\n")]byte - copy(buffer[maxLineLength:], "\r\n") - // Process raw chunks until there's no longer enough to fill a line. - for len(b) >= maxRaw { - base64.StdEncoding.Encode(buffer[:], b[:maxRaw]) - w.Write(buffer[:]) - b = b[maxRaw:] - } - // Handle the last chunk of bytes. - if len(b) > 0 { - out := buffer[:base64.StdEncoding.EncodedLen(len(b))] - base64.StdEncoding.Encode(out, b) - out = append(out, "\r\n"...) - w.Write(out) - } -} - -// Encode returns the encoded-word form of s. If s is ASCII without special -// characters, it is returned unchanged. The provided charset is the IANA -// charset name of s. It is case insensitive. -// RFC 2047 encoded-word -func qEncode(charset, s string) string { - if !needsEncoding(s) { - return s - } - return encodeWord(charset, s) -} - -func needsEncoding(s string) bool { - for _, b := range s { - if (b < ' ' || b > '~') && b != '\t' { - return true - } - } - return false -} - -// encodeWord encodes a string into an encoded-word. -func encodeWord(charset, s string) string { - buf := getBuffer() - - buf.WriteString("=?") - buf.WriteString(charset) - buf.WriteByte('?') - buf.WriteByte('q') - buf.WriteByte('?') - - enc := make([]byte, 3) - for i := 0; i < len(s); i++ { - b := s[i] - switch { - case b == ' ': - buf.WriteByte('_') - case b <= '~' && b >= '!' && b != '=' && b != '?' && b != '_': - buf.WriteByte(b) - default: - enc[0] = '=' - enc[1] = upperhex[b>>4] - enc[2] = upperhex[b&0x0f] - buf.Write(enc) - } - } - buf.WriteString("?=") - - es := buf.String() - putBuffer(buf) - return es -} - -var bufPool = sync.Pool{ - New: func() interface{} { - return new(bytes.Buffer) - }, -} - -func getBuffer() *bytes.Buffer { - return bufPool.Get().(*bytes.Buffer) -} - -func putBuffer(buf *bytes.Buffer) { - if buf.Len() > 1024 { - return - } - buf.Reset() - bufPool.Put(buf) -} diff --git a/vendor/github.com/astaxie/beego/utils/rand.go b/vendor/github.com/astaxie/beego/utils/rand.go deleted file mode 100644 index 344d1cd5..00000000 --- a/vendor/github.com/astaxie/beego/utils/rand.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "crypto/rand" - r "math/rand" - "time" -) - -var alphaNum = []byte(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`) - -// RandomCreateBytes generate random []byte by specify chars. -func RandomCreateBytes(n int, alphabets ...byte) []byte { - if len(alphabets) == 0 { - alphabets = alphaNum - } - var bytes = make([]byte, n) - var randBy bool - if num, err := rand.Read(bytes); num != n || err != nil { - r.Seed(time.Now().UnixNano()) - randBy = true - } - for i, b := range bytes { - if randBy { - bytes[i] = alphabets[r.Intn(len(alphabets))] - } else { - bytes[i] = alphabets[b%byte(len(alphabets))] - } - } - return bytes -} diff --git a/vendor/github.com/astaxie/beego/utils/safemap.go b/vendor/github.com/astaxie/beego/utils/safemap.go deleted file mode 100644 index 1793030a..00000000 --- a/vendor/github.com/astaxie/beego/utils/safemap.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "sync" -) - -// BeeMap is a map with lock -type BeeMap struct { - lock *sync.RWMutex - bm map[interface{}]interface{} -} - -// NewBeeMap return new safemap -func NewBeeMap() *BeeMap { - return &BeeMap{ - lock: new(sync.RWMutex), - bm: make(map[interface{}]interface{}), - } -} - -// Get from maps return the k's value -func (m *BeeMap) Get(k interface{}) interface{} { - m.lock.RLock() - defer m.lock.RUnlock() - if val, ok := m.bm[k]; ok { - return val - } - return nil -} - -// Set Maps the given key and value. Returns false -// if the key is already in the map and changes nothing. -func (m *BeeMap) Set(k interface{}, v interface{}) bool { - m.lock.Lock() - defer m.lock.Unlock() - if val, ok := m.bm[k]; !ok { - m.bm[k] = v - } else if val != v { - m.bm[k] = v - } else { - return false - } - return true -} - -// Check Returns true if k is exist in the map. -func (m *BeeMap) Check(k interface{}) bool { - m.lock.RLock() - defer m.lock.RUnlock() - _, ok := m.bm[k] - return ok -} - -// Delete the given key and value. -func (m *BeeMap) Delete(k interface{}) { - m.lock.Lock() - defer m.lock.Unlock() - delete(m.bm, k) -} - -// Items returns all items in safemap. -func (m *BeeMap) Items() map[interface{}]interface{} { - m.lock.RLock() - defer m.lock.RUnlock() - r := make(map[interface{}]interface{}) - for k, v := range m.bm { - r[k] = v - } - return r -} - -// Count returns the number of items within the map. -func (m *BeeMap) Count() int { - m.lock.RLock() - defer m.lock.RUnlock() - return len(m.bm) -} diff --git a/vendor/github.com/astaxie/beego/utils/slice.go b/vendor/github.com/astaxie/beego/utils/slice.go deleted file mode 100644 index 8f2cef98..00000000 --- a/vendor/github.com/astaxie/beego/utils/slice.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2014 beego Author. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "math/rand" - "time" -) - -type reducetype func(interface{}) interface{} -type filtertype func(interface{}) bool - -// InSlice checks given string in string slice or not. -func InSlice(v string, sl []string) bool { - for _, vv := range sl { - if vv == v { - return true - } - } - return false -} - -// InSliceIface checks given interface in interface slice. -func InSliceIface(v interface{}, sl []interface{}) bool { - for _, vv := range sl { - if vv == v { - return true - } - } - return false -} - -// SliceRandList generate an int slice from min to max. -func SliceRandList(min, max int) []int { - if max < min { - min, max = max, min - } - length := max - min + 1 - t0 := time.Now() - rand.Seed(int64(t0.Nanosecond())) - list := rand.Perm(length) - for index := range list { - list[index] += min - } - return list -} - -// SliceMerge merges interface slices to one slice. -func SliceMerge(slice1, slice2 []interface{}) (c []interface{}) { - c = append(slice1, slice2...) - return -} - -// SliceReduce generates a new slice after parsing every value by reduce function -func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{}) { - for _, v := range slice { - dslice = append(dslice, a(v)) - } - return -} - -// SliceRand returns random one from slice. -func SliceRand(a []interface{}) (b interface{}) { - randnum := rand.Intn(len(a)) - b = a[randnum] - return -} - -// SliceSum sums all values in int64 slice. -func SliceSum(intslice []int64) (sum int64) { - for _, v := range intslice { - sum += v - } - return -} - -// SliceFilter generates a new slice after filter function. -func SliceFilter(slice []interface{}, a filtertype) (ftslice []interface{}) { - for _, v := range slice { - if a(v) { - ftslice = append(ftslice, v) - } - } - return -} - -// SliceDiff returns diff slice of slice1 - slice2. -func SliceDiff(slice1, slice2 []interface{}) (diffslice []interface{}) { - for _, v := range slice1 { - if !InSliceIface(v, slice2) { - diffslice = append(diffslice, v) - } - } - return -} - -// SliceIntersect returns slice that are present in all the slice1 and slice2. -func SliceIntersect(slice1, slice2 []interface{}) (diffslice []interface{}) { - for _, v := range slice1 { - if InSliceIface(v, slice2) { - diffslice = append(diffslice, v) - } - } - return -} - -// SliceChunk separates one slice to some sized slice. -func SliceChunk(slice []interface{}, size int) (chunkslice [][]interface{}) { - if size >= len(slice) { - chunkslice = append(chunkslice, slice) - return - } - end := size - for i := 0; i <= (len(slice) - size); i += size { - chunkslice = append(chunkslice, slice[i:end]) - end += size - } - return -} - -// SliceRange generates a new slice from begin to end with step duration of int64 number. -func SliceRange(start, end, step int64) (intslice []int64) { - for i := start; i <= end; i += step { - intslice = append(intslice, i) - } - return -} - -// SlicePad prepends size number of val into slice. -func SlicePad(slice []interface{}, size int, val interface{}) []interface{} { - if size <= len(slice) { - return slice - } - for i := 0; i < (size - len(slice)); i++ { - slice = append(slice, val) - } - return slice -} - -// SliceUnique cleans repeated values in slice. -func SliceUnique(slice []interface{}) (uniqueslice []interface{}) { - for _, v := range slice { - if !InSliceIface(v, uniqueslice) { - uniqueslice = append(uniqueslice, v) - } - } - return -} - -// SliceShuffle shuffles a slice. -func SliceShuffle(slice []interface{}) []interface{} { - for i := 0; i < len(slice); i++ { - a := rand.Intn(len(slice)) - b := rand.Intn(len(slice)) - slice[a], slice[b] = slice[b], slice[a] - } - return slice -} diff --git a/vendor/github.com/astaxie/beego/utils/utils.go b/vendor/github.com/astaxie/beego/utils/utils.go deleted file mode 100644 index 3874b803..00000000 --- a/vendor/github.com/astaxie/beego/utils/utils.go +++ /dev/null @@ -1,89 +0,0 @@ -package utils - -import ( - "os" - "path/filepath" - "regexp" - "runtime" - "strconv" - "strings" -) - -// GetGOPATHs returns all paths in GOPATH variable. -func GetGOPATHs() []string { - gopath := os.Getenv("GOPATH") - if gopath == "" && compareGoVersion(runtime.Version(), "go1.8") >= 0 { - gopath = defaultGOPATH() - } - return filepath.SplitList(gopath) -} - -func compareGoVersion(a, b string) int { - reg := regexp.MustCompile("^\\d*") - - a = strings.TrimPrefix(a, "go") - b = strings.TrimPrefix(b, "go") - - versionsA := strings.Split(a, ".") - versionsB := strings.Split(b, ".") - - for i := 0; i < len(versionsA) && i < len(versionsB); i++ { - versionA := versionsA[i] - versionB := versionsB[i] - - vA, err := strconv.Atoi(versionA) - if err != nil { - str := reg.FindString(versionA) - if str != "" { - vA, _ = strconv.Atoi(str) - } else { - vA = -1 - } - } - - vB, err := strconv.Atoi(versionB) - if err != nil { - str := reg.FindString(versionB) - if str != "" { - vB, _ = strconv.Atoi(str) - } else { - vB = -1 - } - } - - if vA > vB { - // vA = 12, vB = 8 - return 1 - } else if vA < vB { - // vA = 6, vB = 8 - return -1 - } else if vA == -1 { - // vA = rc1, vB = rc3 - return strings.Compare(versionA, versionB) - } - - // vA = vB = 8 - continue - } - - if len(versionsA) > len(versionsB) { - return 1 - } else if len(versionsA) == len(versionsB) { - return 0 - } - - return -1 -} - -func defaultGOPATH() string { - env := "HOME" - if runtime.GOOS == "windows" { - env = "USERPROFILE" - } else if runtime.GOOS == "plan9" { - env = "home" - } - if home := os.Getenv(env); home != "" { - return filepath.Join(home, "go") - } - return "" -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/LICENSE b/vendor/github.com/baidubce/bce-sdk-go/LICENSE deleted file mode 100644 index f433b1a5..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/LICENSE +++ /dev/null @@ -1,177 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/vendor/github.com/baidubce/bce-sdk-go/auth/credentials.go b/vendor/github.com/baidubce/bce-sdk-go/auth/credentials.go deleted file mode 100644 index fb1e415f..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/auth/credentials.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// credentials.go - the credentials data structure definition - -// Package auth implements the authorization functionality for BCE. -// It use the BCE access key ID and secret access key with the specific sign algorithm to generate -// the authorization string. It also supports the temporary authorization by the STS token. -package auth - -import "errors" - -// BceCredentials define the data structure for authorization -type BceCredentials struct { - AccessKeyId string // access key id to the service - SecretAccessKey string // secret access key to the service - SessionToken string // session token generate by the STS service -} - -func (b *BceCredentials) String() string { - str := "ak: " + b.AccessKeyId + ", sk: " + b.SecretAccessKey - if len(b.SessionToken) != 0 { - return str + ", sessionToken: " + b.SessionToken - } - return str -} - -func NewBceCredentials(ak, sk string) (*BceCredentials, error) { - if len(ak) == 0 { - return nil, errors.New("accessKeyId should not be empty") - } - if len(sk) == 0 { - return nil, errors.New("secretKey should not be empty") - } - - return &BceCredentials{ak, sk, ""}, nil -} - -func NewSessionBceCredentials(ak, sk, token string) (*BceCredentials, error) { - if len(token) == 0 { - return nil, errors.New("sessionToken should not be empty") - } - - result, err := NewBceCredentials(ak, sk) - if err != nil { - return nil, err - } - result.SessionToken = token - - return result, nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/auth/signer.go b/vendor/github.com/baidubce/bce-sdk-go/auth/signer.go deleted file mode 100644 index 57347980..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/auth/signer.go +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// signer.go - implement the specific sign algorithm of BCE V1 protocol - -package auth - -import ( - "fmt" - "sort" - "strings" - - "github.com/baidubce/bce-sdk-go/http" - "github.com/baidubce/bce-sdk-go/util" - "github.com/baidubce/bce-sdk-go/util/log" -) - -var ( - BCE_AUTH_VERSION = "bce-auth-v1" - SIGN_JOINER = "\n" - SIGN_HEADER_JOINER = ";" - DEFAULT_EXPIRE_SECONDS = 1800 - DEFAULT_HEADERS_TO_SIGN = map[string]struct{}{ - strings.ToLower(http.HOST): {}, - strings.ToLower(http.CONTENT_LENGTH): {}, - strings.ToLower(http.CONTENT_TYPE): {}, - strings.ToLower(http.CONTENT_MD5): {}, - } -) - -// Signer abstracts the entity that implements the `Sign` method -type Signer interface { - // Sign the given Request with the Credentials and SignOptions - Sign(*http.Request, *BceCredentials, *SignOptions) -} - -// SignOptions defines the data structure used by Signer -type SignOptions struct { - HeadersToSign map[string]struct{} - Timestamp int64 - ExpireSeconds int -} - -func (opt *SignOptions) String() string { - return fmt.Sprintf(`SignOptions [ - HeadersToSign=%s; - Timestamp=%d; - ExpireSeconds=%d - ]`, opt.HeadersToSign, opt.Timestamp, opt.ExpireSeconds) -} - -// BceV1Signer implements the v1 sign algorithm -type BceV1Signer struct{} - -// Sign - generate the authorization string from the BceCredentials and SignOptions -// -// PARAMS: -// - req: *http.Request for this sign -// - cred: *BceCredentials to access the serice -// - opt: *SignOptions for this sign algorithm -func (b *BceV1Signer) Sign(req *http.Request, cred *BceCredentials, opt *SignOptions) { - if req == nil { - log.Fatal("request should not be null for sign") - return - } - if cred == nil { - log.Fatal("credentials should not be null for sign") - return - } - - // Prepare parameters - accessKeyId := cred.AccessKeyId - secretAccessKey := cred.SecretAccessKey - signDate := util.FormatISO8601Date(util.NowUTCSeconds()) - // Modify the sign time if it is not the default value but specified by client - if opt.Timestamp != 0 { - signDate = util.FormatISO8601Date(opt.Timestamp) - } - - // Set security token if using session credentials - if len(cred.SessionToken) != 0 { - req.SetHeader(http.BCE_SECURITY_TOKEN, cred.SessionToken) - } - - // Prepare the canonical request components - signKeyInfo := fmt.Sprintf("%s/%s/%s/%d", - BCE_AUTH_VERSION, - accessKeyId, - signDate, - opt.ExpireSeconds) - signKey := util.HmacSha256Hex(secretAccessKey, signKeyInfo) - canonicalUri := getCanonicalURIPath(req.Uri()) - canonicalQueryString := getCanonicalQueryString(req.Params()) - canonicalHeaders, signedHeadersArr := getCanonicalHeaders(req.Headers(), opt.HeadersToSign) - - // Generate signed headers string - signedHeaders := "" - if len(signedHeadersArr) > 0 { - sort.Strings(signedHeadersArr) - signedHeaders = strings.Join(signedHeadersArr, SIGN_HEADER_JOINER) - } - - // Generate signature - canonicalParts := []string{req.Method(), canonicalUri, canonicalQueryString, canonicalHeaders} - canonicalReq := strings.Join(canonicalParts, SIGN_JOINER) - log.Debug("CanonicalRequest data:\n" + canonicalReq) - signature := util.HmacSha256Hex(signKey, canonicalReq) - - // Generate auth string and add to the reqeust header - authStr := signKeyInfo + "/" + signedHeaders + "/" + signature - log.Info("Authorization=" + authStr) - - req.SetHeader(http.AUTHORIZATION, authStr) -} - -func getCanonicalURIPath(path string) string { - if len(path) == 0 { - return "/" - } - canonical_path := path - if strings.HasPrefix(path, "/") { - canonical_path = path[1:] - } - canonical_path = util.UriEncode(canonical_path, false) - return "/" + canonical_path -} - -func getCanonicalQueryString(params map[string]string) string { - if len(params) == 0 { - return "" - } - - result := make([]string, 0, len(params)) - for k, v := range params { - if strings.ToLower(k) == strings.ToLower(http.AUTHORIZATION) { - continue - } - item := "" - if len(v) == 0 { - item = fmt.Sprintf("%s=", util.UriEncode(k, true)) - } else { - item = fmt.Sprintf("%s=%s", util.UriEncode(k, true), util.UriEncode(v, true)) - } - result = append(result, item) - } - sort.Strings(result) - return strings.Join(result, "&") -} - -func getCanonicalHeaders(headers map[string]string, - headersToSign map[string]struct{}) (string, []string) { - canonicalHeaders := make([]string, 0, len(headers)) - signHeaders := make([]string, 0, len(headersToSign)) - for k, v := range headers { - headKey := strings.ToLower(k) - if headKey == strings.ToLower(http.AUTHORIZATION) { - continue - } - _, headExists := headersToSign[headKey] - if headExists || - (strings.HasPrefix(headKey, http.BCE_PREFIX) && - (headKey != http.BCE_REQUEST_ID)) { - - headVal := strings.TrimSpace(v) - encoded := util.UriEncode(headKey, true) + ":" + util.UriEncode(headVal, true) - canonicalHeaders = append(canonicalHeaders, encoded) - signHeaders = append(signHeaders, headKey) - } - } - sort.Strings(canonicalHeaders) - sort.Strings(signHeaders) - return strings.Join(canonicalHeaders, SIGN_JOINER), signHeaders -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/builder.go b/vendor/github.com/baidubce/bce-sdk-go/bce/builder.go deleted file mode 100644 index 1b25504c..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/builder.go +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// builder.go - defines the RequestBuilder structure for BCE servies - -package bce - -import ( - "encoding/json" - "fmt" -) - -// RequestBuilder holds config data for bce request. -// Some of fields are required and the others are optional. -// The builder pattern can simplify the execution of requests. -type RequestBuilder struct { - client Client - - url string // required - method string // required - queryParams map[string]string // optional - headers map[string]string // optional - body interface{} // optional - result interface{} // optional -} - -// create RequestBuilder with the client. -func NewRequestBuilder(client Client) *RequestBuilder { - return &RequestBuilder{ - client: client, - } -} - -func (b *RequestBuilder) WithURL(url string) *RequestBuilder { - b.url = url - return b -} - -func (b *RequestBuilder) WithMethod(method string) *RequestBuilder { - b.method = method - return b -} - -// set query param with the key/value directly. -func (b *RequestBuilder) WithQueryParam(key, value string) *RequestBuilder { - if b.queryParams == nil { - b.queryParams = make(map[string]string) - } - b.queryParams[key] = value - return b -} - -// set query param with the key/value only when the value is not blank. -func (b *RequestBuilder) WithQueryParamFilter(key, value string) *RequestBuilder { - if len(value) == 0 { - return b - } - return b.WithQueryParam(key, value) -} - -func (b *RequestBuilder) WithQueryParams(params map[string]string) *RequestBuilder { - if b.queryParams == nil { - b.queryParams = params - } else { - for key, value := range params { - b.queryParams[key] = value - } - } - return b -} - -func (b *RequestBuilder) WithHeader(key, value string) *RequestBuilder { - if b.headers == nil { - b.headers = make(map[string]string) - } - b.headers[key] = value - return b -} - -func (b *RequestBuilder) WithHeaders(headers map[string]string) *RequestBuilder { - if b.headers == nil { - b.headers = headers - } else { - for key, value := range headers { - b.headers[key] = value - } - } - return b -} - -func (b *RequestBuilder) WithBody(body interface{}) *RequestBuilder { - b.body = body - return b -} - -func (b *RequestBuilder) WithResult(result interface{}) *RequestBuilder { - b.result = result - return b -} - -// Do will send request to bce and get result with the builder's parameters. -func (b *RequestBuilder) Do() error { - if err := b.validate(); err != nil { - return err - } - - // build BceRequest - req, err := b.buildBceRequest() - if err != nil { - return err - } - - // get result from BceResponse - if err := b.buildBceResponse(req); err != nil { - return err - } - - return nil -} - -// Validate if the required fields are providered. -func (b *RequestBuilder) validate() error { - if len(b.url) == 0 { - return fmt.Errorf("The url can't be null.") - } - if len(b.method) == 0 { - return fmt.Errorf("The method can't be null.") - } - if b.client == nil { - return fmt.Errorf("The client can't be null.") - } - return nil -} - -func (b *RequestBuilder) buildBceRequest() (*BceRequest, error) { - // Build the request - req := &BceRequest{} - req.SetUri(b.url) - req.SetMethod(b.method) - - if b.headers != nil { - req.SetHeaders(b.headers) - } - if b.queryParams != nil { - req.SetParams(b.queryParams) - } - if b.body != nil { - bodyBytes, err := json.Marshal(b.body) - if err != nil { - return nil, err - } - body, err := NewBodyFromBytes(bodyBytes) - if err != nil { - return nil, err - } - req.SetBody(body) - } - - return req, nil -} - -func (b *RequestBuilder) buildBceResponse(req *BceRequest) error { - // Send request and get response - resp := &BceResponse{} - if err := b.client.SendRequest(req, resp); err != nil { - return err - } - if resp.IsFail() { - return resp.ServiceError() - } - defer resp.Body().Close() - - if b.result == nil { - return nil - } - - return resp.ParseJsonBody(b.result) -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/client.go b/vendor/github.com/baidubce/bce-sdk-go/bce/client.go deleted file mode 100644 index 1600920b..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/client.go +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// client.go - definiton the BceClientConfiguration and BceClient structure - -// Package bce implements the infrastructure to access BCE services. -// -// - BceClient: -// It is the general client of BCE to access all services. It builds http request to access the -// services based on the given client configuration. -// -// - BceClientConfiguration: -// The client configuration data structure which contains endpoint, region, credentials, retry -// policy, sign options and so on. It supports most of the default value and user can also -// access or change the default with its public fields' name. -// -// - Error types: -// The error types when making request or receiving response to the BCE services contains two -// types: the BceClientError when making request to BCE services and the BceServiceError when -// recieving response from them. -// -// - BceRequest: -// The request instance stands for an request to access the BCE services. -// -// - BceResponse: -// The response instance stands for an response from the BCE services. -package bce - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "time" - - "github.com/baidubce/bce-sdk-go/auth" - "github.com/baidubce/bce-sdk-go/http" - "github.com/baidubce/bce-sdk-go/util" - "github.com/baidubce/bce-sdk-go/util/log" -) - -// Client is the general interface which can perform sending request. Different service -// will define its own client in case of specific extension. -type Client interface { - SendRequest(*BceRequest, *BceResponse) error - SendRequestFromBytes(*BceRequest, *BceResponse, []byte) error - GetBceClientConfig() *BceClientConfiguration -} - -// BceClient defines the general client to access the BCE services. -type BceClient struct { - Config *BceClientConfiguration - Signer auth.Signer // the sign algorithm -} - -// BuildHttpRequest - the helper method for the client to build http request -// -// PARAMS: -// - request: the input request object to be built -func (c *BceClient) buildHttpRequest(request *BceRequest) { - // Construct the http request instance for the special fields - request.BuildHttpRequest() - - // Set the client specific configurations - if request.Endpoint() == "" { - request.SetEndpoint(c.Config.Endpoint) - } - if request.Protocol() == "" { - request.SetProtocol(DEFAULT_PROTOCOL) - } - if len(c.Config.ProxyUrl) != 0 { - request.SetProxyUrl(c.Config.ProxyUrl) - } - request.SetTimeout(c.Config.ConnectionTimeoutInMillis / 1000) - - // Set the BCE request headers - request.SetHeader(http.HOST, request.Host()) - request.SetHeader(http.USER_AGENT, c.Config.UserAgent) - request.SetHeader(http.BCE_DATE, util.FormatISO8601Date(util.NowUTCSeconds())) - - // Generate the auth string if needed - if c.Config.Credentials != nil { - c.Signer.Sign(&request.Request, c.Config.Credentials, c.Config.SignOption) - } -} - -// SendRequest - the client performs sending the http request with retry policy and receive the -// response from the BCE services. -// -// PARAMS: -// - req: the request object to be sent to the BCE service -// - resp: the response object to receive the content from BCE service -// RETURNS: -// - error: nil if ok otherwise the specific error -func (c *BceClient) SendRequest(req *BceRequest, resp *BceResponse) error { - // Return client error if it is not nil - if req.ClientError() != nil { - return req.ClientError() - } - - // Build the http request and prepare to send - c.buildHttpRequest(req) - log.Infof("send http request: %v", req) - - // Send request with the given retry policy - retries := 0 - if req.Body() != nil { - defer req.Body().Close() // Manually close the ReadCloser body for retry - } - for { - // The request body should be temporarily saved if retry to send the http request - var retryBuf bytes.Buffer - var teeReader io.Reader - if c.Config.Retry.ShouldRetry(nil, 0) && req.Body() != nil { - teeReader = io.TeeReader(req.Body(), &retryBuf) - req.Request.SetBody(ioutil.NopCloser(teeReader)) - } - httpResp, err := http.Execute(&req.Request) - - if err != nil { - if c.Config.Retry.ShouldRetry(err, retries) { - delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) - time.Sleep(delay_in_mills) - } else { - return &BceClientError{ - fmt.Sprintf("execute http request failed! Retried %d times, error: %v", - retries, err)} - } - retries++ - log.Warnf("send request failed: %v, retry for %d time(s)", err, retries) - if req.Body() != nil { - ioutil.ReadAll(teeReader) - req.Request.SetBody(ioutil.NopCloser(&retryBuf)) - } - continue - } - resp.SetHttpResponse(httpResp) - resp.ParseResponse() - - log.Infof("receive http response: status: %s, debugId: %s, requestId: %s, elapsed: %v", - resp.StatusText(), resp.DebugId(), resp.RequestId(), resp.ElapsedTime()) - for k, v := range resp.Headers() { - log.Debugf("%s=%s", k, v) - } - if resp.IsFail() { - err := resp.ServiceError() - if c.Config.Retry.ShouldRetry(err, retries) { - delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) - time.Sleep(delay_in_mills) - } else { - return err - } - retries++ - log.Warnf("send request failed, retry for %d time(s)", retries) - if req.Body() != nil { - ioutil.ReadAll(teeReader) - req.Request.SetBody(ioutil.NopCloser(&retryBuf)) - } - continue - } - return nil - } -} - -// SendRequestFromBytes - the client performs sending the http request with retry policy and receive the -// response from the BCE services. -// -// PARAMS: -// - req: the request object to be sent to the BCE service -// - resp: the response object to receive the content from BCE service -// - content: the content of body -// RETURNS: -// - error: nil if ok otherwise the specific error -func (c *BceClient) SendRequestFromBytes(req *BceRequest, resp *BceResponse, content []byte) error { - // Return client error if it is not nil - if req.ClientError() != nil { - return req.ClientError() - } - // Build the http request and prepare to send - c.buildHttpRequest(req) - log.Infof("send http request: %v", req) - // Send request with the given retry policy - retries := 0 - for { - // The request body should be temporarily saved if retry to send the http request - buf := bytes.NewBuffer(content) - req.Request.SetBody(ioutil.NopCloser(buf)) - defer req.Request.Body().Close() // Manually close the ReadCloser body for retry - httpResp, err := http.Execute(&req.Request) - if err != nil { - if c.Config.Retry.ShouldRetry(err, retries) { - delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) - time.Sleep(delay_in_mills) - } else { - return &BceClientError{ - fmt.Sprintf("execute http request failed! Retried %d times, error: %v", - retries, err)} - } - retries++ - log.Warnf("send request failed: %v, retry for %d time(s)", err, retries) - continue - } - resp.SetHttpResponse(httpResp) - resp.ParseResponse() - log.Infof("receive http response: status: %s, debugId: %s, requestId: %s, elapsed: %v", - resp.StatusText(), resp.DebugId(), resp.RequestId(), resp.ElapsedTime()) - for k, v := range resp.Headers() { - log.Debugf("%s=%s", k, v) - } - if resp.IsFail() { - err := resp.ServiceError() - if c.Config.Retry.ShouldRetry(err, retries) { - delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) - time.Sleep(delay_in_mills) - } else { - return err - } - retries++ - log.Warnf("send request failed, retry for %d time(s)", retries) - continue - } - return nil - } -} - -func (c *BceClient) GetBceClientConfig() *BceClientConfiguration { - return c.Config -} - -func NewBceClient(conf *BceClientConfiguration, sign auth.Signer) *BceClient { - clientConfig := http.ClientConfig{RedirectDisabled: conf.RedirectDisabled} - http.InitClient(clientConfig) - return &BceClient{conf, sign} -} - -func NewBceClientWithAkSk(ak, sk, endPoint string) (*BceClient, error) { - credentials, err := auth.NewBceCredentials(ak, sk) - if err != nil { - return nil, err - } - defaultSignOptions := &auth.SignOptions{ - HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, - ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} - defaultConf := &BceClientConfiguration{ - Endpoint: endPoint, - Region: DEFAULT_REGION, - UserAgent: DEFAULT_USER_AGENT, - Credentials: credentials, - SignOption: defaultSignOptions, - Retry: DEFAULT_RETRY_POLICY, - ConnectionTimeoutInMillis: DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS, - RedirectDisabled: false} - v1Signer := &auth.BceV1Signer{} - - return NewBceClient(defaultConf, v1Signer), nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/config.go b/vendor/github.com/baidubce/bce-sdk-go/bce/config.go deleted file mode 100644 index a940ae9b..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/config.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// config.go - define the client configuration for BCE - -package bce - -import ( - "fmt" - "reflect" - "runtime" - - "github.com/baidubce/bce-sdk-go/auth" -) - -// Constants and default values for the package bce -const ( - SDK_VERSION = "0.9.111" - URI_PREFIX = "/" // now support uri without prefix "v1" so just set root path - DEFAULT_DOMAIN = "baidubce.com" - DEFAULT_PROTOCOL = "http" - DEFAULT_REGION = "bj" - DEFAULT_CONTENT_TYPE = "application/json;charset=utf-8" - DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS = 1200 * 1000 -) - -var ( - DEFAULT_USER_AGENT string - DEFAULT_RETRY_POLICY = NewBackOffRetryPolicy(3, 20000, 300) -) - -func init() { - DEFAULT_USER_AGENT = "bce-sdk-go" - DEFAULT_USER_AGENT += "/" + SDK_VERSION - DEFAULT_USER_AGENT += "/" + runtime.Version() - DEFAULT_USER_AGENT += "/" + runtime.GOOS - DEFAULT_USER_AGENT += "/" + runtime.GOARCH -} - -// BceClientConfiguration defines the config components structure. -type BceClientConfiguration struct { - Endpoint string - ProxyUrl string - Region string - UserAgent string - Credentials *auth.BceCredentials - SignOption *auth.SignOptions - Retry RetryPolicy - ConnectionTimeoutInMillis int - // CnameEnabled should be true when use custom domain as endpoint to visit bos resource - CnameEnabled bool - BackupEndpoint string - RedirectDisabled bool -} - -func (c *BceClientConfiguration) String() string { - return fmt.Sprintf(`BceClientConfiguration [ - Endpoint=%s; - ProxyUrl=%s; - Region=%s; - UserAgent=%s; - Credentials=%v; - SignOption=%v; - RetryPolicy=%v; - ConnectionTimeoutInMillis=%v; - RedirectDisabled=%v - ]`, c.Endpoint, c.ProxyUrl, c.Region, c.UserAgent, c.Credentials, - c.SignOption, reflect.TypeOf(c.Retry).Name(), c.ConnectionTimeoutInMillis, c.RedirectDisabled) -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/error.go b/vendor/github.com/baidubce/bce-sdk-go/bce/error.go deleted file mode 100644 index e6256512..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/error.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// error.go - define the error types for BCE - -package bce - -const ( - EACCESS_DENIED = "AccessDenied" - EINAPPROPRIATE_JSON = "InappropriateJSON" - EINTERNAL_ERROR = "InternalError" - EINVALID_ACCESS_KEY_ID = "InvalidAccessKeyId" - EINVALID_HTTP_AUTH_HEADER = "InvalidHTTPAuthHeader" - EINVALID_HTTP_REQUEST = "InvalidHTTPRequest" - EINVALID_URI = "InvalidURI" - EMALFORMED_JSON = "MalformedJSON" - EINVALID_VERSION = "InvalidVersion" - EOPT_IN_REQUIRED = "OptInRequired" - EPRECONDITION_FAILED = "PreconditionFailed" - EREQUEST_EXPIRED = "RequestExpired" - ESIGNATURE_DOES_NOT_MATCH = "SignatureDoesNotMatch" -) - -// BceError abstracts the error for BCE -type BceError interface { - error -} - -// BceClientError defines the error struct for the client when making request -type BceClientError struct{ Message string } - -func (b *BceClientError) Error() string { return b.Message } - -func NewBceClientError(msg string) *BceClientError { return &BceClientError{msg} } - -// BceServiceError defines the error struct for the BCE service when receiving response -type BceServiceError struct { - Code string - Message string - RequestId string - StatusCode int -} - -func (b *BceServiceError) Error() string { - ret := "[Code: " + b.Code - ret += "; Message: " + b.Message - ret += "; RequestId: " + b.RequestId + "]" - return ret -} - -func NewBceServiceError(code, msg, reqId string, status int) *BceServiceError { - return &BceServiceError{code, msg, reqId, status} -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/request.go b/vendor/github.com/baidubce/bce-sdk-go/bce/request.go deleted file mode 100644 index ca8409e1..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/request.go +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// request.go - defines the BCE servies request - -package bce - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - - "github.com/baidubce/bce-sdk-go/http" - "github.com/baidubce/bce-sdk-go/util" -) - -// Body defines the data structure used in BCE request. -// Every BCE request that sets the body field must set its content-length and content-md5 headers -// to ensure the correctness of the body content forcely, and users can also set the content-sha256 -// header to strengthen the correctness with the "SetHeader" method. -type Body struct { - stream io.ReadCloser - size int64 - contentMD5 string -} - -func (b *Body) Stream() io.ReadCloser { return b.stream } - -func (b *Body) SetStream(stream io.ReadCloser) { b.stream = stream } - -func (b *Body) Size() int64 { return b.size } - -func (b *Body) ContentMD5() string { return b.contentMD5 } - -// NewBodyFromBytes - build a Body object from the byte stream to be used in the http request, it -// calculates the content-md5 of the byte stream and store the size as well as the stream. -// -// PARAMS: -// - stream: byte stream -// RETURNS: -// - *Body: the return Body object -// - error: error if any specific error occurs -func NewBodyFromBytes(stream []byte) (*Body, error) { - buf := bytes.NewBuffer(stream) - size := int64(buf.Len()) - contentMD5, err := util.CalculateContentMD5(buf, size) - if err != nil { - return nil, err - } - buf = bytes.NewBuffer(stream) - return &Body{ioutil.NopCloser(buf), size, contentMD5}, nil -} - -// NewBodyFromString - build a Body object from the string to be used in the http request, it -// calculates the content-md5 of the byte stream and store the size as well as the stream. -// -// PARAMS: -// - str: the input string -// RETURNS: -// - *Body: the return Body object -// - error: error if any specific error occurs -func NewBodyFromString(str string) (*Body, error) { - buf := bytes.NewBufferString(str) - size := int64(len(str)) - contentMD5, err := util.CalculateContentMD5(buf, size) - if err != nil { - return nil, err - } - buf = bytes.NewBufferString(str) - return &Body{ioutil.NopCloser(buf), size, contentMD5}, nil -} - -// NewBodyFromFile - build a Body object from the given file name to be used in the http request, -// it calculates the content-md5 of the byte stream and store the size as well as the stream. -// -// PARAMS: -// - fname: the given file name -// RETURNS: -// - *Body: the return Body object -// - error: error if any specific error occurs -func NewBodyFromFile(fname string) (*Body, error) { - file, err := os.Open(fname) - if err != nil { - return nil, err - } - fileInfo, infoErr := file.Stat() - if infoErr != nil { - return nil, infoErr - } - contentMD5, md5Err := util.CalculateContentMD5(file, fileInfo.Size()) - if md5Err != nil { - return nil, md5Err - } - if _, err = file.Seek(0, 0); err != nil { - return nil, err - } - return &Body{file, fileInfo.Size(), contentMD5}, nil -} - -// NewBodyFromSectionFile - build a Body object from the given file pointer with offset and size. -// It calculates the content-md5 of the given content and store the size as well as the stream. -// -// PARAMS: -// - file: the input file pointer -// - off: offset of current section body -// - size: current section body size -// RETURNS: -// - *Body: the return Body object -// - error: error if any specific error occurs -func NewBodyFromSectionFile(file *os.File, off, size int64) (*Body, error) { - if _, err := file.Seek(off, 0); err != nil { - return nil, err - } - contentMD5, md5Err := util.CalculateContentMD5(file, size) - if md5Err != nil { - return nil, md5Err - } - if _, err := file.Seek(0, 0); err != nil { - return nil, err - } - section := io.NewSectionReader(file, off, size) - return &Body{ioutil.NopCloser(section), size, contentMD5}, nil -} - -// NewBodyFromSizedReader - build a Body object from the given reader with size. -// It calculates the content-md5 of the given content and store the size as well as the stream. -// -// PARAMS: -// - r: the input reader -// - size: the size to be read, -1 is read all -// RETURNS: -// - *Body: the return Body object -// - error: error if any specific error occurs -func NewBodyFromSizedReader(r io.Reader, size int64) (*Body, error) { - var buffer bytes.Buffer - var rlen int64 - var err error - if size >= 0 { - rlen, err = io.CopyN(&buffer, r, size) - } else { - rlen, err = io.Copy(&buffer, r) - } - if err != nil { - return nil, err - } - if rlen != int64(buffer.Len()) { // must be equal - return nil, NewBceClientError("unexpected reader") - } - if size >= 0 { - if rlen < size { - return nil, NewBceClientError("size is great than reader actual size") - } - } - contentMD5, err := util.CalculateContentMD5(bytes.NewBuffer(buffer.Bytes()), rlen) - if err != nil { - return nil, err - } - body := &Body{ - stream: ioutil.NopCloser(&buffer), - size: rlen, - contentMD5: contentMD5, - } - return body, nil -} - -// BceRequest defines the request structure for accessing BCE services -type BceRequest struct { - http.Request - requestId string - clientError *BceClientError -} - -func (b *BceRequest) RequestId() string { return b.requestId } - -func (b *BceRequest) SetRequestId(val string) { b.requestId = val } - -func (b *BceRequest) ClientError() *BceClientError { return b.clientError } - -func (b *BceRequest) SetClientError(err *BceClientError) { b.clientError = err } - -func (b *BceRequest) SetBody(body *Body) { // override SetBody derived from http.Request - b.Request.SetBody(body.Stream()) - b.SetLength(body.Size()) // set field of "net/http.Request.ContentLength" - if body.Size() > 0 { - b.SetHeader(http.CONTENT_MD5, body.ContentMD5()) - b.SetHeader(http.CONTENT_LENGTH, fmt.Sprintf("%d", body.Size())) - } -} - -func (b *BceRequest) BuildHttpRequest() { - // Only need to build the specific `requestId` field for BCE, other fields are same as the - // `http.Request` as well as its methods. - if len(b.requestId) == 0 { - // Construct the request ID with UUID - b.requestId = util.NewRequestId() - } - b.SetHeader(http.BCE_REQUEST_ID, b.requestId) -} - -func (b *BceRequest) String() string { - requestIdStr := "requestId=" + b.requestId - if b.clientError != nil { - return requestIdStr + ", client error: " + b.ClientError().Error() - } - return requestIdStr + "\n" + b.Request.String() -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/response.go b/vendor/github.com/baidubce/bce-sdk-go/bce/response.go deleted file mode 100644 index 94f2ae4b..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/response.go +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// response.go - defines the common BCE services response - -package bce - -import ( - "bytes" - "encoding/json" - "io" - "io/ioutil" - "strings" - "time" - - "github.com/baidubce/bce-sdk-go/http" -) - -// BceResponse defines the response structure for receiving BCE services response. -type BceResponse struct { - statusCode int - statusText string - requestId string - debugId string - response *http.Response - serviceError *BceServiceError -} - -func (r *BceResponse) IsFail() bool { - return r.response.StatusCode() >= 400 -} - -func (r *BceResponse) StatusCode() int { - return r.statusCode -} - -func (r *BceResponse) StatusText() string { - return r.statusText -} - -func (r *BceResponse) RequestId() string { - return r.requestId -} - -func (r *BceResponse) DebugId() string { - return r.debugId -} - -func (r *BceResponse) Header(key string) string { - return r.response.GetHeader(key) -} - -func (r *BceResponse) Headers() map[string]string { - return r.response.GetHeaders() -} - -func (r *BceResponse) Body() io.ReadCloser { - return r.response.Body() -} - -func (r *BceResponse) SetHttpResponse(response *http.Response) { - r.response = response -} - -func (r *BceResponse) ElapsedTime() time.Duration { - return r.response.ElapsedTime() -} - -func (r *BceResponse) ServiceError() *BceServiceError { - return r.serviceError -} - -func (r *BceResponse) ParseResponse() { - r.statusCode = r.response.StatusCode() - r.statusText = r.response.StatusText() - r.requestId = r.response.GetHeader(http.BCE_REQUEST_ID) - r.debugId = r.response.GetHeader(http.BCE_DEBUG_ID) - if r.IsFail() { - r.serviceError = NewBceServiceError("", r.statusText, r.requestId, r.statusCode) - - // First try to read the error `Code' and `Message' from body - rawBody, _ := ioutil.ReadAll(r.Body()) - defer r.Body().Close() - if len(rawBody) != 0 { - jsonDecoder := json.NewDecoder(bytes.NewBuffer(rawBody)) - if err := jsonDecoder.Decode(r.serviceError); err != nil { - r.serviceError = NewBceServiceError( - EMALFORMED_JSON, - "Service json error message decode failed", - r.requestId, - r.statusCode) - } - return - } - - // Then guess the `Message' from by the return status code - switch r.statusCode { - case 400: - r.serviceError.Code = EINVALID_HTTP_REQUEST - case 403: - r.serviceError.Code = EACCESS_DENIED - case 412: - r.serviceError.Code = EPRECONDITION_FAILED - case 500: - r.serviceError.Code = EINTERNAL_ERROR - default: - words := strings.Split(r.statusText, " ") - r.serviceError.Code = strings.Join(words[1:], "") - } - } -} - -func (r *BceResponse) ParseJsonBody(result interface{}) error { - defer r.Body().Close() - jsonDecoder := json.NewDecoder(r.Body()) - return jsonDecoder.Decode(result) -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/bce/retry.go b/vendor/github.com/baidubce/bce-sdk-go/bce/retry.go deleted file mode 100644 index 19675a3e..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/bce/retry.go +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// retry.go - define the retry policy when making requests to BCE services - -package bce - -import ( - "net" - "net/http" - "time" - - "github.com/baidubce/bce-sdk-go/util/log" -) - -// RetryPolicy defines the two methods to retry for sending request. -type RetryPolicy interface { - ShouldRetry(BceError, int) bool - GetDelayBeforeNextRetryInMillis(BceError, int) time.Duration -} - -// NoRetryPolicy just does not retry. -type NoRetryPolicy struct{} - -func (_ *NoRetryPolicy) ShouldRetry(err BceError, attempts int) bool { - return false -} - -func (_ *NoRetryPolicy) GetDelayBeforeNextRetryInMillis( - err BceError, attempts int) time.Duration { - return 0 * time.Millisecond -} - -func NewNoRetryPolicy() *NoRetryPolicy { - return &NoRetryPolicy{} -} - -// BackOffRetryPolicy implements a policy that retries with exponential back-off strategy. -// This policy will keep retrying until the maximum number of retries is reached. The delay time -// will be a fixed interval for the first time then 2 * interval for the second, 4 * internal for -// the third, and so on. -// In general, the delay time will be 2^number_of_retries_attempted*interval. When a maximum of -// delay time is specified, the delay time will never exceed this limit. -type BackOffRetryPolicy struct { - maxErrorRetry int - maxDelayInMillis int64 - baseIntervalInMillis int64 -} - -func (b *BackOffRetryPolicy) ShouldRetry(err BceError, attempts int) bool { - // Do not retry any more when retry the max times - if attempts >= b.maxErrorRetry { - return false - } - - if err == nil { - return true - } - - // Always retry on IO error - if _, ok := err.(net.Error); ok { - return true - } - - // Only retry on a service error - if realErr, ok := err.(*BceServiceError); ok { - switch realErr.StatusCode { - case http.StatusInternalServerError: - log.Warn("retry for internal server error(500)") - return true - case http.StatusBadGateway: - log.Warn("retry for bad gateway(502)") - return true - case http.StatusServiceUnavailable: - log.Warn("retry for service unavailable(503)") - return true - case http.StatusBadRequest: - if realErr.Code != "Http400" { - return false - } - log.Warn("retry for bad request(400)") - return true - } - - if realErr.Code == EREQUEST_EXPIRED { - log.Warn("retry for request expired") - return true - } - } - return false -} - -func (b *BackOffRetryPolicy) GetDelayBeforeNextRetryInMillis( - err BceError, attempts int) time.Duration { - if attempts < 0 { - return 0 * time.Millisecond - } - delayInMillis := (1 << uint64(attempts)) * b.baseIntervalInMillis - if delayInMillis > b.maxDelayInMillis { - return time.Duration(b.maxDelayInMillis) * time.Millisecond - } - return time.Duration(delayInMillis) * time.Millisecond -} - -func NewBackOffRetryPolicy(maxRetry int, maxDelay, base int64) *BackOffRetryPolicy { - return &BackOffRetryPolicy{maxRetry, maxDelay, base} -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/http/client.go b/vendor/github.com/baidubce/bce-sdk-go/http/client.go deleted file mode 100644 index b036a403..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/http/client.go +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// client.go - define the execute function to send http request and get response - -// Package http defines the structure of request and response which used to access the BCE services -// as well as the http constant headers and and methods. And finally implement the `Execute` funct- -// ion to do the work. -package http - -import ( - "net" - "net/http" - "net/url" - "sync" - "time" -) - -const ( - defaultMaxIdleConnsPerHost = 500 - defaultResponseHeaderTimeout = 60 * time.Second - defaultDialTimeout = 30 * time.Second - defaultSmallInterval = 600 * time.Second - defaultLargeInterval = 1200 * time.Second -) - -// The httpClient is the global variable to send the request and get response -// for reuse and the Client provided by the Go standard library is thread safe. -var ( - httpClient *http.Client - transport *http.Transport -) - -type timeoutConn struct { - conn net.Conn - smallInterval time.Duration - largeInterval time.Duration -} - -func (c *timeoutConn) Read(b []byte) (n int, err error) { - c.SetReadDeadline(time.Now().Add(c.smallInterval)) - n, err = c.conn.Read(b) - c.SetReadDeadline(time.Now().Add(c.largeInterval)) - return n, err -} -func (c *timeoutConn) Write(b []byte) (n int, err error) { - c.SetWriteDeadline(time.Now().Add(c.smallInterval)) - n, err = c.conn.Write(b) - c.SetWriteDeadline(time.Now().Add(c.largeInterval)) - return n, err -} -func (c *timeoutConn) Close() error { return c.conn.Close() } -func (c *timeoutConn) LocalAddr() net.Addr { return c.conn.LocalAddr() } -func (c *timeoutConn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() } -func (c *timeoutConn) SetDeadline(t time.Time) error { return c.conn.SetDeadline(t) } -func (c *timeoutConn) SetReadDeadline(t time.Time) error { return c.conn.SetReadDeadline(t) } -func (c *timeoutConn) SetWriteDeadline(t time.Time) error { return c.conn.SetWriteDeadline(t) } - -type ClientConfig struct { - RedirectDisabled bool -} - -var customizeInit sync.Once - -func InitClient(config ClientConfig) { - customizeInit.Do(func() { - httpClient = &http.Client{} - transport = &http.Transport{ - MaxIdleConnsPerHost: defaultMaxIdleConnsPerHost, - ResponseHeaderTimeout: defaultResponseHeaderTimeout, - Dial: func(network, address string) (net.Conn, error) { - conn, err := net.DialTimeout(network, address, defaultDialTimeout) - if err != nil { - return nil, err - } - tc := &timeoutConn{conn, defaultSmallInterval, defaultLargeInterval} - tc.SetReadDeadline(time.Now().Add(defaultLargeInterval)) - return tc, nil - }, - } - httpClient.Transport = transport - if config.RedirectDisabled { - httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - } - } - }) -} - -// Execute - do the http requset and get the response -// -// PARAMS: -// - request: the http request instance to be sent -// RETURNS: -// - response: the http response returned from the server -// - error: nil if ok otherwise the specific error -func Execute(request *Request) (*Response, error) { - // Build the request object for the current requesting - httpRequest := &http.Request{ - Proto: "HTTP/1.1", - ProtoMajor: 1, - ProtoMinor: 1, - } - - // Set the connection timeout for current request - httpClient.Timeout = time.Duration(request.Timeout()) * time.Second - - // Set the request method - httpRequest.Method = request.Method() - - // Set the request url - internalUrl := &url.URL{ - Scheme: request.Protocol(), - Host: request.Host(), - Path: request.Uri(), - RawQuery: request.QueryString()} - httpRequest.URL = internalUrl - - // Set the request headers - internalHeader := make(http.Header) - for k, v := range request.Headers() { - val := make([]string, 0, 1) - val = append(val, v) - internalHeader[k] = val - } - httpRequest.Header = internalHeader - - if request.Body() != nil { - if request.Length() > 0 { - httpRequest.ContentLength = request.Length() - httpRequest.Body = request.Body() - } else if request.Length() < 0 { - // if set body and ContentLength <= 0, will be chunked - httpRequest.Body = request.Body() - } // else {} body == nil and ContentLength == 0 - } - - // Set the proxy setting if needed - if len(request.ProxyUrl()) != 0 { - transport.Proxy = func(_ *http.Request) (*url.URL, error) { - return url.Parse(request.ProxyUrl()) - } - } - - // Perform the http request and get response - // It needs to explicitly close the keep-alive connections when error occurs for the request - // that may continue sending request's data subsequently. - start := time.Now() - - httpResponse, err := httpClient.Do(httpRequest) - - end := time.Now() - if err != nil { - transport.CloseIdleConnections() - return nil, err - } - if httpResponse.StatusCode >= 400 && - (httpRequest.Method == PUT || httpRequest.Method == POST) { - transport.CloseIdleConnections() - } - response := &Response{httpResponse, end.Sub(start)} - return response, nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/http/constants.go b/vendor/github.com/baidubce/bce-sdk-go/http/constants.go deleted file mode 100644 index 69c5e426..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/http/constants.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// constants.go - defines constants of the BCE http package including headers and methods - -package http - -// Constants of the supported HTTP methods for BCE -const ( - GET = "GET" - PUT = "PUT" - POST = "POST" - DELETE = "DELETE" - HEAD = "HEAD" - OPTIONS = "OPTIONS" - PATCH = "PATCH" -) - -// Constants of the HTTP headers for BCE -const ( - // Standard HTTP Headers - AUTHORIZATION = "Authorization" - CACHE_CONTROL = "Cache-Control" - CONTENT_DISPOSITION = "Content-Disposition" - CONTENT_ENCODING = "Content-Encoding" - CONTENT_LANGUAGE = "Content-Language" - CONTENT_LENGTH = "Content-Length" - CONTENT_MD5 = "Content-Md5" - CONTENT_RANGE = "Content-Range" - CONTENT_TYPE = "Content-Type" - DATE = "Date" - ETAG = "Etag" - EXPIRES = "Expires" - HOST = "Host" - LAST_MODIFIED = "Last-Modified" - LOCATION = "Location" - RANGE = "Range" - SERVER = "Server" - TRANSFER_ENCODING = "Transfer-Encoding" - USER_AGENT = "User-Agent" - - // BCE Common HTTP Headers - BCE_PREFIX = "x-bce-" - BCE_ACL = "x-bce-acl" - BCE_GRANT_READ = "x-bce-grant-read" - BCE_GRANT_FULL_CONTROL = "x-bce-grant-full-control" - BCE_CONTENT_SHA256 = "x-bce-content-sha256" - BCE_CONTENT_CRC32 = "x-bce-content-crc32" - BCE_REQUEST_ID = "x-bce-request-id" - BCE_USER_METADATA_PREFIX = "x-bce-meta-" - BCE_SECURITY_TOKEN = "x-bce-security-token" - BCE_DATE = "x-bce-date" - - // BOS HTTP Headers - BCE_COPY_METADATA_DIRECTIVE = "x-bce-metadata-directive" - BCE_COPY_SOURCE = "x-bce-copy-source" - BCE_COPY_SOURCE_IF_MATCH = "x-bce-copy-source-if-match" - BCE_COPY_SOURCE_IF_MODIFIED_SINCE = "x-bce-copy-source-if-modified-since" - BCE_COPY_SOURCE_IF_NONE_MATCH = "x-bce-copy-source-if-none-match" - BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE = "x-bce-copy-source-if-unmodified-since" - BCE_COPY_SOURCE_RANGE = "x-bce-copy-source-range" - BCE_DEBUG_ID = "x-bce-debug-id" - BCE_OBJECT_TYPE = "x-bce-object-type" - BCE_NEXT_APPEND_OFFSET = "x-bce-next-append-offset" - BCE_STORAGE_CLASS = "x-bce-storage-class" - BCE_PROCESS = "x-bce-process" - BCE_RESTORE_TIER = "x-bce-restore-tier" - BCE_RESTORE_DAYS = "x-bce-restore-days" - BCE_RESTORE = "x-bce-restore" - BCE_FORBID_OVERWRITE = "x-bce-forbid-overwrite" - BCE_SYMLINK_TARGET = "x-bce-symlink-target" -) diff --git a/vendor/github.com/baidubce/bce-sdk-go/http/request.go b/vendor/github.com/baidubce/bce-sdk-go/http/request.go deleted file mode 100644 index 7fecfb99..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/http/request.go +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// request.go - the custom HTTP request for BCE - -package http - -import ( - "fmt" - "io" - "strconv" - "strings" - - "github.com/baidubce/bce-sdk-go/util" -) - -// Reauest stands for the general http request structure to make request to the BCE services. -type Request struct { - protocol string - host string - port int - method string - uri string - proxyUrl string - timeout int - headers map[string]string - params map[string]string - - // Optional body and length fields to set the body stream and content length - body io.ReadCloser - length int64 -} - -func (r *Request) Protocol() string { - return r.protocol -} - -func (r *Request) SetProtocol(protocol string) { - r.protocol = protocol -} - -func (r *Request) Endpoint() string { - if r.host == "" { - return "" - } - return r.protocol + "://" + r.host -} - -func (r *Request) SetEndpoint(endpoint string) { - pos := strings.Index(endpoint, "://") - rest := endpoint - if pos != -1 { - r.protocol = endpoint[0:pos] - rest = endpoint[pos+3:] - } else { - r.protocol = "http" - } - - r.SetHost(rest) -} - -func (r *Request) Host() string { - return r.host -} - -func (r *Request) SetHost(host string) { - r.host = host - pos := strings.Index(host, ":") - if pos != -1 { - p, e := strconv.Atoi(host[pos+1:]) - if e == nil { - r.port = p - } - } - - if r.port == 0 { - if r.protocol == "http" { - r.port = 80 - } else if r.protocol == "https" { - r.port = 443 - } - } -} - -func (r *Request) Port() int { - return r.port -} - -func (r *Request) SetPort(port int) { - // Port can be set by the endpoint or host, this method is rarely used. - r.port = port -} - -func (r *Request) Headers() map[string]string { - return r.headers -} - -func (r *Request) SetHeaders(headers map[string]string) { - r.headers = headers -} - -func (r *Request) Header(key string) string { - if v, ok := r.headers[key]; ok { - return v - } - return "" -} - -func (r *Request) SetHeader(key, value string) { - if r.headers == nil { - r.headers = make(map[string]string) - } - r.headers[key] = value -} - -func (r *Request) Params() map[string]string { - return r.params -} - -func (r *Request) SetParams(params map[string]string) { - r.params = params -} - -func (r *Request) Param(key string) string { - if v, ok := r.params[key]; ok { - return v - } - return "" -} - -func (r *Request) SetParam(key, value string) { - if r.params == nil { - r.params = make(map[string]string) - } - r.params[key] = value -} - -func (r *Request) QueryString() string { - buf := make([]string, 0, len(r.params)) - for k, v := range r.params { - buf = append(buf, util.UriEncode(k, true)+"="+util.UriEncode(v, true)) - } - return strings.Join(buf, "&") -} - -func (r *Request) Method() string { - return r.method -} - -func (r *Request) SetMethod(method string) { - r.method = method -} - -func (r *Request) Uri() string { - return r.uri -} - -func (r *Request) SetUri(uri string) { - r.uri = uri -} - -func (r *Request) ProxyUrl() string { - return r.proxyUrl -} - -func (r *Request) SetProxyUrl(url string) { - r.proxyUrl = url -} - -func (r *Request) Timeout() int { - return r.timeout -} - -func (r *Request) SetTimeout(timeout int) { - r.timeout = timeout -} - -func (r *Request) Body() io.ReadCloser { - return r.body -} - -func (r *Request) SetBody(stream io.ReadCloser) { - r.body = stream -} - -func (r *Request) Length() int64 { - return r.length -} - -func (r *Request) SetLength(l int64) { - r.length = l -} - -func (r *Request) GenerateUrl(addPort bool) string { - if addPort { - return fmt.Sprintf("%s://%s:%d%s?%s", - r.protocol, r.host, r.port, r.uri, r.QueryString()) - } else { - return fmt.Sprintf("%s://%s%s?%s", r.protocol, r.host, r.uri, r.QueryString()) - } -} - -func (r *Request) String() string { - header := make([]string, 0, len(r.headers)) - for k, v := range r.headers { - header = append(header, "\t"+k+"="+v) - } - return fmt.Sprintf("\t%s %s\n%v", - r.method, r.GenerateUrl(false), strings.Join(header, "\n")) -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/http/response.go b/vendor/github.com/baidubce/bce-sdk-go/http/response.go deleted file mode 100644 index 98632fc9..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/http/response.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// response.go - the custom HTTP response for BCE - -package http - -import ( - "io" - "net/http" - "time" -) - -// Response defines the general http response structure for accessing the BCE services. -type Response struct { - httpResponse *http.Response // the standard libaray http.Response object - elapsedTime time.Duration // elapsed time just from sending request to receiving response -} - -func (r *Response) StatusText() string { - return r.httpResponse.Status -} - -func (r *Response) StatusCode() int { - return r.httpResponse.StatusCode -} - -func (r *Response) Protocol() string { - return r.httpResponse.Proto -} - -func (r *Response) HttpResponse() *http.Response { - return r.httpResponse -} - -func (r *Response) SetHttpResponse(response *http.Response) { - r.httpResponse = response -} - -func (r *Response) ElapsedTime() time.Duration { - return r.elapsedTime -} - -func (r *Response) GetHeader(name string) string { - return r.httpResponse.Header.Get(name) -} - -func (r *Response) GetHeaders() map[string]string { - header := r.httpResponse.Header - ret := make(map[string]string, len(header)) - for k, v := range header { - ret[k] = v[0] - } - return ret -} - -func (r *Response) ContentLength() int64 { - return r.httpResponse.ContentLength -} - -func (r *Response) Body() io.ReadCloser { - return r.httpResponse.Body -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/model.go b/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/model.go deleted file mode 100644 index 944a7839..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/model.go +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2020 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// model.go - definitions of the request arguments and results data structure model - -package api - -// SendSmsArgs defines the data structure for sending a SMS request -type SendSmsArgs struct { - Mobile string `json:"mobile"` - Template string `json:"template"` - SignatureId string `json:"signatureId"` - ContentVar map[string]interface{} `json:"contentVar"` - Custom string `json:"custom,omitempty"` - UserExtId string `json:"userExtId,omitempty"` - CallbackUrlId string `json:"merchantUrlId,omitempty"` - ClientToken string `json:"clientToken,omitempty"` -} - -// SendSmsResult defines the data structure of the result of sending a SMS request -type SendSmsResult struct { - Code string `json:"code"` - RequestId string `json:"requestId"` - Message string `json:"message"` - Data []SendMessageItem `json:"data"` -} - -type SendMessageItem struct { - Code string `json:"code"` - Mobile string `json:"mobile"` - MessageId string `json:"messageId"` - Message string `json:"message"` -} - -// CreateSignatureArgs defines the data structure for creating a signature -type CreateSignatureArgs struct { - Content string `json:"content"` - ContentType string `json:"contentType"` - Description string `json:"description,omitempty"` - CountryType string `json:"countryType"` - SignatureFileBase64 string `json:"signatureFileBase64,omitempty"` - SignatureFileFormat string `json:"signatureFileFormat,omitempty"` -} - -// CreateSignatureResult defines the data structure of the result of creating a signature -type CreateSignatureResult struct { - SignatureId string `json:"signatureId"` - Status string `json:"status"` -} - -// DeleteSignatureArgs defines the input data structure for deleting a signature -type DeleteSignatureArgs struct { - SignatureId string `json:"signatureId"` -} - -// ModifySignatureArgs defines the input data structure for modifying parameters of a signature -type ModifySignatureArgs struct { - SignatureId string `json:"signatureId"` - Content string `json:"content"` - ContentType string `json:"contentType"` - Description string `json:"description,omitempty"` - CountryType string `json:"countryType"` - SignatureFileBase64 string `json:"signatureFileBase64,omitempty"` - SignatureFileFormat string `json:"signatureFileFormat,omitempty"` -} - -// GetSignatureArgs defines the input data structure for Getting a signature -type GetSignatureArgs struct { - SignatureId string `json:"signatureId"` -} - -// GetSignatureResult defines the data structure of the result of getting a signature -type GetSignatureResult struct { - SignatureId string `json:"signatureId"` - UserId string `json:"userId"` - Content string `json:"content"` - ContentType string `json:"contentType"` - Status string `json:"status"` - CountryType string `json:"countryType"` - Review string `json:"review"` -} - -// CreateTemplateArgs defines the data structure for creating a template -type CreateTemplateArgs struct { - Name string `json:"name"` - Content string `json:"content"` - SmsType string `json:"smsType"` - CountryType string `json:"countryType"` - Description string `json:"description,omitempty"` -} - -// CreateTemplateResult defines the data structure of the result of creating a template -type CreateTemplateResult struct { - TemplateId string `json:"templateId"` - Status string `json:"status"` -} - -// DeleteTemplateArgs defines the data structure for deleting a template -type DeleteTemplateArgs struct { - TemplateId string `json:"templateId"` -} - -// ModifyTemplateArgs defines the data structure for modifying a template -type ModifyTemplateArgs struct { - TemplateId string `json:"templateId"` - Name string `json:"name"` - Content string `json:"content"` - SmsType string `json:"smsType"` - CountryType string `json:"countryType"` - Description string `json:"description,omitempty"` -} - -// GetTemplateArgs defines the data structure for getting a template -type GetTemplateArgs struct { - TemplateId string `json:"templateId"` -} - -// GetTemplateResult defines the data structure of the result of getting a template -type GetTemplateResult struct { - TemplateId string `json:"templateId"` - UserId string `json:"userId"` - Name string `json:"name"` - Content string `json:"content"` - CountryType string `json:"countryType"` - SmsType string `json:"smsType"` - Status string `json:"status"` - Description string `json:"description"` - Review string `json:"review"` -} - -// UpdateQuotaRateArgs defines the data structure for updating quota and rate limit -type UpdateQuotaRateArgs struct { - QuotaPerDay int `json:"quotaPerDay"` - QuotaPerMonth int `json:"quotaPerMonth"` - RateLimitPerDay int `json:"rateLimitPerMobilePerSignByDay"` - RateLimitPerHour int `json:"rateLimitPerMobilePerSignByHour"` - RateLimitPerMinute int `json:"rateLimitPerMobilePerSignByMinute"` -} - -// QueryQuotaRateResult defines the data structure of querying the user's quota and rate limit -type QueryQuotaRateResult struct { - QuotaPerDay int `json:"quotaPerDay"` - QuotaRemainToday int `json:"quotaRemainToday"` - QuotaPerMonth int `json:"quotaPerMonth"` - QuotaRemainThisMonth int `json:"quotaRemainThisMonth"` - QuotaWhitelist bool `json:"quotaWhitelist"` - RateLimitPerDay int `json:"rateLimitPerMobilePerSignByDay"` - RateLimitPerHour int `json:"rateLimitPerMobilePerSignByHour"` - RateLimitPerMinute int `json:"rateLimitPerMobilePerSignByMinute"` - RateLimitWhitelist bool `json:"rateLimitWhitelist"` -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/quota_rate.go b/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/quota_rate.go deleted file mode 100644 index ccc74581..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/quota_rate.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2020 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// quota_rate.go - the quota and rate limit APIs definition supported by the SMS service - -package api - -import ( - "encoding/json" - - "github.com/baidubce/bce-sdk-go/bce" - "github.com/baidubce/bce-sdk-go/http" -) - -// QueryQuotaRate - query the quota and rate limit detail of an user -// -// RETURNS: -// - *QueryQuotaRateResult: the result of the query -// - error: the return error if any occurs -func QueryQuotaRate(cli bce.Client) (*QueryQuotaRateResult, error) { - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_QUOTA) - req.SetMethod(http.GET) - req.SetParam("userQuery", "") - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return nil, err - } - if resp.IsFail() { - return nil, resp.ServiceError() - } - result := &QueryQuotaRateResult{} - if err := resp.ParseJsonBody(result); err != nil { - return nil, err - } - return result, nil -} - -// UpdateQuotaRate - update the quota and rate limit detail of an user -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to update the quota and rate limit -// RETURNS: -// - *ListBucketsResult: the result bucket list structure -// - error: nil if ok otherwise the specific error -func UpdateQuotaRate(cli bce.Client, args *UpdateQuotaRateArgs) error { - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_QUOTA) - req.SetMethod(http.PUT) - req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) - jsonBytes, jsonErr := json.Marshal(args) - if jsonErr != nil { - return jsonErr - } - body, err := bce.NewBodyFromBytes(jsonBytes) - if err != nil { - return err - } - req.SetBody(body) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return err - } - if resp.IsFail() { - return resp.ServiceError() - } - return nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/send_sms.go b/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/send_sms.go deleted file mode 100644 index 2fd4951b..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/send_sms.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2020 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// send_sms.go - the send sms APIs definition supported by the SMS service - -package api - -import ( - "encoding/json" - - "github.com/baidubce/bce-sdk-go/bce" - "github.com/baidubce/bce-sdk-go/http" - "github.com/baidubce/bce-sdk-go/util" -) - -// SendSms - send an sms message -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to send an sms message -// RETURNS: -// - *api.SendSmsResult: the result of sending an sms message -// - error: the return error if any occurs -func SendSms(cli bce.Client, args *SendSmsArgs) (*SendSmsResult, error) { - if err := CheckError(len(args.Mobile) > 0, "mobile can not be blank"); err != nil { - return nil, err - } - if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { - return nil, err - } - if err := CheckError(len(args.Template) > 0, "templateId can not be blank"); err != nil { - return nil, err - } - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_SEND_SMS) - req.SetMethod(http.POST) - req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) - if len(args.ClientToken) > 0 { - req.SetParam(CLIENT_TOKEN, args.ClientToken) - } else { - req.SetParam(CLIENT_TOKEN, util.NewUUID()) - } - jsonBytes, jsonErr := json.Marshal(args) - if jsonErr != nil { - return nil, jsonErr - } - body, err := bce.NewBodyFromBytes(jsonBytes) - if err != nil { - return nil, err - } - req.SetBody(body) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return nil, err - } - if resp.IsFail() { - return nil, resp.ServiceError() - } - result := &SendSmsResult{} - if err := resp.ParseJsonBody(result); err != nil { - return nil, err - - } - return result, nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/signature.go b/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/signature.go deleted file mode 100644 index 7452f8a6..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/signature.go +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2020 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// signature.go - the sms signature APIs definition supported by the SMS service - -package api - -import ( - "encoding/json" - - "github.com/baidubce/bce-sdk-go/bce" - "github.com/baidubce/bce-sdk-go/http" - "github.com/baidubce/bce-sdk-go/util" -) - -// CreateSignature - create an sms signature -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to create an sms signature -// RETURNS: -// - *api.CreateSignatureResult: the result of creating an sms signature -// - error: the return error if any occurs -func CreateSignature(cli bce.Client, args *CreateSignatureArgs) (*CreateSignatureResult, error) { - if err := CheckError(args != nil, "CreateSignatureArgs can not be nil"); err != nil { - return nil, err - } - if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { - return nil, err - } - if err := CheckError(len(args.ContentType) > 0, "contentType can not be blank"); err != nil { - return nil, err - } - if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { - return nil, err - } - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_SIGNATURE) - req.SetMethod(http.POST) - req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) - req.SetParam(CLIENT_TOKEN, util.NewUUID()) - jsonBytes, jsonErr := json.Marshal(args) - if jsonErr != nil { - return nil, jsonErr - } - body, err := bce.NewBodyFromBytes(jsonBytes) - if err != nil { - return nil, err - } - req.SetBody(body) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return nil, err - } - if resp.IsFail() { - return nil, resp.ServiceError() - } - result := &CreateSignatureResult{} - if err := resp.ParseJsonBody(result); err != nil { - return nil, err - } - return result, nil -} - -// DeleteSignature - delete an sms signature -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to delete an sms signature -// RETURNS: -// - error: the return error if any occurs -func DeleteSignature(cli bce.Client, args *DeleteSignatureArgs) error { - if err := CheckError(args != nil, "DeleteSignatureArgs can not be nil"); err != nil { - return err - } - if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { - return err - } - return bce.NewRequestBuilder(cli). - WithMethod(http.DELETE). - WithURL(REQUEST_URI_SIGNATURE + bce.URI_PREFIX + args.SignatureId). - Do() -} - -// ModifySignature - modify an sms signature -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to modify an sms signature -// RETURNS: -// - error: the return error if any occurs -func ModifySignature(cli bce.Client, args *ModifySignatureArgs) error { - if err := CheckError(args != nil, "ModifySignatureArgs can not be nil"); err != nil { - return err - } - if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { - return err - } - if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { - return err - } - if err := CheckError(len(args.ContentType) > 0, "contentType can not be blank"); err != nil { - return err - } - if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { - return err - } - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_SIGNATURE + bce.URI_PREFIX + args.SignatureId) - req.SetMethod(http.PUT) - req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) - jsonBytes, jsonErr := json.Marshal(args) - if jsonErr != nil { - return jsonErr - } - body, err := bce.NewBodyFromBytes(jsonBytes) - if err != nil { - return err - } - req.SetBody(body) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return err - } - if resp.IsFail() { - return resp.ServiceError() - } - defer func() { resp.Body().Close() }() - return nil -} - -// GetSignature - get the detail of an sms signature -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to get the detail of an sms signature -// RETURNS: -// - *api.GetSignatureResult: the detail of an sms signature -// - error: the return error if any occurs -func GetSignature(cli bce.Client, args *GetSignatureArgs) (*GetSignatureResult, error) { - if err := CheckError(args != nil, "GetSignatureArgs can not be nil"); err != nil { - return nil, err - } - if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { - return nil, err - } - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_SIGNATURE + bce.URI_PREFIX + args.SignatureId) - req.SetMethod(http.GET) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return nil, err - } - if resp.IsFail() { - return nil, resp.ServiceError() - } - result := &GetSignatureResult{} - if err := resp.ParseJsonBody(result); err != nil { - return nil, err - } - return result, nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/template.go b/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/template.go deleted file mode 100644 index ec6d2d03..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/template.go +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright 2020 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// template.go - the sms template APIs definition supported by the SMS service - -package api - -import ( - "encoding/json" - - "github.com/baidubce/bce-sdk-go/bce" - "github.com/baidubce/bce-sdk-go/http" - "github.com/baidubce/bce-sdk-go/util" -) - -// CreateTemplate - create an sms template -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to create an sms template -// RETURNS: -// - *api.CreateTemplateResult: the result of creating an sms template -// - error: the return error if any occurs -func CreateTemplate(cli bce.Client, args *CreateTemplateArgs) (*CreateTemplateResult, error) { - if err := CheckError(args != nil, "CreateTemplateArgs can not be nil"); err != nil { - return nil, err - } - if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { - return nil, err - } - if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { - return nil, err - } - if err := CheckError(len(args.Name) > 0, "name can not be blank"); err != nil { - return nil, err - } - if err := CheckError(len(args.SmsType) > 0, "smsType can not be blank"); err != nil { - return nil, err - } - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_TEMPLATE) - req.SetMethod(http.POST) - req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) - req.SetParam(CLIENT_TOKEN, util.NewUUID()) - jsonBytes, jsonErr := json.Marshal(args) - if jsonErr != nil { - return nil, jsonErr - } - body, err := bce.NewBodyFromBytes(jsonBytes) - if err != nil { - return nil, err - } - req.SetBody(body) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return nil, err - } - if resp.IsFail() { - return nil, resp.ServiceError() - } - result := &CreateTemplateResult{} - if err := resp.ParseJsonBody(result); err != nil { - return nil, err - } - return result, nil -} - -// DeleteTemplate - delete an sms template -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to delete an sms template -// RETURNS: -// - error: the return error if any occurs -func DeleteTemplate(cli bce.Client, args *DeleteTemplateArgs) error { - if err := CheckError(args != nil, "DeleteTemplateArgs can not be nil"); err != nil { - return err - } - if err := CheckError(len(args.TemplateId) > 0, "templateId can not be blank"); err != nil { - return err - } - return bce.NewRequestBuilder(cli). - WithMethod(http.DELETE). - WithURL(REQUEST_URI_TEMPLATE + bce.URI_PREFIX + args.TemplateId). - Do() -} - -// ModifyTemplate - modify an sms template -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to modify an sms template -// RETURNS: -// - error: the return error if any occurs -func ModifyTemplate(cli bce.Client, args *ModifyTemplateArgs) error { - if err := CheckError(args != nil, "ModifyTemplateArgs can not be nil"); err != nil { - return err - } - if err := CheckError(len(args.TemplateId) > 0, "templateId can not be blank"); err != nil { - return err - } - if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { - return err - } - if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { - return err - } - if err := CheckError(len(args.Name) > 0, "name can not be blank"); err != nil { - return err - } - if err := CheckError(len(args.SmsType) > 0, "smsType can not be blank"); err != nil { - return err - } - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_TEMPLATE + bce.URI_PREFIX + args.TemplateId) - req.SetMethod(http.PUT) - req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) - jsonBytes, jsonErr := json.Marshal(args) - if jsonErr != nil { - return jsonErr - } - body, err := bce.NewBodyFromBytes(jsonBytes) - if err != nil { - return err - } - req.SetBody(body) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return err - } - if resp.IsFail() { - return resp.ServiceError() - } - defer func() { resp.Body().Close() }() - return nil -} - -// GetTemplate - modify an sms template -// -// PARAMS: -// - cli: the client agent which can perform sending request -// - args: the arguments to modify an sms template -// RETURNS: -// - error: the return error if any occurs -func GetTemplate(cli bce.Client, args *GetTemplateArgs) (*GetTemplateResult, error) { - if err := CheckError(args != nil, "GetTemplateResult can not be nil"); err != nil { - return nil, err - } - if err := CheckError(len(args.TemplateId) > 0, "templateId can not be blank"); err != nil { - return nil, err - } - req := &bce.BceRequest{} - req.SetUri(REQUEST_URI_TEMPLATE + bce.URI_PREFIX + args.TemplateId) - req.SetMethod(http.GET) - resp := &bce.BceResponse{} - if err := cli.SendRequest(req, resp); err != nil { - return nil, err - } - if resp.IsFail() { - return nil, resp.ServiceError() - } - result := &GetTemplateResult{} - if err := resp.ParseJsonBody(result); err != nil { - return nil, err - } - return result, nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/util.go b/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/util.go deleted file mode 100644 index 6074f4df..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/services/sms/api/util.go +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2020 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// util.go - define the utilities for api package of SMS service - -package api - -import ( - "fmt" -) - -const ( - REQUEST_URI_SEND_SMS = "/api/v3/sendsms" - REQUEST_URI_SIGNATURE = "/sms/v3/signatureApply" - REQUEST_URI_TEMPLATE = "/sms/v3/template" - REQUEST_URI_QUOTA = "/sms/v3/quota" - CLIENT_TOKEN = "clientToken" -) - -func CheckError(condition bool, errMessage string) error { - if !condition { - return fmt.Errorf(errMessage) - } - return nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/services/sms/client.go b/vendor/github.com/baidubce/bce-sdk-go/services/sms/client.go deleted file mode 100644 index b38bf506..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/services/sms/client.go +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2020 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// client.go - define the client for SMS service - -package sms - -import ( - "github.com/baidubce/bce-sdk-go/auth" - "github.com/baidubce/bce-sdk-go/bce" - "github.com/baidubce/bce-sdk-go/services/sms/api" -) - -const ( - REGION_BJ = "bj" - REGION_SU = "su" - DEFAULT_SERVICE_DOMAIN = "smsv3." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN -) - -// Client of SMS service is a kind of BceClient, so derived from BceClient -type Client struct { - *bce.BceClient -} - -// NewClient make the SMS service client with default configuration. -// Use `cli.Config.xxx` to access the config or change it to non-default value. -func NewClient(ak, sk, endpoint string) (*Client, error) { - var credentials *auth.BceCredentials - var err error - if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request - credentials, err = nil, nil - } else { - credentials, err = auth.NewBceCredentials(ak, sk) - if err != nil { - return nil, err - } - } - if len(endpoint) == 0 { - endpoint = DEFAULT_SERVICE_DOMAIN - } - defaultSignOptions := &auth.SignOptions{ - HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, - ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} - defaultConf := &bce.BceClientConfiguration{ - Endpoint: endpoint, - Region: bce.DEFAULT_REGION, - UserAgent: bce.DEFAULT_USER_AGENT, - Credentials: credentials, - SignOption: defaultSignOptions, - Retry: bce.DEFAULT_RETRY_POLICY, - ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} - v1Signer := &auth.BceV1Signer{} - - client := &Client{bce.NewBceClient(defaultConf, v1Signer)} - return client, nil -} - -// SendSms - send an sms message -// -// PARAMS: -// - args: the arguments to send an sms message -// RETURNS: -// - *api.SendSmsResult: the result of sending an sms message -// - error: the return error if any occurs -func (c *Client) SendSms(args *api.SendSmsArgs) (*api.SendSmsResult, error) { - return api.SendSms(c, args) -} - -// CreateSignature - create an sms signature -// -// PARAMS: -// - args: the arguments to create an sms signature -// RETURNS: -// - *api.CreateSignatureResult: the result of creating an sms signature -// - error: the return error if any occurs -func (c *Client) CreateSignature(args *api.CreateSignatureArgs) (*api.CreateSignatureResult, error) { - return api.CreateSignature(c, args) -} - -// DeleteSignature - delete an sms signature -// -// PARAMS: -// - args: the arguments to delete an sms signature -// RETURNS: -// - error: the return error if any occurs -func (c *Client) DeleteSignature(args *api.DeleteSignatureArgs) error { - return api.DeleteSignature(c, args) -} - -// ModifySignature - modify an sms signature -// -// PARAMS: -// - args: the arguments to modify an sms signature -// RETURNS: -// - error: the return error if any occurs -func (c *Client) ModifySignature(args *api.ModifySignatureArgs) error { - return api.ModifySignature(c, args) -} - -// GetSignature - get the detail of an sms signature -// -// PARAMS: -// - args: the arguments to get the detail of an sms signature -// RETURNS: -// - *api.GetSignatureResult: the detail of an sms signature -// - error: the return error if any occurs -func (c *Client) GetSignature(args *api.GetSignatureArgs) (*api.GetSignatureResult, error) { - return api.GetSignature(c, args) -} - -// CreateTemplate - create an sms template -// -// PARAMS: -// - args: the arguments to create an sms template -// RETURNS: -// - *api.CreateTemplateResult: the result of creating an sms template -// - error: the return error if any occurs -func (c *Client) CreateTemplate(args *api.CreateTemplateArgs) (*api.CreateTemplateResult, error) { - return api.CreateTemplate(c, args) -} - -// DeleteTemplate - delete an sms template -// -// PARAMS: -// - args: the arguments to delete an sms template -// RETURNS: -// - error: the return error if any occurs -func (c *Client) DeleteTemplate(args *api.DeleteTemplateArgs) error { - return api.DeleteTemplate(c, args) -} - -// ModifyTemplate - modify an sms template -// -// PARAMS: -// - args: the arguments to modify an sms template -// RETURNS: -// - error: the return error if any occurs -func (c *Client) ModifyTemplate(args *api.ModifyTemplateArgs) error { - return api.ModifyTemplate(c, args) -} - -// GetTemplate - modify an sms template -// -// PARAMS: -// - args: the arguments to modify an sms template -// RETURNS: -// - error: the return error if any occurs -func (c *Client) GetTemplate(args *api.GetTemplateArgs) (*api.GetTemplateResult, error) { - return api.GetTemplate(c, args) -} - -// QueryQuotaAndRateLimit - query the quota and rate limit -// -// RETURNS: -// - QueryQuotaRateResult: the result of querying the quota and rate limit -// - error: the return error if any occurs -func (c *Client) QueryQuotaAndRateLimit() (*api.QueryQuotaRateResult, error) { - return api.QueryQuotaRate(c) -} - -// UpdateQuotaAndRateLimit - update the quota or rate limit -// PARAMS: -// - args: the arguments to update the quota or rate limit -// RETURNS: -// - error: the return error if any occurs -func (c *Client) UpdateQuotaAndRateLimit(args *api.UpdateQuotaRateArgs) error { - return api.UpdateQuotaRate(c, args) -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/util/log/logger.go b/vendor/github.com/baidubce/bce-sdk-go/util/log/logger.go deleted file mode 100644 index 81f54987..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/util/log/logger.go +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// logger.go - defines the logger structure and methods - -// Package log implements the log facilities for BCE. It supports log to stderr, stdout as well as -// log to file with rotating. It is safe to be called by multiple goroutines. -// By using the package level function to use the default logger: -// log.SetLogHandler(log.STDOUT | log.FILE) // default is log to stdout -// log.SetLogDir("/tmp") // default is /tmp -// log.SetRotateType(log.ROTATE_DAY) // default is log.HOUR -// log.SetRotateSize(1 << 30) // default is 1GB -// log.SetLogLevel(log.INFO) // default is log.DEBUG -// log.Debug(1, 1.2, "a") -// log.Debugln(1, 1.2, "a") -// log.Debugf(1, 1.2, "a") -// User can also create new logger without using the default logger: -// customLogger := log.NewLogger() -// customLogger.SetLogHandler(log.FILE) -// customLogger.Debug(1, 1.2, "a") -// The log format can also support custom setting by using the following interface: -// log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_TIME, log.FMT_MSG}) -// Most of the cases just use the default format is enough: -// []string{FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG} -package log - -import ( - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "strings" - "time" -) - -type Handler uint8 - -// Constants for log handler flags, default is STDOUT -const ( - NONE Handler = 0 - STDOUT Handler = 1 - STDERR Handler = 1 << 1 - FILE Handler = 1 << 2 -) - -type RotateStrategy uint8 - -// Constants for log rotating strategy when logging to file, default is by hour -const ( - ROTATE_NONE RotateStrategy = iota - ROTATE_DAY - ROTATE_HOUR - ROTATE_MINUTE - ROTATE_SIZE - - DEFAULT_ROTATE_TYPE = ROTATE_HOUR - DEFAULT_ROTATE_SIZE int64 = 1 << 30 - DEFAULT_LOG_DIR = "/tmp" - ROTATE_SIZE_FILE_PREFIX = "rotating" -) - -type Level uint8 - -// Constants for log levels, default is DEBUG -const ( - DEBUG Level = iota - INFO - WARN - ERROR - FATAL - PANIC -) - -var gLevelString = [...]string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL", "PANIC"} - -// Constants of the log format components to support user custom specification -const ( - FMT_LEVEL = "level" - FMT_LTIME = "ltime" // long time with microsecond - FMT_TIME = "time" // just with second - FMT_LOCATION = "location" // caller's location with file, line, function - FMT_MSG = "msg" -) - -var ( - LOG_FMT_STR = map[string]string{ - FMT_LEVEL: "[%s]", - FMT_LTIME: "2006-01-02 15:04:05.000000", - FMT_TIME: "2006-01-02 15:04:05", - FMT_LOCATION: "%s:%d:%s:", - FMT_MSG: "%s", - } - gDefaultLogFormat = []string{FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG} -) - -type writerArgs struct { - record string - rotateArgs interface{} // used for rotating: the size of the record or the logging time -} - -// Logger defines the internal implementation of the log facility -type logger struct { - writers map[Handler]io.WriteCloser // the destination writer to log message - writerChan chan *writerArgs // the writer channal to pass each record and time or size - logFormat []string - levelThreshold Level - handler Handler - - // Fields that used when logging to file - logDir string - logFile string - rotateType RotateStrategy - rotateSize int64 - done chan bool -} - -func (l *logger) logging(level Level, format string, args ...interface{}) { - // Only log message that set the handler and is greater than or equal to the threshold - if l.handler == NONE || level < l.levelThreshold { - return - } - - // Generate the log record string and pass it to the writer channel - now := time.Now() - pc, file, line, ok, funcname := uintptr(0), "???", 0, true, "???" - pc, file, line, ok = runtime.Caller(2) - if ok { - funcname = runtime.FuncForPC(pc).Name() - funcname = filepath.Ext(funcname) - funcname = strings.TrimPrefix(funcname, ".") - file = filepath.Base(file) - } - buf := make([]string, 0, len(l.logFormat)) - msg := fmt.Sprintf(format, args...) - for _, f := range l.logFormat { - if _, exists := LOG_FMT_STR[f]; !exists { // skip not supported part - continue - } - fmtStr := LOG_FMT_STR[f] - switch f { - case FMT_LEVEL: - buf = append(buf, fmt.Sprintf(fmtStr, gLevelString[level])) - case FMT_LTIME: - buf = append(buf, now.Format(fmtStr)) - case FMT_TIME: - buf = append(buf, now.Format(fmtStr)) - case FMT_LOCATION: - buf = append(buf, fmt.Sprintf(fmtStr, file, line, funcname)) - case FMT_MSG: - buf = append(buf, fmt.Sprintf(fmtStr, msg)) - } - } - record := strings.Join(buf, " ") - if l.rotateType == ROTATE_SIZE { - l.writerChan <- &writerArgs{record, int64(len(record))} - } else { - l.writerChan <- &writerArgs{record, now} - } - - // wait for current record done logging -} - -func (l *logger) buildWriter(args interface{}) { - if l.handler&STDOUT == STDOUT { - l.writers[STDOUT] = os.Stdout - } else { - delete(l.writers, STDOUT) - } - if l.handler&STDERR == STDERR { - l.writers[STDERR] = os.Stderr - } else { - delete(l.writers, STDERR) - } - if l.handler&FILE == FILE { - l.writers[FILE] = l.buildFileWriter(args) - } else { - delete(l.writers, FILE) - } -} - -func (l *logger) buildFileWriter(args interface{}) io.WriteCloser { - if l.handler&FILE != FILE { - return os.Stderr - } - - if len(l.logDir) == 0 { - l.logDir = DEFAULT_LOG_DIR - } - if l.rotateType < ROTATE_NONE || l.rotateType > ROTATE_SIZE { - l.rotateType = DEFAULT_ROTATE_TYPE - } - if l.rotateType == ROTATE_SIZE && l.rotateSize == 0 { - l.rotateSize = DEFAULT_ROTATE_SIZE - } - - logFile, needCreateFile := "", false - if l.rotateType == ROTATE_SIZE { - recordSize, _ := args.(int64) - logFile, needCreateFile = l.buildFileWriterBySize(recordSize) - } else { - recordTime, _ := args.(time.Time) - switch l.rotateType { - case ROTATE_NONE: - logFile = "default.log" - case ROTATE_DAY: - logFile = recordTime.Format("2006-01-02.log") - case ROTATE_HOUR: - logFile = recordTime.Format("2006-01-02_15.log") - case ROTATE_MINUTE: - logFile = recordTime.Format("2006-01-02_15-04.log") - } - if _, exist := getFileInfo(filepath.Join(l.logDir, logFile)); !exist { - needCreateFile = true - } - } - l.logFile = logFile - logFile = filepath.Join(l.logDir, l.logFile) - - // Should create new file - if needCreateFile { - if w, ok := l.writers[FILE]; ok { - w.Close() - } - if writer, err := os.Create(logFile); err == nil { - return writer - } else { - return os.Stderr - } - } - - // Already open the file - if w, ok := l.writers[FILE]; ok { - return w - } - - // Newly open the file - if writer, err := os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND, 0666); err == nil { - return writer - } else { - return os.Stderr - } -} - -func (l *logger) buildFileWriterBySize(recordSize int64) (string, bool) { - logFile, needCreateFile := "", false - // First running the program and need to get filename by checking the existed files - if len(l.logFile) == 0 { - fname := fmt.Sprintf("%s-%s.0.log", ROTATE_SIZE_FILE_PREFIX, getSizeString(l.rotateSize)) - for { - size, exist := getFileInfo(filepath.Join(l.logDir, fname)) - if !exist { - logFile, needCreateFile = fname, true - break - } - if exist && size+recordSize <= l.rotateSize { - logFile, needCreateFile = fname, false - break - } - fname = getNextFileName(fname) - } - } else { // check the file size to append to the existed file or create a new file - currentFile := filepath.Join(l.logDir, l.logFile) - size, exist := getFileInfo(currentFile) - if !exist { - logFile, needCreateFile = l.logFile, true - } else { - if size+recordSize > l.rotateSize { // size exceeded - logFile, needCreateFile = getNextFileName(l.logFile), true - } else { - logFile, needCreateFile = l.logFile, false - } - } - } - return logFile, needCreateFile -} - -func (l *logger) SetHandler(h Handler) { l.handler = h } - -func (l *logger) SetLogDir(dir string) { l.logDir = dir } - -func (l *logger) SetLogLevel(level Level) { l.levelThreshold = level } - -func (l *logger) SetLogFormat(format []string) { l.logFormat = format } - -func (l *logger) SetRotateType(rotate RotateStrategy) { l.rotateType = rotate } - -func (l *logger) SetRotateSize(size int64) { l.rotateSize = size } - -func (l *logger) Debug(msg ...interface{}) { l.logging(DEBUG, "%s\n", concat(msg...)) } - -func (l *logger) Debugln(msg ...interface{}) { l.logging(DEBUG, "%s\n", concat(msg...)) } - -func (l *logger) Debugf(f string, msg ...interface{}) { l.logging(DEBUG, f+"\n", msg...) } - -func (l *logger) Info(msg ...interface{}) { l.logging(INFO, "%s\n", concat(msg...)) } - -func (l *logger) Infoln(msg ...interface{}) { l.logging(INFO, "%s\n", concat(msg...)) } - -func (l *logger) Infof(f string, msg ...interface{}) { l.logging(INFO, f+"\n", msg...) } - -func (l *logger) Warn(msg ...interface{}) { l.logging(WARN, "%s\n", concat(msg...)) } - -func (l *logger) Warnln(msg ...interface{}) { l.logging(WARN, "%s\n", concat(msg...)) } - -func (l *logger) Warnf(f string, msg ...interface{}) { l.logging(WARN, f+"\n", msg...) } - -func (l *logger) Error(msg ...interface{}) { l.logging(ERROR, "%s\n", concat(msg...)) } - -func (l *logger) Errorln(msg ...interface{}) { l.logging(ERROR, "%s\n", concat(msg...)) } - -func (l *logger) Errorf(f string, msg ...interface{}) { l.logging(ERROR, f+"\n", msg...) } - -func (l *logger) Fatal(msg ...interface{}) { l.logging(FATAL, "%s\n", concat(msg...)) } - -func (l *logger) Fatalln(msg ...interface{}) { l.logging(FATAL, "%s\n", concat(msg...)) } - -func (l *logger) Fatalf(f string, msg ...interface{}) { l.logging(FATAL, f+"\n", msg...) } - -func (l *logger) Panic(msg ...interface{}) { - record := concat(msg...) - l.logging(PANIC, "%s\n", record) - panic(record) -} - -func (l *logger) Panicln(msg ...interface{}) { - record := concat(msg...) - l.logging(PANIC, "%s\n", record) - panic(record) -} - -func (l *logger) Panicf(format string, msg ...interface{}) { - record := fmt.Sprintf(format, msg...) - l.logging(PANIC, format+"\n", msg...) - panic(record) -} - -func (l *logger) Close() { - select { - case <-l.done: - return - default: - } - l.writerChan <- nil -} - -func NewLogger() *logger { - obj := &logger{ - writers: make(map[Handler]io.WriteCloser, 3), // now only support 3 kinds of handler - writerChan: make(chan *writerArgs, 100), - logFormat: gDefaultLogFormat, - levelThreshold: DEBUG, - handler: NONE, - done: make(chan bool), - } - // The backend writer goroutine to write each log record - go func() { - defer func() { - if e := recover(); e != nil { - fmt.Println(e) - } - }() - for { - select { - case <-obj.done: - return - case args := <-obj.writerChan: // wait until a record comes to log - if args == nil { - close(obj.done) - close(obj.writerChan) - return - } - obj.buildWriter(args.rotateArgs) - for _, w := range obj.writers { - fmt.Fprint(w, args.record) - } - } - } - }() - - return obj -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/util/log/util.go b/vendor/github.com/baidubce/bce-sdk-go/util/log/util.go deleted file mode 100644 index 23a6b39c..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/util/log/util.go +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// util.go - define the package-level default logger and functions for easily use. - -package log - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -// The global default logger object to perform logging in this package-level functions -var gDefaultLogger *logger - -func init() { - gDefaultLogger = NewLogger() -} - -// Helper functions -func getFileInfo(path string) (int64, bool) { - info, err := os.Stat(path) - if err != nil { - return -1, false - } else { - return info.Size(), true - } -} - -func getSizeString(size int64) string { - if size < 0 { - return fmt.Sprintf("%d", size) - } - if size < (1 << 10) { - return fmt.Sprintf("%dB", size) - } else if size < (1 << 20) { - return fmt.Sprintf("%dkB", size>>10) - } else if size < (1 << 30) { - return fmt.Sprintf("%dMB", size>>20) - } else if size < (1 << 40) { - return fmt.Sprintf("%dGB", size>>30) - } else { - return "SUPER-LARGE" - } -} - -func getNextFileName(nowFileName string) string { - pos1 := strings.Index(nowFileName, ".") - rest := nowFileName[pos1+1:] - pos2 := strings.Index(rest, ".") - num, _ := strconv.Atoi(rest[0:pos2]) - return fmt.Sprintf("%s.%d.log", nowFileName[0:pos1], num+1) -} - -func concat(msg ...interface{}) string { - buf := make([]string, 0, len(msg)) - for _, m := range msg { - buf = append(buf, fmt.Sprintf("%v", m)) - } - return strings.Join(buf, " ") -} - -// Export package-level functions for logging messages by using the default logger. It supports 3 -// kinds of interface which is similar to the standard package "fmt": with suffix of "ln", "f" or -// nothing. -func Debug(msg ...interface{}) { - gDefaultLogger.logging(DEBUG, "%s\n", concat(msg...)) -} - -func Debugln(msg ...interface{}) { - gDefaultLogger.logging(DEBUG, "%s\n", concat(msg...)) -} - -func Debugf(format string, msg ...interface{}) { - gDefaultLogger.logging(DEBUG, format+"\n", msg...) -} - -func Info(msg ...interface{}) { - gDefaultLogger.logging(INFO, "%s\n", concat(msg...)) -} - -func Infoln(msg ...interface{}) { - gDefaultLogger.logging(INFO, "%s\n", concat(msg...)) -} - -func Infof(format string, msg ...interface{}) { - gDefaultLogger.logging(INFO, format+"\n", msg...) -} - -func Warn(msg ...interface{}) { - gDefaultLogger.logging(WARN, "%s\n", concat(msg...)) -} - -func Warnln(msg ...interface{}) { - gDefaultLogger.logging(WARN, "%s\n", concat(msg...)) -} - -func Warnf(format string, msg ...interface{}) { - gDefaultLogger.logging(WARN, format+"\n", msg...) -} - -func Error(msg ...interface{}) { - gDefaultLogger.logging(ERROR, "%s\n", concat(msg...)) -} - -func Errorln(msg ...interface{}) { - gDefaultLogger.logging(ERROR, "%s\n", concat(msg...)) -} - -func Errorf(format string, msg ...interface{}) { - gDefaultLogger.logging(ERROR, format+"\n", msg...) -} - -func Fatal(msg ...interface{}) { - gDefaultLogger.logging(FATAL, "%s\n", concat(msg...)) -} - -func Fatalln(msg ...interface{}) { - gDefaultLogger.logging(FATAL, "%s\n", concat(msg...)) -} - -func Fatalf(format string, msg ...interface{}) { - gDefaultLogger.logging(FATAL, format+"\n", msg...) -} - -func Panic(msg ...interface{}) { - record := concat(msg...) - gDefaultLogger.logging(PANIC, "%s\n", record) - panic(record) -} - -func Panicln(msg ...interface{}) { - record := concat(msg...) - gDefaultLogger.logging(PANIC, "%s\n", record) - panic(record) -} - -func Panicf(format string, msg ...interface{}) { - record := fmt.Sprintf(format, msg...) - gDefaultLogger.logging(PANIC, format+"\n", msg...) - panic(record) -} - -func Close() { - gDefaultLogger.Close() -} - -// SetLogHandler - set the handler of the logger -// -// PARAMS: -// - Handler: the handler defined in this package, now just support STDOUT, STDERR, FILE -func SetLogHandler(h Handler) { - gDefaultLogger.handler = h -} - -// SetLogLevel - set the level threshold of the logger, only level equal to or bigger than this -// value will be logged. -// -// PARAMS: -// - Level: the level defined in this package, now support 6 levels. -func SetLogLevel(l Level) { - gDefaultLogger.levelThreshold = l -} - -// SetLogFormat - set the log component of each record when logging it. The default log format is -// {FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG}. -// -// PARAMS: -// - format: the format component array. -func SetLogFormat(format []string) { - gDefaultLogger.logFormat = format -} - -// SetLogDir - set the logging directory if logging to file. -// -// PARAMS: -// - dir: the logging directory -// RETURNS: -// - error: check the directory and try to make it, otherwise return the error. -func SetLogDir(dir string) error { - if _, err := os.Stat(dir); err != nil { - if os.IsNotExist(err) { - if mkErr := os.Mkdir(dir, os.ModePerm); mkErr != nil { - return mkErr - } - } else { - return err - } - } - gDefaultLogger.logDir = dir - return nil -} - -// SetRotateType - set the rotating strategy if logging to file. -// -// PARAMS: -// - RotateStrategy: the rotate strategy defined in this package, now support 5 strategy. -func SetRotateType(r RotateStrategy) { - gDefaultLogger.rotateType = r -} - -// SetRotateSize - set the rotating size if logging to file and set the strategy of size. -// -// PARAMS: -// - size: the rotating size -// RETURNS: -// - error: check the value and return any error if error occurs. -func SetRotateSize(size int64) error { - if size <= 0 { - return fmt.Errorf("%s", "rotate size should not be negative") - } - gDefaultLogger.rotateSize = size - return nil -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/util/string.go b/vendor/github.com/baidubce/bce-sdk-go/util/string.go deleted file mode 100644 index 3bb0b10d..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/util/string.go +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// string.go - define the string util function - -// Package util defines the common utilities including string and time. -package util - -import ( - "bytes" - "crypto/hmac" - "crypto/md5" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "fmt" - "io" -) - -func HmacSha256Hex(key, str_to_sign string) string { - hasher := hmac.New(sha256.New, []byte(key)) - hasher.Write([]byte(str_to_sign)) - return hex.EncodeToString(hasher.Sum(nil)) -} - -func CalculateContentMD5(data io.Reader, size int64) (string, error) { - hasher := md5.New() - n, err := io.CopyN(hasher, data, size) - if err != nil { - return "", fmt.Errorf("calculate content-md5 occurs error: %v", err) - } - if n != size { - return "", fmt.Errorf("calculate content-md5 writing size %d != size %d", n, size) - } - return base64.StdEncoding.EncodeToString(hasher.Sum(nil)), nil -} - -func UriEncode(uri string, encodeSlash bool) string { - var byte_buf bytes.Buffer - for _, b := range []byte(uri) { - if (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || - b == '-' || b == '_' || b == '.' || b == '~' || (b == '/' && !encodeSlash) { - byte_buf.WriteByte(b) - } else { - byte_buf.WriteString(fmt.Sprintf("%%%02X", b)) - } - } - return byte_buf.String() -} - -func NewUUID() string { - var buf [16]byte - for { - if _, err := rand.Read(buf[:]); err == nil { - break - } - } - buf[6] = (buf[6] & 0x0f) | (4 << 4) - buf[8] = (buf[8] & 0xbf) | 0x80 - - res := make([]byte, 36) - hex.Encode(res[0:8], buf[0:4]) - res[8] = '-' - hex.Encode(res[9:13], buf[4:6]) - res[13] = '-' - hex.Encode(res[14:18], buf[6:8]) - res[18] = '-' - hex.Encode(res[19:23], buf[8:10]) - res[23] = '-' - hex.Encode(res[24:], buf[10:]) - return string(res) -} - -func NewRequestId() string { - return NewUUID() -} diff --git a/vendor/github.com/baidubce/bce-sdk-go/util/time.go b/vendor/github.com/baidubce/bce-sdk-go/util/time.go deleted file mode 100644 index e9f9e3d1..00000000 --- a/vendor/github.com/baidubce/bce-sdk-go/util/time.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2017 Baidu, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - -// time.go - define the time utility functions for BCE - -package util - -import "time" - -const ( - RFC822Format = "Mon, 02 Jan 2006 15:04:05 MST" - ISO8601Format = "2006-01-02T15:04:05Z" -) - -func NowUTCSeconds() int64 { return time.Now().UTC().Unix() } - -func NowUTCNanoSeconds() int64 { return time.Now().UTC().UnixNano() } - -func FormatRFC822Date(timestamp_second int64) string { - tm := time.Unix(timestamp_second, 0).UTC() - return tm.Format(RFC822Format) -} - -func ParseRFC822Date(time_string string) (time.Time, error) { - return time.Parse(RFC822Format, time_string) -} - -func FormatISO8601Date(timestamp_second int64) string { - tm := time.Unix(timestamp_second, 0).UTC() - return tm.Format(ISO8601Format) -} - -func ParseISO8601Date(time_string string) (time.Time, error) { - return time.Parse(ISO8601Format, time_string) -} diff --git a/vendor/github.com/beorn7/perks/LICENSE b/vendor/github.com/beorn7/perks/LICENSE deleted file mode 100644 index 339177be..00000000 --- a/vendor/github.com/beorn7/perks/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (C) 2013 Blake Mizerany - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/beorn7/perks/quantile/exampledata.txt b/vendor/github.com/beorn7/perks/quantile/exampledata.txt deleted file mode 100644 index 1602287d..00000000 --- a/vendor/github.com/beorn7/perks/quantile/exampledata.txt +++ /dev/null @@ -1,2388 +0,0 @@ -8 -5 -26 -12 -5 -235 -13 -6 -28 -30 -3 -3 -3 -3 -5 -2 -33 -7 -2 -4 -7 -12 -14 -5 -8 -3 -10 -4 -5 -3 -6 -6 -209 -20 -3 -10 -14 -3 -4 -6 -8 -5 -11 -7 -3 -2 -3 -3 -212 -5 -222 -4 -10 -10 -5 -6 -3 -8 -3 -10 -254 -220 -2 -3 -5 -24 -5 -4 -222 -7 -3 -3 -223 -8 -15 -12 -14 -14 -3 -2 -2 -3 -13 -3 -11 -4 -4 -6 -5 -7 -13 -5 -3 -5 -2 -5 -3 -5 -2 -7 -15 -17 -14 -3 -6 -6 -3 -17 -5 -4 -7 -6 -4 -4 -8 -6 -8 -3 -9 -3 -6 -3 -4 -5 -3 -3 -660 -4 -6 -10 -3 -6 -3 -2 -5 -13 -2 -4 -4 -10 -4 -8 -4 -3 -7 -9 -9 -3 -10 -37 -3 -13 -4 -12 -3 -6 -10 -8 -5 -21 -2 -3 -8 -3 -2 -3 -3 -4 -12 -2 -4 -8 -8 -4 -3 -2 -20 -1 -6 -32 -2 -11 -6 -18 -3 -8 -11 -3 -212 -3 -4 -2 -6 -7 -12 -11 -3 -2 -16 -10 -6 -4 -6 -3 -2 -7 -3 -2 -2 -2 -2 -5 -6 -4 -3 -10 -3 -4 -6 -5 -3 -4 -4 -5 -6 -4 -3 -4 -4 -5 -7 -5 -5 -3 -2 -7 -2 -4 -12 -4 -5 -6 -2 -4 -4 -8 -4 -15 -13 -7 -16 -5 -3 -23 -5 -5 -7 -3 -2 -9 -8 -7 -5 -8 -11 -4 -10 -76 -4 -47 -4 -3 -2 -7 -4 -2 -3 -37 -10 -4 -2 -20 -5 -4 -4 -10 -10 -4 -3 -7 -23 -240 -7 -13 -5 -5 -3 -3 -2 -5 -4 -2 -8 -7 -19 -2 -23 -8 -7 -2 -5 -3 -8 -3 -8 -13 -5 -5 -5 -2 -3 -23 -4 -9 -8 -4 -3 -3 -5 -220 -2 -3 -4 -6 -14 -3 -53 -6 -2 -5 -18 -6 -3 -219 -6 -5 -2 -5 -3 -6 -5 -15 -4 -3 -17 -3 -2 -4 -7 -2 -3 -3 -4 -4 -3 -2 -664 -6 -3 -23 -5 -5 -16 -5 -8 -2 -4 -2 -24 -12 -3 -2 -3 -5 -8 -3 -5 -4 -3 -14 -3 -5 -8 -2 -3 -7 -9 -4 -2 -3 -6 -8 -4 -3 -4 -6 -5 -3 -3 -6 -3 -19 -4 -4 -6 -3 -6 -3 -5 -22 -5 -4 -4 -3 -8 -11 -4 -9 -7 -6 -13 -4 -4 -4 -6 -17 -9 -3 -3 -3 -4 -3 -221 -5 -11 -3 -4 -2 -12 -6 -3 -5 -7 -5 -7 -4 -9 -7 -14 -37 -19 -217 -16 -3 -5 -2 -2 -7 -19 -7 -6 -7 -4 -24 -5 -11 -4 -7 -7 -9 -13 -3 -4 -3 -6 -28 -4 -4 -5 -5 -2 -5 -6 -4 -4 -6 -10 -5 -4 -3 -2 -3 -3 -6 -5 -5 -4 -3 -2 -3 -7 -4 -6 -18 -16 -8 -16 -4 -5 -8 -6 -9 -13 -1545 -6 -215 -6 -5 -6 -3 -45 -31 -5 -2 -2 -4 -3 -3 -2 -5 -4 -3 -5 -7 -7 -4 -5 -8 -5 -4 -749 -2 -31 -9 -11 -2 -11 -5 -4 -4 -7 -9 -11 -4 -5 -4 -7 -3 -4 -6 -2 -15 -3 -4 -3 -4 -3 -5 -2 -13 -5 -5 -3 -3 -23 -4 -4 -5 -7 -4 -13 -2 -4 -3 -4 -2 -6 -2 -7 -3 -5 -5 -3 -29 -5 -4 -4 -3 -10 -2 -3 -79 -16 -6 -6 -7 -7 -3 -5 -5 -7 -4 -3 -7 -9 -5 -6 -5 -9 -6 -3 -6 -4 -17 -2 -10 -9 -3 -6 -2 -3 -21 -22 -5 -11 -4 -2 -17 -2 -224 -2 -14 -3 -4 -4 -2 -4 -4 -4 -4 -5 -3 -4 -4 -10 -2 -6 -3 -3 -5 -7 -2 -7 -5 -6 -3 -218 -2 -2 -5 -2 -6 -3 -5 -222 -14 -6 -33 -3 -2 -5 -3 -3 -3 -9 -5 -3 -3 -2 -7 -4 -3 -4 -3 -5 -6 -5 -26 -4 -13 -9 -7 -3 -221 -3 -3 -4 -4 -4 -4 -2 -18 -5 -3 -7 -9 -6 -8 -3 -10 -3 -11 -9 -5 -4 -17 -5 -5 -6 -6 -3 -2 -4 -12 -17 -6 -7 -218 -4 -2 -4 -10 -3 -5 -15 -3 -9 -4 -3 -3 -6 -29 -3 -3 -4 -5 -5 -3 -8 -5 -6 -6 -7 -5 -3 -5 -3 -29 -2 -31 -5 -15 -24 -16 -5 -207 -4 -3 -3 -2 -15 -4 -4 -13 -5 -5 -4 -6 -10 -2 -7 -8 -4 -6 -20 -5 -3 -4 -3 -12 -12 -5 -17 -7 -3 -3 -3 -6 -10 -3 -5 -25 -80 -4 -9 -3 -2 -11 -3 -3 -2 -3 -8 -7 -5 -5 -19 -5 -3 -3 -12 -11 -2 -6 -5 -5 -5 -3 -3 -3 -4 -209 -14 -3 -2 -5 -19 -4 -4 -3 -4 -14 -5 -6 -4 -13 -9 -7 -4 -7 -10 -2 -9 -5 -7 -2 -8 -4 -6 -5 -5 -222 -8 -7 -12 -5 -216 -3 -4 -4 -6 -3 -14 -8 -7 -13 -4 -3 -3 -3 -3 -17 -5 -4 -3 -33 -6 -6 -33 -7 -5 -3 -8 -7 -5 -2 -9 -4 -2 -233 -24 -7 -4 -8 -10 -3 -4 -15 -2 -16 -3 -3 -13 -12 -7 -5 -4 -207 -4 -2 -4 -27 -15 -2 -5 -2 -25 -6 -5 -5 -6 -13 -6 -18 -6 -4 -12 -225 -10 -7 -5 -2 -2 -11 -4 -14 -21 -8 -10 -3 -5 -4 -232 -2 -5 -5 -3 -7 -17 -11 -6 -6 -23 -4 -6 -3 -5 -4 -2 -17 -3 -6 -5 -8 -3 -2 -2 -14 -9 -4 -4 -2 -5 -5 -3 -7 -6 -12 -6 -10 -3 -6 -2 -2 -19 -5 -4 -4 -9 -2 -4 -13 -3 -5 -6 -3 -6 -5 -4 -9 -6 -3 -5 -7 -3 -6 -6 -4 -3 -10 -6 -3 -221 -3 -5 -3 -6 -4 -8 -5 -3 -6 -4 -4 -2 -54 -5 -6 -11 -3 -3 -4 -4 -4 -3 -7 -3 -11 -11 -7 -10 -6 -13 -223 -213 -15 -231 -7 -3 -7 -228 -2 -3 -4 -4 -5 -6 -7 -4 -13 -3 -4 -5 -3 -6 -4 -6 -7 -2 -4 -3 -4 -3 -3 -6 -3 -7 -3 -5 -18 -5 -6 -8 -10 -3 -3 -3 -2 -4 -2 -4 -4 -5 -6 -6 -4 -10 -13 -3 -12 -5 -12 -16 -8 -4 -19 -11 -2 -4 -5 -6 -8 -5 -6 -4 -18 -10 -4 -2 -216 -6 -6 -6 -2 -4 -12 -8 -3 -11 -5 -6 -14 -5 -3 -13 -4 -5 -4 -5 -3 -28 -6 -3 -7 -219 -3 -9 -7 -3 -10 -6 -3 -4 -19 -5 -7 -11 -6 -15 -19 -4 -13 -11 -3 -7 -5 -10 -2 -8 -11 -2 -6 -4 -6 -24 -6 -3 -3 -3 -3 -6 -18 -4 -11 -4 -2 -5 -10 -8 -3 -9 -5 -3 -4 -5 -6 -2 -5 -7 -4 -4 -14 -6 -4 -4 -5 -5 -7 -2 -4 -3 -7 -3 -3 -6 -4 -5 -4 -4 -4 -3 -3 -3 -3 -8 -14 -2 -3 -5 -3 -2 -4 -5 -3 -7 -3 -3 -18 -3 -4 -4 -5 -7 -3 -3 -3 -13 -5 -4 -8 -211 -5 -5 -3 -5 -2 -5 -4 -2 -655 -6 -3 -5 -11 -2 -5 -3 -12 -9 -15 -11 -5 -12 -217 -2 -6 -17 -3 -3 -207 -5 -5 -4 -5 -9 -3 -2 -8 -5 -4 -3 -2 -5 -12 -4 -14 -5 -4 -2 -13 -5 -8 -4 -225 -4 -3 -4 -5 -4 -3 -3 -6 -23 -9 -2 -6 -7 -233 -4 -4 -6 -18 -3 -4 -6 -3 -4 -4 -2 -3 -7 -4 -13 -227 -4 -3 -5 -4 -2 -12 -9 -17 -3 -7 -14 -6 -4 -5 -21 -4 -8 -9 -2 -9 -25 -16 -3 -6 -4 -7 -8 -5 -2 -3 -5 -4 -3 -3 -5 -3 -3 -3 -2 -3 -19 -2 -4 -3 -4 -2 -3 -4 -4 -2 -4 -3 -3 -3 -2 -6 -3 -17 -5 -6 -4 -3 -13 -5 -3 -3 -3 -4 -9 -4 -2 -14 -12 -4 -5 -24 -4 -3 -37 -12 -11 -21 -3 -4 -3 -13 -4 -2 -3 -15 -4 -11 -4 -4 -3 -8 -3 -4 -4 -12 -8 -5 -3 -3 -4 -2 -220 -3 -5 -223 -3 -3 -3 -10 -3 -15 -4 -241 -9 -7 -3 -6 -6 -23 -4 -13 -7 -3 -4 -7 -4 -9 -3 -3 -4 -10 -5 -5 -1 -5 -24 -2 -4 -5 -5 -6 -14 -3 -8 -2 -3 -5 -13 -13 -3 -5 -2 -3 -15 -3 -4 -2 -10 -4 -4 -4 -5 -5 -3 -5 -3 -4 -7 -4 -27 -3 -6 -4 -15 -3 -5 -6 -6 -5 -4 -8 -3 -9 -2 -6 -3 -4 -3 -7 -4 -18 -3 -11 -3 -3 -8 -9 -7 -24 -3 -219 -7 -10 -4 -5 -9 -12 -2 -5 -4 -4 -4 -3 -3 -19 -5 -8 -16 -8 -6 -22 -3 -23 -3 -242 -9 -4 -3 -3 -5 -7 -3 -3 -5 -8 -3 -7 -5 -14 -8 -10 -3 -4 -3 -7 -4 -6 -7 -4 -10 -4 -3 -11 -3 -7 -10 -3 -13 -6 -8 -12 -10 -5 -7 -9 -3 -4 -7 -7 -10 -8 -30 -9 -19 -4 -3 -19 -15 -4 -13 -3 -215 -223 -4 -7 -4 -8 -17 -16 -3 -7 -6 -5 -5 -4 -12 -3 -7 -4 -4 -13 -4 -5 -2 -5 -6 -5 -6 -6 -7 -10 -18 -23 -9 -3 -3 -6 -5 -2 -4 -2 -7 -3 -3 -2 -5 -5 -14 -10 -224 -6 -3 -4 -3 -7 -5 -9 -3 -6 -4 -2 -5 -11 -4 -3 -3 -2 -8 -4 -7 -4 -10 -7 -3 -3 -18 -18 -17 -3 -3 -3 -4 -5 -3 -3 -4 -12 -7 -3 -11 -13 -5 -4 -7 -13 -5 -4 -11 -3 -12 -3 -6 -4 -4 -21 -4 -6 -9 -5 -3 -10 -8 -4 -6 -4 -4 -6 -5 -4 -8 -6 -4 -6 -4 -4 -5 -9 -6 -3 -4 -2 -9 -3 -18 -2 -4 -3 -13 -3 -6 -6 -8 -7 -9 -3 -2 -16 -3 -4 -6 -3 -2 -33 -22 -14 -4 -9 -12 -4 -5 -6 -3 -23 -9 -4 -3 -5 -5 -3 -4 -5 -3 -5 -3 -10 -4 -5 -5 -8 -4 -4 -6 -8 -5 -4 -3 -4 -6 -3 -3 -3 -5 -9 -12 -6 -5 -9 -3 -5 -3 -2 -2 -2 -18 -3 -2 -21 -2 -5 -4 -6 -4 -5 -10 -3 -9 -3 -2 -10 -7 -3 -6 -6 -4 -4 -8 -12 -7 -3 -7 -3 -3 -9 -3 -4 -5 -4 -4 -5 -5 -10 -15 -4 -4 -14 -6 -227 -3 -14 -5 -216 -22 -5 -4 -2 -2 -6 -3 -4 -2 -9 -9 -4 -3 -28 -13 -11 -4 -5 -3 -3 -2 -3 -3 -5 -3 -4 -3 -5 -23 -26 -3 -4 -5 -6 -4 -6 -3 -5 -5 -3 -4 -3 -2 -2 -2 -7 -14 -3 -6 -7 -17 -2 -2 -15 -14 -16 -4 -6 -7 -13 -6 -4 -5 -6 -16 -3 -3 -28 -3 -6 -15 -3 -9 -2 -4 -6 -3 -3 -22 -4 -12 -6 -7 -2 -5 -4 -10 -3 -16 -6 -9 -2 -5 -12 -7 -5 -5 -5 -5 -2 -11 -9 -17 -4 -3 -11 -7 -3 -5 -15 -4 -3 -4 -211 -8 -7 -5 -4 -7 -6 -7 -6 -3 -6 -5 -6 -5 -3 -4 -4 -26 -4 -6 -10 -4 -4 -3 -2 -3 -3 -4 -5 -9 -3 -9 -4 -4 -5 -5 -8 -2 -4 -2 -3 -8 -4 -11 -19 -5 -8 -6 -3 -5 -6 -12 -3 -2 -4 -16 -12 -3 -4 -4 -8 -6 -5 -6 -6 -219 -8 -222 -6 -16 -3 -13 -19 -5 -4 -3 -11 -6 -10 -4 -7 -7 -12 -5 -3 -3 -5 -6 -10 -3 -8 -2 -5 -4 -7 -2 -4 -4 -2 -12 -9 -6 -4 -2 -40 -2 -4 -10 -4 -223 -4 -2 -20 -6 -7 -24 -5 -4 -5 -2 -20 -16 -6 -5 -13 -2 -3 -3 -19 -3 -2 -4 -5 -6 -7 -11 -12 -5 -6 -7 -7 -3 -5 -3 -5 -3 -14 -3 -4 -4 -2 -11 -1 -7 -3 -9 -6 -11 -12 -5 -8 -6 -221 -4 -2 -12 -4 -3 -15 -4 -5 -226 -7 -218 -7 -5 -4 -5 -18 -4 -5 -9 -4 -4 -2 -9 -18 -18 -9 -5 -6 -6 -3 -3 -7 -3 -5 -4 -4 -4 -12 -3 -6 -31 -5 -4 -7 -3 -6 -5 -6 -5 -11 -2 -2 -11 -11 -6 -7 -5 -8 -7 -10 -5 -23 -7 -4 -3 -5 -34 -2 -5 -23 -7 -3 -6 -8 -4 -4 -4 -2 -5 -3 -8 -5 -4 -8 -25 -2 -3 -17 -8 -3 -4 -8 -7 -3 -15 -6 -5 -7 -21 -9 -5 -6 -6 -5 -3 -2 -3 -10 -3 -6 -3 -14 -7 -4 -4 -8 -7 -8 -2 -6 -12 -4 -213 -6 -5 -21 -8 -2 -5 -23 -3 -11 -2 -3 -6 -25 -2 -3 -6 -7 -6 -6 -4 -4 -6 -3 -17 -9 -7 -6 -4 -3 -10 -7 -2 -3 -3 -3 -11 -8 -3 -7 -6 -4 -14 -36 -3 -4 -3 -3 -22 -13 -21 -4 -2 -7 -4 -4 -17 -15 -3 -7 -11 -2 -4 -7 -6 -209 -6 -3 -2 -2 -24 -4 -9 -4 -3 -3 -3 -29 -2 -2 -4 -3 -3 -5 -4 -6 -3 -3 -2 -4 diff --git a/vendor/github.com/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go deleted file mode 100644 index d7d14f8e..00000000 --- a/vendor/github.com/beorn7/perks/quantile/stream.go +++ /dev/null @@ -1,316 +0,0 @@ -// Package quantile computes approximate quantiles over an unbounded data -// stream within low memory and CPU bounds. -// -// A small amount of accuracy is traded to achieve the above properties. -// -// Multiple streams can be merged before calling Query to generate a single set -// of results. This is meaningful when the streams represent the same type of -// data. See Merge and Samples. -// -// For more detailed information about the algorithm used, see: -// -// Effective Computation of Biased Quantiles over Data Streams -// -// http://www.cs.rutgers.edu/~muthu/bquant.pdf -package quantile - -import ( - "math" - "sort" -) - -// Sample holds an observed value and meta information for compression. JSON -// tags have been added for convenience. -type Sample struct { - Value float64 `json:",string"` - Width float64 `json:",string"` - Delta float64 `json:",string"` -} - -// Samples represents a slice of samples. It implements sort.Interface. -type Samples []Sample - -func (a Samples) Len() int { return len(a) } -func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value } -func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -type invariant func(s *stream, r float64) float64 - -// NewLowBiased returns an initialized Stream for low-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the lower ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within (1±Epsilon)*Quantile. -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewLowBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * r - } - return newStream(ƒ) -} - -// NewHighBiased returns an initialized Stream for high-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the higher ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewHighBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * (s.n - r) - } - return newStream(ƒ) -} - -// NewTargeted returns an initialized Stream concerned with a particular set of -// quantile values that are supplied a priori. Knowing these a priori reduces -// space and computation time. The targets map maps the desired quantiles to -// their absolute errors, i.e. the true quantile of a value returned by a query -// is guaranteed to be within (Quantile±Epsilon). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. -func NewTargeted(targetMap map[float64]float64) *Stream { - // Convert map to slice to avoid slow iterations on a map. - // ƒ is called on the hot path, so converting the map to a slice - // beforehand results in significant CPU savings. - targets := targetMapToSlice(targetMap) - - ƒ := func(s *stream, r float64) float64 { - var m = math.MaxFloat64 - var f float64 - for _, t := range targets { - if t.quantile*s.n <= r { - f = (2 * t.epsilon * r) / t.quantile - } else { - f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile) - } - if f < m { - m = f - } - } - return m - } - return newStream(ƒ) -} - -type target struct { - quantile float64 - epsilon float64 -} - -func targetMapToSlice(targetMap map[float64]float64) []target { - targets := make([]target, 0, len(targetMap)) - - for quantile, epsilon := range targetMap { - t := target{ - quantile: quantile, - epsilon: epsilon, - } - targets = append(targets, t) - } - - return targets -} - -// Stream computes quantiles for a stream of float64s. It is not thread-safe by -// design. Take care when using across multiple goroutines. -type Stream struct { - *stream - b Samples - sorted bool -} - -func newStream(ƒ invariant) *Stream { - x := &stream{ƒ: ƒ} - return &Stream{x, make(Samples, 0, 500), true} -} - -// Insert inserts v into the stream. -func (s *Stream) Insert(v float64) { - s.insert(Sample{Value: v, Width: 1}) -} - -func (s *Stream) insert(sample Sample) { - s.b = append(s.b, sample) - s.sorted = false - if len(s.b) == cap(s.b) { - s.flush() - } -} - -// Query returns the computed qth percentiles value. If s was created with -// NewTargeted, and q is not in the set of quantiles provided a priori, Query -// will return an unspecified result. -func (s *Stream) Query(q float64) float64 { - if !s.flushed() { - // Fast path when there hasn't been enough data for a flush; - // this also yields better accuracy for small sets of data. - l := len(s.b) - if l == 0 { - return 0 - } - i := int(math.Ceil(float64(l) * q)) - if i > 0 { - i -= 1 - } - s.maybeSort() - return s.b[i].Value - } - s.flush() - return s.stream.query(q) -} - -// Merge merges samples into the underlying streams samples. This is handy when -// merging multiple streams from separate threads, database shards, etc. -// -// ATTENTION: This method is broken and does not yield correct results. The -// underlying algorithm is not capable of merging streams correctly. -func (s *Stream) Merge(samples Samples) { - sort.Sort(samples) - s.stream.merge(samples) -} - -// Reset reinitializes and clears the list reusing the samples buffer memory. -func (s *Stream) Reset() { - s.stream.reset() - s.b = s.b[:0] -} - -// Samples returns stream samples held by s. -func (s *Stream) Samples() Samples { - if !s.flushed() { - return s.b - } - s.flush() - return s.stream.samples() -} - -// Count returns the total number of samples observed in the stream -// since initialization. -func (s *Stream) Count() int { - return len(s.b) + s.stream.count() -} - -func (s *Stream) flush() { - s.maybeSort() - s.stream.merge(s.b) - s.b = s.b[:0] -} - -func (s *Stream) maybeSort() { - if !s.sorted { - s.sorted = true - sort.Sort(s.b) - } -} - -func (s *Stream) flushed() bool { - return len(s.stream.l) > 0 -} - -type stream struct { - n float64 - l []Sample - ƒ invariant -} - -func (s *stream) reset() { - s.l = s.l[:0] - s.n = 0 -} - -func (s *stream) insert(v float64) { - s.merge(Samples{{v, 1, 0}}) -} - -func (s *stream) merge(samples Samples) { - // TODO(beorn7): This tries to merge not only individual samples, but - // whole summaries. The paper doesn't mention merging summaries at - // all. Unittests show that the merging is inaccurate. Find out how to - // do merges properly. - var r float64 - i := 0 - for _, sample := range samples { - for ; i < len(s.l); i++ { - c := s.l[i] - if c.Value > sample.Value { - // Insert at position i. - s.l = append(s.l, Sample{}) - copy(s.l[i+1:], s.l[i:]) - s.l[i] = Sample{ - sample.Value, - sample.Width, - math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1), - // TODO(beorn7): How to calculate delta correctly? - } - i++ - goto inserted - } - r += c.Width - } - s.l = append(s.l, Sample{sample.Value, sample.Width, 0}) - i++ - inserted: - s.n += sample.Width - r += sample.Width - } - s.compress() -} - -func (s *stream) count() int { - return int(s.n) -} - -func (s *stream) query(q float64) float64 { - t := math.Ceil(q * s.n) - t += math.Ceil(s.ƒ(s, t) / 2) - p := s.l[0] - var r float64 - for _, c := range s.l[1:] { - r += p.Width - if r+c.Width+c.Delta > t { - return p.Value - } - p = c - } - return p.Value -} - -func (s *stream) compress() { - if len(s.l) < 2 { - return - } - x := s.l[len(s.l)-1] - xi := len(s.l) - 1 - r := s.n - 1 - x.Width - - for i := len(s.l) - 2; i >= 0; i-- { - c := s.l[i] - if c.Width+x.Width+x.Delta <= s.ƒ(s, r) { - x.Width += c.Width - s.l[xi] = x - // Remove element at i. - copy(s.l[i:], s.l[i+1:]) - s.l = s.l[:len(s.l)-1] - xi -= 1 - } else { - x = c - xi = i - } - r -= c.Width - } -} - -func (s *stream) samples() Samples { - samples := make(Samples, len(s.l)) - copy(samples, s.l) - return samples -} diff --git a/vendor/github.com/cespare/xxhash/v2/LICENSE.txt b/vendor/github.com/cespare/xxhash/v2/LICENSE.txt deleted file mode 100644 index 24b53065..00000000 --- a/vendor/github.com/cespare/xxhash/v2/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2016 Caleb Spare - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/cespare/xxhash/v2/README.md b/vendor/github.com/cespare/xxhash/v2/README.md deleted file mode 100644 index 792b4a60..00000000 --- a/vendor/github.com/cespare/xxhash/v2/README.md +++ /dev/null @@ -1,69 +0,0 @@ -# xxhash - -[![Go Reference](https://pkg.go.dev/badge/github.com/cespare/xxhash/v2.svg)](https://pkg.go.dev/github.com/cespare/xxhash/v2) -[![Test](https://github.com/cespare/xxhash/actions/workflows/test.yml/badge.svg)](https://github.com/cespare/xxhash/actions/workflows/test.yml) - -xxhash is a Go implementation of the 64-bit -[xxHash](http://cyan4973.github.io/xxHash/) algorithm, XXH64. This is a -high-quality hashing algorithm that is much faster than anything in the Go -standard library. - -This package provides a straightforward API: - -``` -func Sum64(b []byte) uint64 -func Sum64String(s string) uint64 -type Digest struct{ ... } - func New() *Digest -``` - -The `Digest` type implements hash.Hash64. Its key methods are: - -``` -func (*Digest) Write([]byte) (int, error) -func (*Digest) WriteString(string) (int, error) -func (*Digest) Sum64() uint64 -``` - -This implementation provides a fast pure-Go implementation and an even faster -assembly implementation for amd64. - -## Compatibility - -This package is in a module and the latest code is in version 2 of the module. -You need a version of Go with at least "minimal module compatibility" to use -github.com/cespare/xxhash/v2: - -* 1.9.7+ for Go 1.9 -* 1.10.3+ for Go 1.10 -* Go 1.11 or later - -I recommend using the latest release of Go. - -## Benchmarks - -Here are some quick benchmarks comparing the pure-Go and assembly -implementations of Sum64. - -| input size | purego | asm | -| --- | --- | --- | -| 5 B | 979.66 MB/s | 1291.17 MB/s | -| 100 B | 7475.26 MB/s | 7973.40 MB/s | -| 4 KB | 17573.46 MB/s | 17602.65 MB/s | -| 10 MB | 17131.46 MB/s | 17142.16 MB/s | - -These numbers were generated on Ubuntu 18.04 with an Intel i7-8700K CPU using -the following commands under Go 1.11.2: - -``` -$ go test -tags purego -benchtime 10s -bench '/xxhash,direct,bytes' -$ go test -benchtime 10s -bench '/xxhash,direct,bytes' -``` - -## Projects using this package - -- [InfluxDB](https://github.com/influxdata/influxdb) -- [Prometheus](https://github.com/prometheus/prometheus) -- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) -- [FreeCache](https://github.com/coocood/freecache) -- [FastCache](https://github.com/VictoriaMetrics/fastcache) diff --git a/vendor/github.com/cespare/xxhash/v2/go.mod b/vendor/github.com/cespare/xxhash/v2/go.mod deleted file mode 100644 index 49f67608..00000000 --- a/vendor/github.com/cespare/xxhash/v2/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/cespare/xxhash/v2 - -go 1.11 diff --git a/vendor/github.com/cespare/xxhash/v2/go.sum b/vendor/github.com/cespare/xxhash/v2/go.sum deleted file mode 100644 index e69de29b..00000000 diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash.go b/vendor/github.com/cespare/xxhash/v2/xxhash.go deleted file mode 100644 index 15c835d5..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash.go +++ /dev/null @@ -1,235 +0,0 @@ -// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described -// at http://cyan4973.github.io/xxHash/. -package xxhash - -import ( - "encoding/binary" - "errors" - "math/bits" -) - -const ( - prime1 uint64 = 11400714785074694791 - prime2 uint64 = 14029467366897019727 - prime3 uint64 = 1609587929392839161 - prime4 uint64 = 9650029242287828579 - prime5 uint64 = 2870177450012600261 -) - -// NOTE(caleb): I'm using both consts and vars of the primes. Using consts where -// possible in the Go code is worth a small (but measurable) performance boost -// by avoiding some MOVQs. Vars are needed for the asm and also are useful for -// convenience in the Go code in a few places where we need to intentionally -// avoid constant arithmetic (e.g., v1 := prime1 + prime2 fails because the -// result overflows a uint64). -var ( - prime1v = prime1 - prime2v = prime2 - prime3v = prime3 - prime4v = prime4 - prime5v = prime5 -) - -// Digest implements hash.Hash64. -type Digest struct { - v1 uint64 - v2 uint64 - v3 uint64 - v4 uint64 - total uint64 - mem [32]byte - n int // how much of mem is used -} - -// New creates a new Digest that computes the 64-bit xxHash algorithm. -func New() *Digest { - var d Digest - d.Reset() - return &d -} - -// Reset clears the Digest's state so that it can be reused. -func (d *Digest) Reset() { - d.v1 = prime1v + prime2 - d.v2 = prime2 - d.v3 = 0 - d.v4 = -prime1v - d.total = 0 - d.n = 0 -} - -// Size always returns 8 bytes. -func (d *Digest) Size() int { return 8 } - -// BlockSize always returns 32 bytes. -func (d *Digest) BlockSize() int { return 32 } - -// Write adds more data to d. It always returns len(b), nil. -func (d *Digest) Write(b []byte) (n int, err error) { - n = len(b) - d.total += uint64(n) - - if d.n+n < 32 { - // This new data doesn't even fill the current block. - copy(d.mem[d.n:], b) - d.n += n - return - } - - if d.n > 0 { - // Finish off the partial block. - copy(d.mem[d.n:], b) - d.v1 = round(d.v1, u64(d.mem[0:8])) - d.v2 = round(d.v2, u64(d.mem[8:16])) - d.v3 = round(d.v3, u64(d.mem[16:24])) - d.v4 = round(d.v4, u64(d.mem[24:32])) - b = b[32-d.n:] - d.n = 0 - } - - if len(b) >= 32 { - // One or more full blocks left. - nw := writeBlocks(d, b) - b = b[nw:] - } - - // Store any remaining partial block. - copy(d.mem[:], b) - d.n = len(b) - - return -} - -// Sum appends the current hash to b and returns the resulting slice. -func (d *Digest) Sum(b []byte) []byte { - s := d.Sum64() - return append( - b, - byte(s>>56), - byte(s>>48), - byte(s>>40), - byte(s>>32), - byte(s>>24), - byte(s>>16), - byte(s>>8), - byte(s), - ) -} - -// Sum64 returns the current hash. -func (d *Digest) Sum64() uint64 { - var h uint64 - - if d.total >= 32 { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = d.v3 + prime5 - } - - h += d.total - - i, end := 0, d.n - for ; i+8 <= end; i += 8 { - k1 := round(0, u64(d.mem[i:i+8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if i+4 <= end { - h ^= uint64(u32(d.mem[i:i+4])) * prime1 - h = rol23(h)*prime2 + prime3 - i += 4 - } - for i < end { - h ^= uint64(d.mem[i]) * prime5 - h = rol11(h) * prime1 - i++ - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -const ( - magic = "xxh\x06" - marshaledSize = len(magic) + 8*5 + 32 -) - -// MarshalBinary implements the encoding.BinaryMarshaler interface. -func (d *Digest) MarshalBinary() ([]byte, error) { - b := make([]byte, 0, marshaledSize) - b = append(b, magic...) - b = appendUint64(b, d.v1) - b = appendUint64(b, d.v2) - b = appendUint64(b, d.v3) - b = appendUint64(b, d.v4) - b = appendUint64(b, d.total) - b = append(b, d.mem[:d.n]...) - b = b[:len(b)+len(d.mem)-d.n] - return b, nil -} - -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. -func (d *Digest) UnmarshalBinary(b []byte) error { - if len(b) < len(magic) || string(b[:len(magic)]) != magic { - return errors.New("xxhash: invalid hash state identifier") - } - if len(b) != marshaledSize { - return errors.New("xxhash: invalid hash state size") - } - b = b[len(magic):] - b, d.v1 = consumeUint64(b) - b, d.v2 = consumeUint64(b) - b, d.v3 = consumeUint64(b) - b, d.v4 = consumeUint64(b) - b, d.total = consumeUint64(b) - copy(d.mem[:], b) - d.n = int(d.total % uint64(len(d.mem))) - return nil -} - -func appendUint64(b []byte, x uint64) []byte { - var a [8]byte - binary.LittleEndian.PutUint64(a[:], x) - return append(b, a[:]...) -} - -func consumeUint64(b []byte) ([]byte, uint64) { - x := u64(b) - return b[8:], x -} - -func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } -func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } - -func round(acc, input uint64) uint64 { - acc += input * prime2 - acc = rol31(acc) - acc *= prime1 - return acc -} - -func mergeRound(acc, val uint64) uint64 { - val = round(0, val) - acc ^= val - acc = acc*prime1 + prime4 - return acc -} - -func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } -func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } -func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } -func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } -func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } -func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } -func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } -func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.go b/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.go deleted file mode 100644 index ad14b807..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !appengine -// +build gc -// +build !purego - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -// -//go:noescape -func Sum64(b []byte) uint64 - -//go:noescape -func writeBlocks(d *Digest, b []byte) int diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s b/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s deleted file mode 100644 index be8db5bf..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s +++ /dev/null @@ -1,215 +0,0 @@ -// +build !appengine -// +build gc -// +build !purego - -#include "textflag.h" - -// Register allocation: -// AX h -// SI pointer to advance through b -// DX n -// BX loop end -// R8 v1, k1 -// R9 v2 -// R10 v3 -// R11 v4 -// R12 tmp -// R13 prime1v -// R14 prime2v -// DI prime4v - -// round reads from and advances the buffer pointer in SI. -// It assumes that R13 has prime1v and R14 has prime2v. -#define round(r) \ - MOVQ (SI), R12 \ - ADDQ $8, SI \ - IMULQ R14, R12 \ - ADDQ R12, r \ - ROLQ $31, r \ - IMULQ R13, r - -// mergeRound applies a merge round on the two registers acc and val. -// It assumes that R13 has prime1v, R14 has prime2v, and DI has prime4v. -#define mergeRound(acc, val) \ - IMULQ R14, val \ - ROLQ $31, val \ - IMULQ R13, val \ - XORQ val, acc \ - IMULQ R13, acc \ - ADDQ DI, acc - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT, $0-32 - // Load fixed primes. - MOVQ ·prime1v(SB), R13 - MOVQ ·prime2v(SB), R14 - MOVQ ·prime4v(SB), DI - - // Load slice. - MOVQ b_base+0(FP), SI - MOVQ b_len+8(FP), DX - LEAQ (SI)(DX*1), BX - - // The first loop limit will be len(b)-32. - SUBQ $32, BX - - // Check whether we have at least one block. - CMPQ DX, $32 - JLT noBlocks - - // Set up initial state (v1, v2, v3, v4). - MOVQ R13, R8 - ADDQ R14, R8 - MOVQ R14, R9 - XORQ R10, R10 - XORQ R11, R11 - SUBQ R13, R11 - - // Loop until SI > BX. -blockLoop: - round(R8) - round(R9) - round(R10) - round(R11) - - CMPQ SI, BX - JLE blockLoop - - MOVQ R8, AX - ROLQ $1, AX - MOVQ R9, R12 - ROLQ $7, R12 - ADDQ R12, AX - MOVQ R10, R12 - ROLQ $12, R12 - ADDQ R12, AX - MOVQ R11, R12 - ROLQ $18, R12 - ADDQ R12, AX - - mergeRound(AX, R8) - mergeRound(AX, R9) - mergeRound(AX, R10) - mergeRound(AX, R11) - - JMP afterBlocks - -noBlocks: - MOVQ ·prime5v(SB), AX - -afterBlocks: - ADDQ DX, AX - - // Right now BX has len(b)-32, and we want to loop until SI > len(b)-8. - ADDQ $24, BX - - CMPQ SI, BX - JG fourByte - -wordLoop: - // Calculate k1. - MOVQ (SI), R8 - ADDQ $8, SI - IMULQ R14, R8 - ROLQ $31, R8 - IMULQ R13, R8 - - XORQ R8, AX - ROLQ $27, AX - IMULQ R13, AX - ADDQ DI, AX - - CMPQ SI, BX - JLE wordLoop - -fourByte: - ADDQ $4, BX - CMPQ SI, BX - JG singles - - MOVL (SI), R8 - ADDQ $4, SI - IMULQ R13, R8 - XORQ R8, AX - - ROLQ $23, AX - IMULQ R14, AX - ADDQ ·prime3v(SB), AX - -singles: - ADDQ $4, BX - CMPQ SI, BX - JGE finalize - -singlesLoop: - MOVBQZX (SI), R12 - ADDQ $1, SI - IMULQ ·prime5v(SB), R12 - XORQ R12, AX - - ROLQ $11, AX - IMULQ R13, AX - - CMPQ SI, BX - JL singlesLoop - -finalize: - MOVQ AX, R12 - SHRQ $33, R12 - XORQ R12, AX - IMULQ R14, AX - MOVQ AX, R12 - SHRQ $29, R12 - XORQ R12, AX - IMULQ ·prime3v(SB), AX - MOVQ AX, R12 - SHRQ $32, R12 - XORQ R12, AX - - MOVQ AX, ret+24(FP) - RET - -// writeBlocks uses the same registers as above except that it uses AX to store -// the d pointer. - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT, $0-40 - // Load fixed primes needed for round. - MOVQ ·prime1v(SB), R13 - MOVQ ·prime2v(SB), R14 - - // Load slice. - MOVQ b_base+8(FP), SI - MOVQ b_len+16(FP), DX - LEAQ (SI)(DX*1), BX - SUBQ $32, BX - - // Load vN from d. - MOVQ d+0(FP), AX - MOVQ 0(AX), R8 // v1 - MOVQ 8(AX), R9 // v2 - MOVQ 16(AX), R10 // v3 - MOVQ 24(AX), R11 // v4 - - // We don't need to check the loop condition here; this function is - // always called with at least one block of data to process. -blockLoop: - round(R8) - round(R9) - round(R10) - round(R11) - - CMPQ SI, BX - JLE blockLoop - - // Copy vN back to d. - MOVQ R8, 0(AX) - MOVQ R9, 8(AX) - MOVQ R10, 16(AX) - MOVQ R11, 24(AX) - - // The number of bytes written is SI minus the old base pointer. - SUBQ b_base+8(FP), SI - MOVQ SI, ret+32(FP) - - RET diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_other.go b/vendor/github.com/cespare/xxhash/v2/xxhash_other.go deleted file mode 100644 index 4a5a8216..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_other.go +++ /dev/null @@ -1,76 +0,0 @@ -// +build !amd64 appengine !gc purego - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -func Sum64(b []byte) uint64 { - // A simpler version would be - // d := New() - // d.Write(b) - // return d.Sum64() - // but this is faster, particularly for small inputs. - - n := len(b) - var h uint64 - - if n >= 32 { - v1 := prime1v + prime2 - v2 := prime2 - v3 := uint64(0) - v4 := -prime1v - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = prime5 - } - - h += uint64(n) - - i, end := 0, len(b) - for ; i+8 <= end; i += 8 { - k1 := round(0, u64(b[i:i+8:len(b)])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if i+4 <= end { - h ^= uint64(u32(b[i:i+4:len(b)])) * prime1 - h = rol23(h)*prime2 + prime3 - i += 4 - } - for ; i < end; i++ { - h ^= uint64(b[i]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -func writeBlocks(d *Digest, b []byte) int { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - n := len(b) - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4 - return n - len(b) -} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go deleted file mode 100644 index fc9bea7a..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build appengine - -// This file contains the safe implementations of otherwise unsafe-using code. - -package xxhash - -// Sum64String computes the 64-bit xxHash digest of s. -func Sum64String(s string) uint64 { - return Sum64([]byte(s)) -} - -// WriteString adds more data to d. It always returns len(s), nil. -func (d *Digest) WriteString(s string) (n int, err error) { - return d.Write([]byte(s)) -} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go deleted file mode 100644 index 376e0ca2..00000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go +++ /dev/null @@ -1,57 +0,0 @@ -// +build !appengine - -// This file encapsulates usage of unsafe. -// xxhash_safe.go contains the safe implementations. - -package xxhash - -import ( - "unsafe" -) - -// In the future it's possible that compiler optimizations will make these -// XxxString functions unnecessary by realizing that calls such as -// Sum64([]byte(s)) don't need to copy s. See https://golang.org/issue/2205. -// If that happens, even if we keep these functions they can be replaced with -// the trivial safe code. - -// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is: -// -// var b []byte -// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) -// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data -// bh.Len = len(s) -// bh.Cap = len(s) -// -// Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough -// weight to this sequence of expressions that any function that uses it will -// not be inlined. Instead, the functions below use a different unsafe -// conversion designed to minimize the inliner weight and allow both to be -// inlined. There is also a test (TestInlining) which verifies that these are -// inlined. -// -// See https://github.com/golang/go/issues/42739 for discussion. - -// Sum64String computes the 64-bit xxHash digest of s. -// It may be faster than Sum64([]byte(s)) by avoiding a copy. -func Sum64String(s string) uint64 { - b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})) - return Sum64(b) -} - -// WriteString adds more data to d. It always returns len(s), nil. -// It may be faster than Write([]byte(s)) by avoiding a copy. -func (d *Digest) WriteString(s string) (n int, err error) { - d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))) - // d.Write always returns len(s), nil. - // Ignoring the return output and returning these fixed values buys a - // savings of 6 in the inliner's cost model. - return len(s), nil -} - -// sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout -// of the first two words is the same as the layout of a string. -type sliceHeader struct { - s string - cap int -} diff --git a/vendor/github.com/go-gomail/gomail/.travis.yml b/vendor/github.com/go-gomail/gomail/.travis.yml deleted file mode 100644 index 48915e73..00000000 --- a/vendor/github.com/go-gomail/gomail/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: - - 1.2 - - 1.3 - - 1.4 - - 1.5 - - 1.6 - - tip diff --git a/vendor/github.com/go-gomail/gomail/CHANGELOG.md b/vendor/github.com/go-gomail/gomail/CHANGELOG.md deleted file mode 100644 index a797ab4c..00000000 --- a/vendor/github.com/go-gomail/gomail/CHANGELOG.md +++ /dev/null @@ -1,20 +0,0 @@ -# Change Log -All notable changes to this project will be documented in this file. -This project adheres to [Semantic Versioning](http://semver.org/). - -## [2.0.0] - 2015-09-02 - -- Mailer has been removed. It has been replaced by Dialer and Sender. -- `File` type and the `CreateFile` and `OpenFile` functions have been removed. -- `Message.Attach` and `Message.Embed` have a new signature. -- `Message.GetBodyWriter` has been removed. Use `Message.AddAlternativeWriter` -instead. -- `Message.Export` has been removed. `Message.WriteTo` can be used instead. -- `Message.DelHeader` has been removed. -- The `Bcc` header field is no longer sent. It is far more simpler and -efficient: the same message is sent to all recipients instead of sending a -different email to each Bcc address. -- LoginAuth has been removed. `NewPlainDialer` now implements the LOGIN -authentication mechanism when needed. -- Go 1.2 is now required instead of Go 1.3. No external dependency are used when -using Go 1.5. diff --git a/vendor/github.com/go-gomail/gomail/CONTRIBUTING.md b/vendor/github.com/go-gomail/gomail/CONTRIBUTING.md deleted file mode 100644 index d5601c25..00000000 --- a/vendor/github.com/go-gomail/gomail/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -Thank you for contributing to Gomail! Here are a few guidelines: - -## Bugs - -If you think you found a bug, create an issue and supply the minimum amount -of code triggering the bug so it can be reproduced. - - -## Fixing a bug - -If you want to fix a bug, you can send a pull request. It should contains a -new test or update an existing one to cover that bug. - - -## New feature proposal - -If you think Gomail lacks a feature, you can open an issue or send a pull -request. I want to keep Gomail code and API as simple as possible so please -describe your needs so we can discuss whether this feature should be added to -Gomail or not. diff --git a/vendor/github.com/go-gomail/gomail/LICENSE b/vendor/github.com/go-gomail/gomail/LICENSE deleted file mode 100644 index 5f5c12af..00000000 --- a/vendor/github.com/go-gomail/gomail/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Alexandre Cesaro - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/go-gomail/gomail/README.md b/vendor/github.com/go-gomail/gomail/README.md deleted file mode 100644 index b3be9e14..00000000 --- a/vendor/github.com/go-gomail/gomail/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# Gomail -[![Build Status](https://travis-ci.org/go-gomail/gomail.svg?branch=v2)](https://travis-ci.org/go-gomail/gomail) [![Code Coverage](http://gocover.io/_badge/gopkg.in/gomail.v2)](http://gocover.io/gopkg.in/gomail.v2) [![Documentation](https://godoc.org/gopkg.in/gomail.v2?status.svg)](https://godoc.org/gopkg.in/gomail.v2) - -## Introduction - -Gomail is a simple and efficient package to send emails. It is well tested and -documented. - -Gomail can only send emails using an SMTP server. But the API is flexible and it -is easy to implement other methods for sending emails using a local Postfix, an -API, etc. - -It is versioned using [gopkg.in](https://gopkg.in) so I promise -there will never be backward incompatible changes within each version. - -It requires Go 1.2 or newer. With Go 1.5, no external dependencies are used. - - -## Features - -Gomail supports: -- Attachments -- Embedded images -- HTML and text templates -- Automatic encoding of special characters -- SSL and TLS -- Sending multiple emails with the same SMTP connection - - -## Documentation - -https://godoc.org/gopkg.in/gomail.v2 - - -## Download - - go get gopkg.in/gomail.v2 - - -## Examples - -See the [examples in the documentation](https://godoc.org/gopkg.in/gomail.v2#example-package). - - -## FAQ - -### x509: certificate signed by unknown authority - -If you get this error it means the certificate used by the SMTP server is not -considered valid by the client running Gomail. As a quick workaround you can -bypass the verification of the server's certificate chain and host name by using -`SetTLSConfig`: - - package main - - import ( - "crypto/tls" - - "gopkg.in/gomail.v2" - ) - - func main() { - d := gomail.NewDialer("smtp.example.com", 587, "user", "123456") - d.TLSConfig = &tls.Config{InsecureSkipVerify: true} - - // Send emails using d. - } - -Note, however, that this is insecure and should not be used in production. - - -## Contribute - -Contributions are more than welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for -more info. - - -## Change log - -See [CHANGELOG.md](CHANGELOG.md). - - -## License - -[MIT](LICENSE) - - -## Contact - -You can ask questions on the [Gomail -thread](https://groups.google.com/d/topic/golang-nuts/jMxZHzvvEVg/discussion) -in the Go mailing-list. diff --git a/vendor/github.com/go-gomail/gomail/auth.go b/vendor/github.com/go-gomail/gomail/auth.go deleted file mode 100644 index d28b83ab..00000000 --- a/vendor/github.com/go-gomail/gomail/auth.go +++ /dev/null @@ -1,49 +0,0 @@ -package gomail - -import ( - "bytes" - "errors" - "fmt" - "net/smtp" -) - -// loginAuth is an smtp.Auth that implements the LOGIN authentication mechanism. -type loginAuth struct { - username string - password string - host string -} - -func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { - if !server.TLS { - advertised := false - for _, mechanism := range server.Auth { - if mechanism == "LOGIN" { - advertised = true - break - } - } - if !advertised { - return "", nil, errors.New("gomail: unencrypted connection") - } - } - if server.Name != a.host { - return "", nil, errors.New("gomail: wrong host name") - } - return "LOGIN", nil, nil -} - -func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { - if !more { - return nil, nil - } - - switch { - case bytes.Equal(fromServer, []byte("Username:")): - return []byte(a.username), nil - case bytes.Equal(fromServer, []byte("Password:")): - return []byte(a.password), nil - default: - return nil, fmt.Errorf("gomail: unexpected server challenge: %s", fromServer) - } -} diff --git a/vendor/github.com/go-gomail/gomail/doc.go b/vendor/github.com/go-gomail/gomail/doc.go deleted file mode 100644 index a8f5091f..00000000 --- a/vendor/github.com/go-gomail/gomail/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package gomail provides a simple interface to compose emails and to mail them -// efficiently. -// -// More info on Github: https://github.com/go-gomail/gomail -package gomail diff --git a/vendor/github.com/go-gomail/gomail/message.go b/vendor/github.com/go-gomail/gomail/message.go deleted file mode 100644 index 4bffb1e7..00000000 --- a/vendor/github.com/go-gomail/gomail/message.go +++ /dev/null @@ -1,322 +0,0 @@ -package gomail - -import ( - "bytes" - "io" - "os" - "path/filepath" - "time" -) - -// Message represents an email. -type Message struct { - header header - parts []*part - attachments []*file - embedded []*file - charset string - encoding Encoding - hEncoder mimeEncoder - buf bytes.Buffer -} - -type header map[string][]string - -type part struct { - contentType string - copier func(io.Writer) error - encoding Encoding -} - -// NewMessage creates a new message. It uses UTF-8 and quoted-printable encoding -// by default. -func NewMessage(settings ...MessageSetting) *Message { - m := &Message{ - header: make(header), - charset: "UTF-8", - encoding: QuotedPrintable, - } - - m.applySettings(settings) - - if m.encoding == Base64 { - m.hEncoder = bEncoding - } else { - m.hEncoder = qEncoding - } - - return m -} - -// Reset resets the message so it can be reused. The message keeps its previous -// settings so it is in the same state that after a call to NewMessage. -func (m *Message) Reset() { - for k := range m.header { - delete(m.header, k) - } - m.parts = nil - m.attachments = nil - m.embedded = nil -} - -func (m *Message) applySettings(settings []MessageSetting) { - for _, s := range settings { - s(m) - } -} - -// A MessageSetting can be used as an argument in NewMessage to configure an -// email. -type MessageSetting func(m *Message) - -// SetCharset is a message setting to set the charset of the email. -func SetCharset(charset string) MessageSetting { - return func(m *Message) { - m.charset = charset - } -} - -// SetEncoding is a message setting to set the encoding of the email. -func SetEncoding(enc Encoding) MessageSetting { - return func(m *Message) { - m.encoding = enc - } -} - -// Encoding represents a MIME encoding scheme like quoted-printable or base64. -type Encoding string - -const ( - // QuotedPrintable represents the quoted-printable encoding as defined in - // RFC 2045. - QuotedPrintable Encoding = "quoted-printable" - // Base64 represents the base64 encoding as defined in RFC 2045. - Base64 Encoding = "base64" - // Unencoded can be used to avoid encoding the body of an email. The headers - // will still be encoded using quoted-printable encoding. - Unencoded Encoding = "8bit" -) - -// SetHeader sets a value to the given header field. -func (m *Message) SetHeader(field string, value ...string) { - m.encodeHeader(value) - m.header[field] = value -} - -func (m *Message) encodeHeader(values []string) { - for i := range values { - values[i] = m.encodeString(values[i]) - } -} - -func (m *Message) encodeString(value string) string { - return m.hEncoder.Encode(m.charset, value) -} - -// SetHeaders sets the message headers. -func (m *Message) SetHeaders(h map[string][]string) { - for k, v := range h { - m.SetHeader(k, v...) - } -} - -// SetAddressHeader sets an address to the given header field. -func (m *Message) SetAddressHeader(field, address, name string) { - m.header[field] = []string{m.FormatAddress(address, name)} -} - -// FormatAddress formats an address and a name as a valid RFC 5322 address. -func (m *Message) FormatAddress(address, name string) string { - if name == "" { - return address - } - - enc := m.encodeString(name) - if enc == name { - m.buf.WriteByte('"') - for i := 0; i < len(name); i++ { - b := name[i] - if b == '\\' || b == '"' { - m.buf.WriteByte('\\') - } - m.buf.WriteByte(b) - } - m.buf.WriteByte('"') - } else if hasSpecials(name) { - m.buf.WriteString(bEncoding.Encode(m.charset, name)) - } else { - m.buf.WriteString(enc) - } - m.buf.WriteString(" <") - m.buf.WriteString(address) - m.buf.WriteByte('>') - - addr := m.buf.String() - m.buf.Reset() - return addr -} - -func hasSpecials(text string) bool { - for i := 0; i < len(text); i++ { - switch c := text[i]; c { - case '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"': - return true - } - } - - return false -} - -// SetDateHeader sets a date to the given header field. -func (m *Message) SetDateHeader(field string, date time.Time) { - m.header[field] = []string{m.FormatDate(date)} -} - -// FormatDate formats a date as a valid RFC 5322 date. -func (m *Message) FormatDate(date time.Time) string { - return date.Format(time.RFC1123Z) -} - -// GetHeader gets a header field. -func (m *Message) GetHeader(field string) []string { - return m.header[field] -} - -// SetBody sets the body of the message. It replaces any content previously set -// by SetBody, AddAlternative or AddAlternativeWriter. -func (m *Message) SetBody(contentType, body string, settings ...PartSetting) { - m.parts = []*part{m.newPart(contentType, newCopier(body), settings)} -} - -// AddAlternative adds an alternative part to the message. -// -// It is commonly used to send HTML emails that default to the plain text -// version for backward compatibility. AddAlternative appends the new part to -// the end of the message. So the plain text part should be added before the -// HTML part. See http://en.wikipedia.org/wiki/MIME#Alternative -func (m *Message) AddAlternative(contentType, body string, settings ...PartSetting) { - m.AddAlternativeWriter(contentType, newCopier(body), settings...) -} - -func newCopier(s string) func(io.Writer) error { - return func(w io.Writer) error { - _, err := io.WriteString(w, s) - return err - } -} - -// AddAlternativeWriter adds an alternative part to the message. It can be -// useful with the text/template or html/template packages. -func (m *Message) AddAlternativeWriter(contentType string, f func(io.Writer) error, settings ...PartSetting) { - m.parts = append(m.parts, m.newPart(contentType, f, settings)) -} - -func (m *Message) newPart(contentType string, f func(io.Writer) error, settings []PartSetting) *part { - p := &part{ - contentType: contentType, - copier: f, - encoding: m.encoding, - } - - for _, s := range settings { - s(p) - } - - return p -} - -// A PartSetting can be used as an argument in Message.SetBody, -// Message.AddAlternative or Message.AddAlternativeWriter to configure the part -// added to a message. -type PartSetting func(*part) - -// SetPartEncoding sets the encoding of the part added to the message. By -// default, parts use the same encoding than the message. -func SetPartEncoding(e Encoding) PartSetting { - return PartSetting(func(p *part) { - p.encoding = e - }) -} - -type file struct { - Name string - Header map[string][]string - CopyFunc func(w io.Writer) error -} - -func (f *file) setHeader(field, value string) { - f.Header[field] = []string{value} -} - -// A FileSetting can be used as an argument in Message.Attach or Message.Embed. -type FileSetting func(*file) - -// SetHeader is a file setting to set the MIME header of the message part that -// contains the file content. -// -// Mandatory headers are automatically added if they are not set when sending -// the email. -func SetHeader(h map[string][]string) FileSetting { - return func(f *file) { - for k, v := range h { - f.Header[k] = v - } - } -} - -// Rename is a file setting to set the name of the attachment if the name is -// different than the filename on disk. -func Rename(name string) FileSetting { - return func(f *file) { - f.Name = name - } -} - -// SetCopyFunc is a file setting to replace the function that runs when the -// message is sent. It should copy the content of the file to the io.Writer. -// -// The default copy function opens the file with the given filename, and copy -// its content to the io.Writer. -func SetCopyFunc(f func(io.Writer) error) FileSetting { - return func(fi *file) { - fi.CopyFunc = f - } -} - -func (m *Message) appendFile(list []*file, name string, settings []FileSetting) []*file { - f := &file{ - Name: filepath.Base(name), - Header: make(map[string][]string), - CopyFunc: func(w io.Writer) error { - h, err := os.Open(name) - if err != nil { - return err - } - if _, err := io.Copy(w, h); err != nil { - h.Close() - return err - } - return h.Close() - }, - } - - for _, s := range settings { - s(f) - } - - if list == nil { - return []*file{f} - } - - return append(list, f) -} - -// Attach attaches the files to the email. -func (m *Message) Attach(filename string, settings ...FileSetting) { - m.attachments = m.appendFile(m.attachments, filename, settings) -} - -// Embed embeds the images to the email. -func (m *Message) Embed(filename string, settings ...FileSetting) { - m.embedded = m.appendFile(m.embedded, filename, settings) -} diff --git a/vendor/github.com/go-gomail/gomail/mime.go b/vendor/github.com/go-gomail/gomail/mime.go deleted file mode 100644 index 194d4a76..00000000 --- a/vendor/github.com/go-gomail/gomail/mime.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build go1.5 - -package gomail - -import ( - "mime" - "mime/quotedprintable" - "strings" -) - -var newQPWriter = quotedprintable.NewWriter - -type mimeEncoder struct { - mime.WordEncoder -} - -var ( - bEncoding = mimeEncoder{mime.BEncoding} - qEncoding = mimeEncoder{mime.QEncoding} - lastIndexByte = strings.LastIndexByte -) diff --git a/vendor/github.com/go-gomail/gomail/mime_go14.go b/vendor/github.com/go-gomail/gomail/mime_go14.go deleted file mode 100644 index 3dc26aa2..00000000 --- a/vendor/github.com/go-gomail/gomail/mime_go14.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build !go1.5 - -package gomail - -import "gopkg.in/alexcesaro/quotedprintable.v3" - -var newQPWriter = quotedprintable.NewWriter - -type mimeEncoder struct { - quotedprintable.WordEncoder -} - -var ( - bEncoding = mimeEncoder{quotedprintable.BEncoding} - qEncoding = mimeEncoder{quotedprintable.QEncoding} - lastIndexByte = func(s string, c byte) int { - for i := len(s) - 1; i >= 0; i-- { - - if s[i] == c { - return i - } - } - return -1 - } -) diff --git a/vendor/github.com/go-gomail/gomail/send.go b/vendor/github.com/go-gomail/gomail/send.go deleted file mode 100644 index 9115ebe7..00000000 --- a/vendor/github.com/go-gomail/gomail/send.go +++ /dev/null @@ -1,116 +0,0 @@ -package gomail - -import ( - "errors" - "fmt" - "io" - "net/mail" -) - -// Sender is the interface that wraps the Send method. -// -// Send sends an email to the given addresses. -type Sender interface { - Send(from string, to []string, msg io.WriterTo) error -} - -// SendCloser is the interface that groups the Send and Close methods. -type SendCloser interface { - Sender - Close() error -} - -// A SendFunc is a function that sends emails to the given addresses. -// -// The SendFunc type is an adapter to allow the use of ordinary functions as -// email senders. If f is a function with the appropriate signature, SendFunc(f) -// is a Sender object that calls f. -type SendFunc func(from string, to []string, msg io.WriterTo) error - -// Send calls f(from, to, msg). -func (f SendFunc) Send(from string, to []string, msg io.WriterTo) error { - return f(from, to, msg) -} - -// Send sends emails using the given Sender. -func Send(s Sender, msg ...*Message) error { - for i, m := range msg { - if err := send(s, m); err != nil { - return fmt.Errorf("gomail: could not send email %d: %v", i+1, err) - } - } - - return nil -} - -func send(s Sender, m *Message) error { - from, err := m.getFrom() - if err != nil { - return err - } - - to, err := m.getRecipients() - if err != nil { - return err - } - - if err := s.Send(from, to, m); err != nil { - return err - } - - return nil -} - -func (m *Message) getFrom() (string, error) { - from := m.header["Sender"] - if len(from) == 0 { - from = m.header["From"] - if len(from) == 0 { - return "", errors.New(`gomail: invalid message, "From" field is absent`) - } - } - - return parseAddress(from[0]) -} - -func (m *Message) getRecipients() ([]string, error) { - n := 0 - for _, field := range []string{"To", "Cc", "Bcc"} { - if addresses, ok := m.header[field]; ok { - n += len(addresses) - } - } - list := make([]string, 0, n) - - for _, field := range []string{"To", "Cc", "Bcc"} { - if addresses, ok := m.header[field]; ok { - for _, a := range addresses { - addr, err := parseAddress(a) - if err != nil { - return nil, err - } - list = addAddress(list, addr) - } - } - } - - return list, nil -} - -func addAddress(list []string, addr string) []string { - for _, a := range list { - if addr == a { - return list - } - } - - return append(list, addr) -} - -func parseAddress(field string) (string, error) { - addr, err := mail.ParseAddress(field) - if err != nil { - return "", fmt.Errorf("gomail: invalid address %q: %v", field, err) - } - return addr.Address, nil -} diff --git a/vendor/github.com/go-gomail/gomail/smtp.go b/vendor/github.com/go-gomail/gomail/smtp.go deleted file mode 100644 index 2aa49c8b..00000000 --- a/vendor/github.com/go-gomail/gomail/smtp.go +++ /dev/null @@ -1,202 +0,0 @@ -package gomail - -import ( - "crypto/tls" - "fmt" - "io" - "net" - "net/smtp" - "strings" - "time" -) - -// A Dialer is a dialer to an SMTP server. -type Dialer struct { - // Host represents the host of the SMTP server. - Host string - // Port represents the port of the SMTP server. - Port int - // Username is the username to use to authenticate to the SMTP server. - Username string - // Password is the password to use to authenticate to the SMTP server. - Password string - // Auth represents the authentication mechanism used to authenticate to the - // SMTP server. - Auth smtp.Auth - // SSL defines whether an SSL connection is used. It should be false in - // most cases since the authentication mechanism should use the STARTTLS - // extension instead. - SSL bool - // TSLConfig represents the TLS configuration used for the TLS (when the - // STARTTLS extension is used) or SSL connection. - TLSConfig *tls.Config - // LocalName is the hostname sent to the SMTP server with the HELO command. - // By default, "localhost" is sent. - LocalName string -} - -// NewDialer returns a new SMTP Dialer. The given parameters are used to connect -// to the SMTP server. -func NewDialer(host string, port int, username, password string) *Dialer { - return &Dialer{ - Host: host, - Port: port, - Username: username, - Password: password, - SSL: port == 465, - } -} - -// NewPlainDialer returns a new SMTP Dialer. The given parameters are used to -// connect to the SMTP server. -// -// Deprecated: Use NewDialer instead. -func NewPlainDialer(host string, port int, username, password string) *Dialer { - return NewDialer(host, port, username, password) -} - -// Dial dials and authenticates to an SMTP server. The returned SendCloser -// should be closed when done using it. -func (d *Dialer) Dial() (SendCloser, error) { - conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second) - if err != nil { - return nil, err - } - - if d.SSL { - conn = tlsClient(conn, d.tlsConfig()) - } - - c, err := smtpNewClient(conn, d.Host) - if err != nil { - return nil, err - } - - if d.LocalName != "" { - if err := c.Hello(d.LocalName); err != nil { - return nil, err - } - } - - if !d.SSL { - if ok, _ := c.Extension("STARTTLS"); ok { - if err := c.StartTLS(d.tlsConfig()); err != nil { - c.Close() - return nil, err - } - } - } - - if d.Auth == nil && d.Username != "" { - if ok, auths := c.Extension("AUTH"); ok { - if strings.Contains(auths, "CRAM-MD5") { - d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password) - } else if strings.Contains(auths, "LOGIN") && - !strings.Contains(auths, "PLAIN") { - d.Auth = &loginAuth{ - username: d.Username, - password: d.Password, - host: d.Host, - } - } else { - d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host) - } - } - } - - if d.Auth != nil { - if err = c.Auth(d.Auth); err != nil { - c.Close() - return nil, err - } - } - - return &smtpSender{c, d}, nil -} - -func (d *Dialer) tlsConfig() *tls.Config { - if d.TLSConfig == nil { - return &tls.Config{ServerName: d.Host} - } - return d.TLSConfig -} - -func addr(host string, port int) string { - return fmt.Sprintf("%s:%d", host, port) -} - -// DialAndSend opens a connection to the SMTP server, sends the given emails and -// closes the connection. -func (d *Dialer) DialAndSend(m ...*Message) error { - s, err := d.Dial() - if err != nil { - return err - } - defer s.Close() - - return Send(s, m...) -} - -type smtpSender struct { - smtpClient - d *Dialer -} - -func (c *smtpSender) Send(from string, to []string, msg io.WriterTo) error { - if err := c.Mail(from); err != nil { - if err == io.EOF { - // This is probably due to a timeout, so reconnect and try again. - sc, derr := c.d.Dial() - if derr == nil { - if s, ok := sc.(*smtpSender); ok { - *c = *s - return c.Send(from, to, msg) - } - } - } - return err - } - - for _, addr := range to { - if err := c.Rcpt(addr); err != nil { - return err - } - } - - w, err := c.Data() - if err != nil { - return err - } - - if _, err = msg.WriteTo(w); err != nil { - w.Close() - return err - } - - return w.Close() -} - -func (c *smtpSender) Close() error { - return c.Quit() -} - -// Stubbed out for tests. -var ( - netDialTimeout = net.DialTimeout - tlsClient = tls.Client - smtpNewClient = func(conn net.Conn, host string) (smtpClient, error) { - return smtp.NewClient(conn, host) - } -) - -type smtpClient interface { - Hello(string) error - Extension(string) (bool, string) - StartTLS(*tls.Config) error - Auth(smtp.Auth) error - Mail(string) error - Rcpt(string) error - Data() (io.WriteCloser, error) - Quit() error - Close() error -} diff --git a/vendor/github.com/go-gomail/gomail/writeto.go b/vendor/github.com/go-gomail/gomail/writeto.go deleted file mode 100644 index 9fb6b86e..00000000 --- a/vendor/github.com/go-gomail/gomail/writeto.go +++ /dev/null @@ -1,306 +0,0 @@ -package gomail - -import ( - "encoding/base64" - "errors" - "io" - "mime" - "mime/multipart" - "path/filepath" - "strings" - "time" -) - -// WriteTo implements io.WriterTo. It dumps the whole message into w. -func (m *Message) WriteTo(w io.Writer) (int64, error) { - mw := &messageWriter{w: w} - mw.writeMessage(m) - return mw.n, mw.err -} - -func (w *messageWriter) writeMessage(m *Message) { - if _, ok := m.header["Mime-Version"]; !ok { - w.writeString("Mime-Version: 1.0\r\n") - } - if _, ok := m.header["Date"]; !ok { - w.writeHeader("Date", m.FormatDate(now())) - } - w.writeHeaders(m.header) - - if m.hasMixedPart() { - w.openMultipart("mixed") - } - - if m.hasRelatedPart() { - w.openMultipart("related") - } - - if m.hasAlternativePart() { - w.openMultipart("alternative") - } - for _, part := range m.parts { - w.writePart(part, m.charset) - } - if m.hasAlternativePart() { - w.closeMultipart() - } - - w.addFiles(m.embedded, false) - if m.hasRelatedPart() { - w.closeMultipart() - } - - w.addFiles(m.attachments, true) - if m.hasMixedPart() { - w.closeMultipart() - } -} - -func (m *Message) hasMixedPart() bool { - return (len(m.parts) > 0 && len(m.attachments) > 0) || len(m.attachments) > 1 -} - -func (m *Message) hasRelatedPart() bool { - return (len(m.parts) > 0 && len(m.embedded) > 0) || len(m.embedded) > 1 -} - -func (m *Message) hasAlternativePart() bool { - return len(m.parts) > 1 -} - -type messageWriter struct { - w io.Writer - n int64 - writers [3]*multipart.Writer - partWriter io.Writer - depth uint8 - err error -} - -func (w *messageWriter) openMultipart(mimeType string) { - mw := multipart.NewWriter(w) - contentType := "multipart/" + mimeType + ";\r\n boundary=" + mw.Boundary() - w.writers[w.depth] = mw - - if w.depth == 0 { - w.writeHeader("Content-Type", contentType) - w.writeString("\r\n") - } else { - w.createPart(map[string][]string{ - "Content-Type": {contentType}, - }) - } - w.depth++ -} - -func (w *messageWriter) createPart(h map[string][]string) { - w.partWriter, w.err = w.writers[w.depth-1].CreatePart(h) -} - -func (w *messageWriter) closeMultipart() { - if w.depth > 0 { - w.writers[w.depth-1].Close() - w.depth-- - } -} - -func (w *messageWriter) writePart(p *part, charset string) { - w.writeHeaders(map[string][]string{ - "Content-Type": {p.contentType + "; charset=" + charset}, - "Content-Transfer-Encoding": {string(p.encoding)}, - }) - w.writeBody(p.copier, p.encoding) -} - -func (w *messageWriter) addFiles(files []*file, isAttachment bool) { - for _, f := range files { - if _, ok := f.Header["Content-Type"]; !ok { - mediaType := mime.TypeByExtension(filepath.Ext(f.Name)) - if mediaType == "" { - mediaType = "application/octet-stream" - } - f.setHeader("Content-Type", mediaType+`; name="`+f.Name+`"`) - } - - if _, ok := f.Header["Content-Transfer-Encoding"]; !ok { - f.setHeader("Content-Transfer-Encoding", string(Base64)) - } - - if _, ok := f.Header["Content-Disposition"]; !ok { - var disp string - if isAttachment { - disp = "attachment" - } else { - disp = "inline" - } - f.setHeader("Content-Disposition", disp+`; filename="`+f.Name+`"`) - } - - if !isAttachment { - if _, ok := f.Header["Content-ID"]; !ok { - f.setHeader("Content-ID", "<"+f.Name+">") - } - } - w.writeHeaders(f.Header) - w.writeBody(f.CopyFunc, Base64) - } -} - -func (w *messageWriter) Write(p []byte) (int, error) { - if w.err != nil { - return 0, errors.New("gomail: cannot write as writer is in error") - } - - var n int - n, w.err = w.w.Write(p) - w.n += int64(n) - return n, w.err -} - -func (w *messageWriter) writeString(s string) { - n, _ := io.WriteString(w.w, s) - w.n += int64(n) -} - -func (w *messageWriter) writeHeader(k string, v ...string) { - w.writeString(k) - if len(v) == 0 { - w.writeString(":\r\n") - return - } - w.writeString(": ") - - // Max header line length is 78 characters in RFC 5322 and 76 characters - // in RFC 2047. So for the sake of simplicity we use the 76 characters - // limit. - charsLeft := 76 - len(k) - len(": ") - - for i, s := range v { - // If the line is already too long, insert a newline right away. - if charsLeft < 1 { - if i == 0 { - w.writeString("\r\n ") - } else { - w.writeString(",\r\n ") - } - charsLeft = 75 - } else if i != 0 { - w.writeString(", ") - charsLeft -= 2 - } - - // While the header content is too long, fold it by inserting a newline. - for len(s) > charsLeft { - s = w.writeLine(s, charsLeft) - charsLeft = 75 - } - w.writeString(s) - if i := lastIndexByte(s, '\n'); i != -1 { - charsLeft = 75 - (len(s) - i - 1) - } else { - charsLeft -= len(s) - } - } - w.writeString("\r\n") -} - -func (w *messageWriter) writeLine(s string, charsLeft int) string { - // If there is already a newline before the limit. Write the line. - if i := strings.IndexByte(s, '\n'); i != -1 && i < charsLeft { - w.writeString(s[:i+1]) - return s[i+1:] - } - - for i := charsLeft - 1; i >= 0; i-- { - if s[i] == ' ' { - w.writeString(s[:i]) - w.writeString("\r\n ") - return s[i+1:] - } - } - - // We could not insert a newline cleanly so look for a space or a newline - // even if it is after the limit. - for i := 75; i < len(s); i++ { - if s[i] == ' ' { - w.writeString(s[:i]) - w.writeString("\r\n ") - return s[i+1:] - } - if s[i] == '\n' { - w.writeString(s[:i+1]) - return s[i+1:] - } - } - - // Too bad, no space or newline in the whole string. Just write everything. - w.writeString(s) - return "" -} - -func (w *messageWriter) writeHeaders(h map[string][]string) { - if w.depth == 0 { - for k, v := range h { - if k != "Bcc" { - w.writeHeader(k, v...) - } - } - } else { - w.createPart(h) - } -} - -func (w *messageWriter) writeBody(f func(io.Writer) error, enc Encoding) { - var subWriter io.Writer - if w.depth == 0 { - w.writeString("\r\n") - subWriter = w.w - } else { - subWriter = w.partWriter - } - - if enc == Base64 { - wc := base64.NewEncoder(base64.StdEncoding, newBase64LineWriter(subWriter)) - w.err = f(wc) - wc.Close() - } else if enc == Unencoded { - w.err = f(subWriter) - } else { - wc := newQPWriter(subWriter) - w.err = f(wc) - wc.Close() - } -} - -// As required by RFC 2045, 6.7. (page 21) for quoted-printable, and -// RFC 2045, 6.8. (page 25) for base64. -const maxLineLen = 76 - -// base64LineWriter limits text encoded in base64 to 76 characters per line -type base64LineWriter struct { - w io.Writer - lineLen int -} - -func newBase64LineWriter(w io.Writer) *base64LineWriter { - return &base64LineWriter{w: w} -} - -func (w *base64LineWriter) Write(p []byte) (int, error) { - n := 0 - for len(p)+w.lineLen > maxLineLen { - w.w.Write(p[:maxLineLen-w.lineLen]) - w.w.Write([]byte("\r\n")) - p = p[maxLineLen-w.lineLen:] - n += maxLineLen - w.lineLen - w.lineLen = 0 - } - - w.w.Write(p) - w.lineLen += len(p) - - return n + len(p), nil -} - -// Stubbed out for testing. -var now = time.Now diff --git a/vendor/github.com/go-sql-driver/mysql/.gitignore b/vendor/github.com/go-sql-driver/mysql/.gitignore deleted file mode 100644 index 2de28da1..00000000 --- a/vendor/github.com/go-sql-driver/mysql/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -.DS_Store -.DS_Store? -._* -.Spotlight-V100 -.Trashes -Icon? -ehthumbs.db -Thumbs.db -.idea diff --git a/vendor/github.com/go-sql-driver/mysql/AUTHORS b/vendor/github.com/go-sql-driver/mysql/AUTHORS deleted file mode 100644 index 50afa2c8..00000000 --- a/vendor/github.com/go-sql-driver/mysql/AUTHORS +++ /dev/null @@ -1,117 +0,0 @@ -# This is the official list of Go-MySQL-Driver authors for copyright purposes. - -# If you are submitting a patch, please add your name or the name of the -# organization which holds the copyright to this list in alphabetical order. - -# Names should be added to this file as -# Name -# The email address is not required for organizations. -# Please keep the list sorted. - - -# Individual Persons - -Aaron Hopkins -Achille Roussel -Alex Snast -Alexey Palazhchenko -Andrew Reid -Animesh Ray -Arne Hormann -Ariel Mashraki -Asta Xie -Bulat Gaifullin -Caine Jette -Carlos Nieto -Chris Moos -Craig Wilson -Daniel Montoya -Daniel Nichter -Daniël van Eeden -Dave Protasowski -DisposaBoy -Egor Smolyakov -Erwan Martin -Evan Shaw -Frederick Mayle -Gustavo Kristic -Hajime Nakagami -Hanno Braun -Henri Yandell -Hirotaka Yamamoto -Huyiguang -ICHINOSE Shogo -Ilia Cimpoes -INADA Naoki -Jacek Szwec -James Harr -Jeff Hodges -Jeffrey Charles -Jerome Meyer -Jiajia Zhong -Jian Zhen -Joshua Prunier -Julien Lefevre -Julien Schmidt -Justin Li -Justin Nuß -Kamil Dziedzic -Kei Kamikawa -Kevin Malachowski -Kieron Woodhouse -Lennart Rudolph -Leonardo YongUk Kim -Linh Tran Tuan -Lion Yang -Luca Looz -Lucas Liu -Luke Scott -Maciej Zimnoch -Michael Woolnough -Nathanial Murphy -Nicola Peduzzi -Olivier Mengué -oscarzhao -Paul Bonser -Peter Schultz -Rebecca Chin -Reed Allman -Richard Wilkes -Robert Russell -Runrioter Wung -Sho Iizuka -Sho Ikeda -Shuode Li -Simon J Mudd -Soroush Pour -Stan Putrya -Stanley Gunawan -Steven Hartland -Tan Jinhua <312841925 at qq.com> -Thomas Wodarek -Tim Ruffles -Tom Jenkinson -Vladimir Kovpak -Vladyslav Zhelezniak -Xiangyu Hu -Xiaobing Jiang -Xiuming Chen -Xuehong Chan -Zhenye Xie -Zhixin Wen - -# Organizations - -Barracuda Networks, Inc. -Counting Ltd. -DigitalOcean Inc. -Facebook Inc. -GitHub Inc. -Google Inc. -InfoSum Ltd. -Keybase Inc. -Multiplay Ltd. -Percona LLC -Pivotal Inc. -Stripe Inc. -Zendesk Inc. diff --git a/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md b/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md deleted file mode 100644 index 72a738ed..00000000 --- a/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md +++ /dev/null @@ -1,232 +0,0 @@ -## Version 1.6 (2021-04-01) - -Changes: - - - Migrate the CI service from travis-ci to GitHub Actions (#1176, #1183, #1190) - - `NullTime` is deprecated (#960, #1144) - - Reduce allocations when building SET command (#1111) - - Performance improvement for time formatting (#1118) - - Performance improvement for time parsing (#1098, #1113) - -New Features: - - - Implement `driver.Validator` interface (#1106, #1174) - - Support returning `uint64` from `Valuer` in `ConvertValue` (#1143) - - Add `json.RawMessage` for converter and prepared statement (#1059) - - Interpolate `json.RawMessage` as `string` (#1058) - - Implements `CheckNamedValue` (#1090) - -Bugfixes: - - - Stop rounding times (#1121, #1172) - - Put zero filler into the SSL handshake packet (#1066) - - Fix checking cancelled connections back into the connection pool (#1095) - - Fix remove last 0 byte for mysql_old_password when password is empty (#1133) - - -## Version 1.5 (2020-01-07) - -Changes: - - - Dropped support Go 1.9 and lower (#823, #829, #886, #1016, #1017) - - Improve buffer handling (#890) - - Document potentially insecure TLS configs (#901) - - Use a double-buffering scheme to prevent data races (#943) - - Pass uint64 values without converting them to string (#838, #955) - - Update collations and make utf8mb4 default (#877, #1054) - - Make NullTime compatible with sql.NullTime in Go 1.13+ (#995) - - Removed CloudSQL support (#993, #1007) - - Add Go Module support (#1003) - -New Features: - - - Implement support of optional TLS (#900) - - Check connection liveness (#934, #964, #997, #1048, #1051, #1052) - - Implement Connector Interface (#941, #958, #1020, #1035) - -Bugfixes: - - - Mark connections as bad on error during ping (#875) - - Mark connections as bad on error during dial (#867) - - Fix connection leak caused by rapid context cancellation (#1024) - - Mark connections as bad on error during Conn.Prepare (#1030) - - -## Version 1.4.1 (2018-11-14) - -Bugfixes: - - - Fix TIME format for binary columns (#818) - - Fix handling of empty auth plugin names (#835) - - Fix caching_sha2_password with empty password (#826) - - Fix canceled context broke mysqlConn (#862) - - Fix OldAuthSwitchRequest support (#870) - - Fix Auth Response packet for cleartext password (#887) - -## Version 1.4 (2018-06-03) - -Changes: - - - Documentation fixes (#530, #535, #567) - - Refactoring (#575, #579, #580, #581, #603, #615, #704) - - Cache column names (#444) - - Sort the DSN parameters in DSNs generated from a config (#637) - - Allow native password authentication by default (#644) - - Use the default port if it is missing in the DSN (#668) - - Removed the `strict` mode (#676) - - Do not query `max_allowed_packet` by default (#680) - - Dropped support Go 1.6 and lower (#696) - - Updated `ConvertValue()` to match the database/sql/driver implementation (#760) - - Document the usage of `0000-00-00T00:00:00` as the time.Time zero value (#783) - - Improved the compatibility of the authentication system (#807) - -New Features: - - - Multi-Results support (#537) - - `rejectReadOnly` DSN option (#604) - - `context.Context` support (#608, #612, #627, #761) - - Transaction isolation level support (#619, #744) - - Read-Only transactions support (#618, #634) - - `NewConfig` function which initializes a config with default values (#679) - - Implemented the `ColumnType` interfaces (#667, #724) - - Support for custom string types in `ConvertValue` (#623) - - Implemented `NamedValueChecker`, improving support for uint64 with high bit set (#690, #709, #710) - - `caching_sha2_password` authentication plugin support (#794, #800, #801, #802) - - Implemented `driver.SessionResetter` (#779) - - `sha256_password` authentication plugin support (#808) - -Bugfixes: - - - Use the DSN hostname as TLS default ServerName if `tls=true` (#564, #718) - - Fixed LOAD LOCAL DATA INFILE for empty files (#590) - - Removed columns definition cache since it sometimes cached invalid data (#592) - - Don't mutate registered TLS configs (#600) - - Make RegisterTLSConfig concurrency-safe (#613) - - Handle missing auth data in the handshake packet correctly (#646) - - Do not retry queries when data was written to avoid data corruption (#302, #736) - - Cache the connection pointer for error handling before invalidating it (#678) - - Fixed imports for appengine/cloudsql (#700) - - Fix sending STMT_LONG_DATA for 0 byte data (#734) - - Set correct capacity for []bytes read from length-encoded strings (#766) - - Make RegisterDial concurrency-safe (#773) - - -## Version 1.3 (2016-12-01) - -Changes: - - - Go 1.1 is no longer supported - - Use decimals fields in MySQL to format time types (#249) - - Buffer optimizations (#269) - - TLS ServerName defaults to the host (#283) - - Refactoring (#400, #410, #437) - - Adjusted documentation for second generation CloudSQL (#485) - - Documented DSN system var quoting rules (#502) - - Made statement.Close() calls idempotent to avoid errors in Go 1.6+ (#512) - -New Features: - - - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249) - - Support for returning table alias on Columns() (#289, #359, #382) - - Placeholder interpolation, can be actived with the DSN parameter `interpolateParams=true` (#309, #318, #490) - - Support for uint64 parameters with high bit set (#332, #345) - - Cleartext authentication plugin support (#327) - - Exported ParseDSN function and the Config struct (#403, #419, #429) - - Read / Write timeouts (#401) - - Support for JSON field type (#414) - - Support for multi-statements and multi-results (#411, #431) - - DSN parameter to set the driver-side max_allowed_packet value manually (#489) - - Native password authentication plugin support (#494, #524) - -Bugfixes: - - - Fixed handling of queries without columns and rows (#255) - - Fixed a panic when SetKeepAlive() failed (#298) - - Handle ERR packets while reading rows (#321) - - Fixed reading NULL length-encoded integers in MySQL 5.6+ (#349) - - Fixed absolute paths support in LOAD LOCAL DATA INFILE (#356) - - Actually zero out bytes in handshake response (#378) - - Fixed race condition in registering LOAD DATA INFILE handler (#383) - - Fixed tests with MySQL 5.7.9+ (#380) - - QueryUnescape TLS config names (#397) - - Fixed "broken pipe" error by writing to closed socket (#390) - - Fixed LOAD LOCAL DATA INFILE buffering (#424) - - Fixed parsing of floats into float64 when placeholders are used (#434) - - Fixed DSN tests with Go 1.7+ (#459) - - Handle ERR packets while waiting for EOF (#473) - - Invalidate connection on error while discarding additional results (#513) - - Allow terminating packets of length 0 (#516) - - -## Version 1.2 (2014-06-03) - -Changes: - - - We switched back to a "rolling release". `go get` installs the current master branch again - - Version v1 of the driver will not be maintained anymore. Go 1.0 is no longer supported by this driver - - Exported errors to allow easy checking from application code - - Enabled TCP Keepalives on TCP connections - - Optimized INFILE handling (better buffer size calculation, lazy init, ...) - - The DSN parser also checks for a missing separating slash - - Faster binary date / datetime to string formatting - - Also exported the MySQLWarning type - - mysqlConn.Close returns the first error encountered instead of ignoring all errors - - writePacket() automatically writes the packet size to the header - - readPacket() uses an iterative approach instead of the recursive approach to merge splitted packets - -New Features: - - - `RegisterDial` allows the usage of a custom dial function to establish the network connection - - Setting the connection collation is possible with the `collation` DSN parameter. This parameter should be preferred over the `charset` parameter - - Logging of critical errors is configurable with `SetLogger` - - Google CloudSQL support - -Bugfixes: - - - Allow more than 32 parameters in prepared statements - - Various old_password fixes - - Fixed TestConcurrent test to pass Go's race detection - - Fixed appendLengthEncodedInteger for large numbers - - Renamed readLengthEnodedString to readLengthEncodedString and skipLengthEnodedString to skipLengthEncodedString (fixed typo) - - -## Version 1.1 (2013-11-02) - -Changes: - - - Go-MySQL-Driver now requires Go 1.1 - - Connections now use the collation `utf8_general_ci` by default. Adding `&charset=UTF8` to the DSN should not be necessary anymore - - Made closing rows and connections error tolerant. This allows for example deferring rows.Close() without checking for errors - - `[]byte(nil)` is now treated as a NULL value. Before, it was treated like an empty string / `[]byte("")` - - DSN parameter values must now be url.QueryEscape'ed. This allows text values to contain special characters, such as '&'. - - Use the IO buffer also for writing. This results in zero allocations (by the driver) for most queries - - Optimized the buffer for reading - - stmt.Query now caches column metadata - - New Logo - - Changed the copyright header to include all contributors - - Improved the LOAD INFILE documentation - - The driver struct is now exported to make the driver directly accessible - - Refactored the driver tests - - Added more benchmarks and moved all to a separate file - - Other small refactoring - -New Features: - - - Added *old_passwords* support: Required in some cases, but must be enabled by adding `allowOldPasswords=true` to the DSN since it is insecure - - Added a `clientFoundRows` parameter: Return the number of matching rows instead of the number of rows changed on UPDATEs - - Added TLS/SSL support: Use a TLS/SSL encrypted connection to the server. Custom TLS configs can be registered and used - -Bugfixes: - - - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification - - Convert to DB timezone when inserting `time.Time` - - Splitted packets (more than 16MB) are now merged correctly - - Fixed false positive `io.EOF` errors when the data was fully read - - Avoid panics on reuse of closed connections - - Fixed empty string producing false nil values - - Fixed sign byte for positive TIME fields - - -## Version 1.0 (2013-05-14) - -Initial Release diff --git a/vendor/github.com/go-sql-driver/mysql/LICENSE b/vendor/github.com/go-sql-driver/mysql/LICENSE deleted file mode 100644 index 14e2f777..00000000 --- a/vendor/github.com/go-sql-driver/mysql/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/go-sql-driver/mysql/README.md b/vendor/github.com/go-sql-driver/mysql/README.md deleted file mode 100644 index 0b13154f..00000000 --- a/vendor/github.com/go-sql-driver/mysql/README.md +++ /dev/null @@ -1,520 +0,0 @@ -# Go-MySQL-Driver - -A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) package - -![Go-MySQL-Driver logo](https://raw.github.com/wiki/go-sql-driver/mysql/gomysql_m.png "Golang Gopher holding the MySQL Dolphin") - ---------------------------------------- - * [Features](#features) - * [Requirements](#requirements) - * [Installation](#installation) - * [Usage](#usage) - * [DSN (Data Source Name)](#dsn-data-source-name) - * [Password](#password) - * [Protocol](#protocol) - * [Address](#address) - * [Parameters](#parameters) - * [Examples](#examples) - * [Connection pool and timeouts](#connection-pool-and-timeouts) - * [context.Context Support](#contextcontext-support) - * [ColumnType Support](#columntype-support) - * [LOAD DATA LOCAL INFILE support](#load-data-local-infile-support) - * [time.Time support](#timetime-support) - * [Unicode support](#unicode-support) - * [Testing / Development](#testing--development) - * [License](#license) - ---------------------------------------- - -## Features - * Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance") - * Native Go implementation. No C-bindings, just pure Go - * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](https://godoc.org/github.com/go-sql-driver/mysql#DialFunc) - * Automatic handling of broken connections - * Automatic Connection Pooling *(by database/sql package)* - * Supports queries larger than 16MB - * Full [`sql.RawBytes`](https://golang.org/pkg/database/sql/#RawBytes) support. - * Intelligent `LONG DATA` handling in prepared statements - * Secure `LOAD DATA LOCAL INFILE` support with file allowlisting and `io.Reader` support - * Optional `time.Time` parsing - * Optional placeholder interpolation - -## Requirements - * Go 1.10 or higher. We aim to support the 3 latest versions of Go. - * MySQL (4.1+), MariaDB, Percona Server, Google CloudSQL or Sphinx (2.2.3+) - ---------------------------------------- - -## Installation -Simple install the package to your [$GOPATH](https://github.com/golang/go/wiki/GOPATH "GOPATH") with the [go tool](https://golang.org/cmd/go/ "go command") from shell: -```bash -$ go get -u github.com/go-sql-driver/mysql -``` -Make sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`. - -## Usage -_Go MySQL Driver_ is an implementation of Go's `database/sql/driver` interface. You only need to import the driver and can use the full [`database/sql`](https://golang.org/pkg/database/sql/) API then. - -Use `mysql` as `driverName` and a valid [DSN](#dsn-data-source-name) as `dataSourceName`: - -```go -import ( - "database/sql" - "time" - - _ "github.com/go-sql-driver/mysql" -) - -// ... - -db, err := sql.Open("mysql", "user:password@/dbname") -if err != nil { - panic(err) -} -// See "Important settings" section. -db.SetConnMaxLifetime(time.Minute * 3) -db.SetMaxOpenConns(10) -db.SetMaxIdleConns(10) -``` - -[Examples are available in our Wiki](https://github.com/go-sql-driver/mysql/wiki/Examples "Go-MySQL-Driver Examples"). - -### Important settings - -`db.SetConnMaxLifetime()` is required to ensure connections are closed by the driver safely before connection is closed by MySQL server, OS, or other middlewares. Since some middlewares close idle connections by 5 minutes, we recommend timeout shorter than 5 minutes. This setting helps load balancing and changing system variables too. - -`db.SetMaxOpenConns()` is highly recommended to limit the number of connection used by the application. There is no recommended limit number because it depends on application and MySQL server. - -`db.SetMaxIdleConns()` is recommended to be set same to (or greater than) `db.SetMaxOpenConns()`. When it is smaller than `SetMaxOpenConns()`, connections can be opened and closed very frequently than you expect. Idle connections can be closed by the `db.SetConnMaxLifetime()`. If you want to close idle connections more rapidly, you can use `db.SetConnMaxIdleTime()` since Go 1.15. - - -### DSN (Data Source Name) - -The Data Source Name has a common format, like e.g. [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php) uses it, but without type-prefix (optional parts marked by squared brackets): -``` -[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN] -``` - -A DSN in its fullest form: -``` -username:password@protocol(address)/dbname?param=value -``` - -Except for the databasename, all values are optional. So the minimal DSN is: -``` -/dbname -``` - -If you do not want to preselect a database, leave `dbname` empty: -``` -/ -``` -This has the same effect as an empty DSN string: -``` - -``` - -Alternatively, [Config.FormatDSN](https://godoc.org/github.com/go-sql-driver/mysql#Config.FormatDSN) can be used to create a DSN string by filling a struct. - -#### Password -Passwords can consist of any character. Escaping is **not** necessary. - -#### Protocol -See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available. -In general you should use an Unix domain socket if available and TCP otherwise for best performance. - -#### Address -For TCP and UDP networks, addresses have the form `host[:port]`. -If `port` is omitted, the default port will be used. -If `host` is a literal IPv6 address, it must be enclosed in square brackets. -The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form. - -For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. `/var/run/mysqld/mysqld.sock` or `/tmp/mysql.sock`. - -#### Parameters -*Parameters are case-sensitive!* - -Notice that any of `true`, `TRUE`, `True` or `1` is accepted to stand for a true boolean value. Not surprisingly, false can be specified as any of: `false`, `FALSE`, `False` or `0`. - -##### `allowAllFiles` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`allowAllFiles=true` disables the file allowlist for `LOAD DATA LOCAL INFILE` and allows *all* files. -[*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html) - -##### `allowCleartextPasswords` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`allowCleartextPasswords=true` allows using the [cleartext client side plugin](https://dev.mysql.com/doc/en/cleartext-pluggable-authentication.html) if required by an account, such as one defined with the [PAM authentication plugin](http://dev.mysql.com/doc/en/pam-authentication-plugin.html). Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include [TLS / SSL](#tls), IPsec, or a private network. - -##### `allowNativePasswords` - -``` -Type: bool -Valid Values: true, false -Default: true -``` -`allowNativePasswords=false` disallows the usage of MySQL native password method. - -##### `allowOldPasswords` - -``` -Type: bool -Valid Values: true, false -Default: false -``` -`allowOldPasswords=true` allows the usage of the insecure old password method. This should be avoided, but is necessary in some cases. See also [the old_passwords wiki page](https://github.com/go-sql-driver/mysql/wiki/old_passwords). - -##### `charset` - -``` -Type: string -Valid Values: -Default: none -``` - -Sets the charset used for client-server interaction (`"SET NAMES "`). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset failes. This enables for example support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers (`charset=utf8mb4,utf8`). - -Usage of the `charset` parameter is discouraged because it issues additional queries to the server. -Unless you need the fallback behavior, please use `collation` instead. - -##### `checkConnLiveness` - -``` -Type: bool -Valid Values: true, false -Default: true -``` - -On supported platforms connections retrieved from the connection pool are checked for liveness before using them. If the check fails, the respective connection is marked as bad and the query retried with another connection. -`checkConnLiveness=false` disables this liveness check of connections. - -##### `collation` - -``` -Type: string -Valid Values: -Default: utf8mb4_general_ci -``` - -Sets the collation used for client-server interaction on connection. In contrast to `charset`, `collation` does not issue additional queries. If the specified collation is unavailable on the target server, the connection will fail. - -A list of valid charsets for a server is retrievable with `SHOW COLLATION`. - -The default collation (`utf8mb4_general_ci`) is supported from MySQL 5.5. You should use an older collation (e.g. `utf8_general_ci`) for older MySQL. - -Collations for charset "ucs2", "utf16", "utf16le", and "utf32" can not be used ([ref](https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset)). - - -##### `clientFoundRows` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`clientFoundRows=true` causes an UPDATE to return the number of matching rows instead of the number of rows changed. - -##### `columnsWithAlias` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -When `columnsWithAlias` is true, calls to `sql.Rows.Columns()` will return the table alias and the column name separated by a dot. For example: - -``` -SELECT u.id FROM users as u -``` - -will return `u.id` instead of just `id` if `columnsWithAlias=true`. - -##### `interpolateParams` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -If `interpolateParams` is true, placeholders (`?`) in calls to `db.Query()` and `db.Exec()` are interpolated into a single query string with given parameters. This reduces the number of roundtrips, since the driver has to prepare a statement, execute it with given parameters and close the statement again with `interpolateParams=false`. - -*This can not be used together with the multibyte encodings BIG5, CP932, GB2312, GBK or SJIS. These are rejected as they may [introduce a SQL injection vulnerability](http://stackoverflow.com/a/12118602/3430118)!* - -##### `loc` - -``` -Type: string -Valid Values: -Default: UTC -``` - -Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](https://golang.org/pkg/time/#LoadLocation) for details. - -Note that this sets the location for time.Time values but does not change MySQL's [time_zone setting](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html). For that see the [time_zone system variable](#system-variables), which can also be set as a DSN parameter. - -Please keep in mind, that param values must be [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`. - -##### `maxAllowedPacket` -``` -Type: decimal number -Default: 4194304 -``` - -Max packet size allowed in bytes. The default value is 4 MiB and should be adjusted to match the server settings. `maxAllowedPacket=0` can be used to automatically fetch the `max_allowed_packet` variable from server *on every connection*. - -##### `multiStatements` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -Allow multiple statements in one query. While this allows batch queries, it also greatly increases the risk of SQL injections. Only the result of the first query is returned, all other results are silently discarded. - -When `multiStatements` is used, `?` parameters must only be used in the first statement. - -##### `parseTime` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`parseTime=true` changes the output type of `DATE` and `DATETIME` values to `time.Time` instead of `[]byte` / `string` -The date or datetime like `0000-00-00 00:00:00` is converted into zero value of `time.Time`. - - -##### `readTimeout` - -``` -Type: duration -Default: 0 -``` - -I/O read timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - -##### `rejectReadOnly` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - - -`rejectReadOnly=true` causes the driver to reject read-only connections. This -is for a possible race condition during an automatic failover, where the mysql -client gets connected to a read-only replica after the failover. - -Note that this should be a fairly rare case, as an automatic failover normally -happens when the primary is down, and the race condition shouldn't happen -unless it comes back up online as soon as the failover is kicked off. On the -other hand, when this happens, a MySQL application can get stuck on a -read-only connection until restarted. It is however fairly easy to reproduce, -for example, using a manual failover on AWS Aurora's MySQL-compatible cluster. - -If you are not relying on read-only transactions to reject writes that aren't -supposed to happen, setting this on some MySQL providers (such as AWS Aurora) -is safer for failovers. - -Note that ERROR 1290 can be returned for a `read-only` server and this option will -cause a retry for that error. However the same error number is used for some -other cases. You should ensure your application will never cause an ERROR 1290 -except for `read-only` mode when enabling this option. - - -##### `serverPubKey` - -``` -Type: string -Valid Values: -Default: none -``` - -Server public keys can be registered with [`mysql.RegisterServerPubKey`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterServerPubKey), which can then be used by the assigned name in the DSN. -Public keys are used to transmit encrypted data, e.g. for authentication. -If the server's public key is known, it should be set manually to avoid expensive and potentially insecure transmissions of the public key from the server to the client each time it is required. - - -##### `timeout` - -``` -Type: duration -Default: OS default -``` - -Timeout for establishing connections, aka dial timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - - -##### `tls` - -``` -Type: bool / string -Valid Values: true, false, skip-verify, preferred, -Default: false -``` - -`tls=true` enables TLS / SSL encrypted connection to the server. Use `skip-verify` if you want to use a self-signed or invalid certificate (server side) or use `preferred` to use TLS only when advertised by the server. This is similar to `skip-verify`, but additionally allows a fallback to a connection which is not encrypted. Neither `skip-verify` nor `preferred` add any reliable security. You can use a custom TLS config after registering it with [`mysql.RegisterTLSConfig`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterTLSConfig). - - -##### `writeTimeout` - -``` -Type: duration -Default: 0 -``` - -I/O write timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - - -##### System Variables - -Any other parameters are interpreted as system variables: - * `=`: `SET =` - * `=`: `SET =` - * `=%27%27`: `SET =''` - -Rules: -* The values for string variables must be quoted with `'`. -* The values must also be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed! - (which implies values of string variables must be wrapped with `%27`). - -Examples: - * `autocommit=1`: `SET autocommit=1` - * [`time_zone=%27Europe%2FParis%27`](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html): `SET time_zone='Europe/Paris'` - * [`transaction_isolation=%27REPEATABLE-READ%27`](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_transaction_isolation): `SET transaction_isolation='REPEATABLE-READ'` - - -#### Examples -``` -user@unix(/path/to/socket)/dbname -``` - -``` -root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local -``` - -``` -user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true -``` - -Treat warnings as errors by setting the system variable [`sql_mode`](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html): -``` -user:password@/dbname?sql_mode=TRADITIONAL -``` - -TCP via IPv6: -``` -user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci -``` - -TCP on a remote host, e.g. Amazon RDS: -``` -id:password@tcp(your-amazonaws-uri.com:3306)/dbname -``` - -Google Cloud SQL on App Engine: -``` -user:password@unix(/cloudsql/project-id:region-name:instance-name)/dbname -``` - -TCP using default port (3306) on localhost: -``` -user:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped -``` - -Use the default protocol (tcp) and host (localhost:3306): -``` -user:password@/dbname -``` - -No Database preselected: -``` -user:password@/ -``` - - -### Connection pool and timeouts -The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see `*DB.SetMaxOpenConns`, `*DB.SetMaxIdleConns`, and `*DB.SetConnMaxLifetime` in the [database/sql documentation](https://golang.org/pkg/database/sql/). The read, write, and dial timeouts for each individual connection are configured with the DSN parameters [`readTimeout`](#readtimeout), [`writeTimeout`](#writetimeout), and [`timeout`](#timeout), respectively. - -## `ColumnType` Support -This driver supports the [`ColumnType` interface](https://golang.org/pkg/database/sql/#ColumnType) introduced in Go 1.8, with the exception of [`ColumnType.Length()`](https://golang.org/pkg/database/sql/#ColumnType.Length), which is currently not supported. - -## `context.Context` Support -Go 1.8 added `database/sql` support for `context.Context`. This driver supports query timeouts and cancellation via contexts. -See [context support in the database/sql package](https://golang.org/doc/go1.8#database_sql) for more details. - - -### `LOAD DATA LOCAL INFILE` support -For this feature you need direct access to the package. Therefore you must change the import path (no `_`): -```go -import "github.com/go-sql-driver/mysql" -``` - -Files must be explicitly allowed by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the allowlist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html)). - -To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore. - -See the [godoc of Go-MySQL-Driver](https://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details. - - -### `time.Time` support -The default internal output type of MySQL `DATE` and `DATETIME` values is `[]byte` which allows you to scan the value into a `[]byte`, `string` or `sql.RawBytes` variable in your program. - -However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` variables, which is the logical equivalent in Go to `DATE` and `DATETIME` in MySQL. You can do that by changing the internal output type from `[]byte` to `time.Time` with the DSN parameter `parseTime=true`. You can set the default [`time.Time` location](https://golang.org/pkg/time/#Location) with the `loc` DSN parameter. - -**Caution:** As of Go 1.1, this makes `time.Time` the only variable type you can scan `DATE` and `DATETIME` values into. This breaks for example [`sql.RawBytes` support](https://github.com/go-sql-driver/mysql/wiki/Examples#rawbytes). - - -### Unicode support -Since version 1.5 Go-MySQL-Driver automatically uses the collation ` utf8mb4_general_ci` by default. - -Other collations / charsets can be set using the [`collation`](#collation) DSN parameter. - -Version 1.0 of the driver recommended adding `&charset=utf8` (alias for `SET NAMES utf8`) to the DSN to enable proper UTF-8 support. This is not necessary anymore. The [`collation`](#collation) parameter should be preferred to set another collation / charset than the default. - -See http://dev.mysql.com/doc/refman/8.0/en/charset-unicode.html for more details on MySQL's Unicode support. - -## Testing / Development -To run the driver tests you may need to adjust the configuration. See the [Testing Wiki-Page](https://github.com/go-sql-driver/mysql/wiki/Testing "Testing") for details. - -Go-MySQL-Driver is not feature-complete yet. Your help is very appreciated. -If you want to contribute, you can work on an [open issue](https://github.com/go-sql-driver/mysql/issues?state=open) or review a [pull request](https://github.com/go-sql-driver/mysql/pulls). - -See the [Contribution Guidelines](https://github.com/go-sql-driver/mysql/blob/master/.github/CONTRIBUTING.md) for details. - ---------------------------------------- - -## License -Go-MySQL-Driver is licensed under the [Mozilla Public License Version 2.0](https://raw.github.com/go-sql-driver/mysql/master/LICENSE) - -Mozilla summarizes the license scope as follows: -> MPL: The copyleft applies to any files containing MPLed code. - - -That means: - * You can **use** the **unchanged** source code both in private and commercially. - * When distributing, you **must publish** the source code of any **changed files** licensed under the MPL 2.0 under a) the MPL 2.0 itself or b) a compatible license (e.g. GPL 3.0 or Apache License 2.0). - * You **needn't publish** the source code of your library as long as the files licensed under the MPL 2.0 are **unchanged**. - -Please read the [MPL 2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) if you have further questions regarding the license. - -You can read the full terms here: [LICENSE](https://raw.github.com/go-sql-driver/mysql/master/LICENSE). - -![Go Gopher and MySQL Dolphin](https://raw.github.com/wiki/go-sql-driver/mysql/go-mysql-driver_m.jpg "Golang Gopher transporting the MySQL Dolphin in a wheelbarrow") diff --git a/vendor/github.com/go-sql-driver/mysql/auth.go b/vendor/github.com/go-sql-driver/mysql/auth.go deleted file mode 100644 index b2f19e8f..00000000 --- a/vendor/github.com/go-sql-driver/mysql/auth.go +++ /dev/null @@ -1,425 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - "crypto/x509" - "encoding/pem" - "fmt" - "sync" -) - -// server pub keys registry -var ( - serverPubKeyLock sync.RWMutex - serverPubKeyRegistry map[string]*rsa.PublicKey -) - -// RegisterServerPubKey registers a server RSA public key which can be used to -// send data in a secure manner to the server without receiving the public key -// in a potentially insecure way from the server first. -// Registered keys can afterwards be used adding serverPubKey= to the DSN. -// -// Note: The provided rsa.PublicKey instance is exclusively owned by the driver -// after registering it and may not be modified. -// -// data, err := ioutil.ReadFile("mykey.pem") -// if err != nil { -// log.Fatal(err) -// } -// -// block, _ := pem.Decode(data) -// if block == nil || block.Type != "PUBLIC KEY" { -// log.Fatal("failed to decode PEM block containing public key") -// } -// -// pub, err := x509.ParsePKIXPublicKey(block.Bytes) -// if err != nil { -// log.Fatal(err) -// } -// -// if rsaPubKey, ok := pub.(*rsa.PublicKey); ok { -// mysql.RegisterServerPubKey("mykey", rsaPubKey) -// } else { -// log.Fatal("not a RSA public key") -// } -// -func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) { - serverPubKeyLock.Lock() - if serverPubKeyRegistry == nil { - serverPubKeyRegistry = make(map[string]*rsa.PublicKey) - } - - serverPubKeyRegistry[name] = pubKey - serverPubKeyLock.Unlock() -} - -// DeregisterServerPubKey removes the public key registered with the given name. -func DeregisterServerPubKey(name string) { - serverPubKeyLock.Lock() - if serverPubKeyRegistry != nil { - delete(serverPubKeyRegistry, name) - } - serverPubKeyLock.Unlock() -} - -func getServerPubKey(name string) (pubKey *rsa.PublicKey) { - serverPubKeyLock.RLock() - if v, ok := serverPubKeyRegistry[name]; ok { - pubKey = v - } - serverPubKeyLock.RUnlock() - return -} - -// Hash password using pre 4.1 (old password) method -// https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c -type myRnd struct { - seed1, seed2 uint32 -} - -const myRndMaxVal = 0x3FFFFFFF - -// Pseudo random number generator -func newMyRnd(seed1, seed2 uint32) *myRnd { - return &myRnd{ - seed1: seed1 % myRndMaxVal, - seed2: seed2 % myRndMaxVal, - } -} - -// Tested to be equivalent to MariaDB's floating point variant -// http://play.golang.org/p/QHvhd4qved -// http://play.golang.org/p/RG0q4ElWDx -func (r *myRnd) NextByte() byte { - r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal - r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal - - return byte(uint64(r.seed1) * 31 / myRndMaxVal) -} - -// Generate binary hash from byte string using insecure pre 4.1 method -func pwHash(password []byte) (result [2]uint32) { - var add uint32 = 7 - var tmp uint32 - - result[0] = 1345345333 - result[1] = 0x12345671 - - for _, c := range password { - // skip spaces and tabs in password - if c == ' ' || c == '\t' { - continue - } - - tmp = uint32(c) - result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8) - result[1] += (result[1] << 8) ^ result[0] - add += tmp - } - - // Remove sign bit (1<<31)-1) - result[0] &= 0x7FFFFFFF - result[1] &= 0x7FFFFFFF - - return -} - -// Hash password using insecure pre 4.1 method -func scrambleOldPassword(scramble []byte, password string) []byte { - scramble = scramble[:8] - - hashPw := pwHash([]byte(password)) - hashSc := pwHash(scramble) - - r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1]) - - var out [8]byte - for i := range out { - out[i] = r.NextByte() + 64 - } - - mask := r.NextByte() - for i := range out { - out[i] ^= mask - } - - return out[:] -} - -// Hash password using 4.1+ method (SHA1) -func scramblePassword(scramble []byte, password string) []byte { - if len(password) == 0 { - return nil - } - - // stage1Hash = SHA1(password) - crypt := sha1.New() - crypt.Write([]byte(password)) - stage1 := crypt.Sum(nil) - - // scrambleHash = SHA1(scramble + SHA1(stage1Hash)) - // inner Hash - crypt.Reset() - crypt.Write(stage1) - hash := crypt.Sum(nil) - - // outer Hash - crypt.Reset() - crypt.Write(scramble) - crypt.Write(hash) - scramble = crypt.Sum(nil) - - // token = scrambleHash XOR stage1Hash - for i := range scramble { - scramble[i] ^= stage1[i] - } - return scramble -} - -// Hash password using MySQL 8+ method (SHA256) -func scrambleSHA256Password(scramble []byte, password string) []byte { - if len(password) == 0 { - return nil - } - - // XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble)) - - crypt := sha256.New() - crypt.Write([]byte(password)) - message1 := crypt.Sum(nil) - - crypt.Reset() - crypt.Write(message1) - message1Hash := crypt.Sum(nil) - - crypt.Reset() - crypt.Write(message1Hash) - crypt.Write(scramble) - message2 := crypt.Sum(nil) - - for i := range message1 { - message1[i] ^= message2[i] - } - - return message1 -} - -func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) { - plain := make([]byte, len(password)+1) - copy(plain, password) - for i := range plain { - j := i % len(seed) - plain[i] ^= seed[j] - } - sha1 := sha1.New() - return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil) -} - -func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error { - enc, err := encryptPassword(mc.cfg.Passwd, seed, pub) - if err != nil { - return err - } - return mc.writeAuthSwitchPacket(enc) -} - -func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) { - switch plugin { - case "caching_sha2_password": - authResp := scrambleSHA256Password(authData, mc.cfg.Passwd) - return authResp, nil - - case "mysql_old_password": - if !mc.cfg.AllowOldPasswords { - return nil, ErrOldPassword - } - if len(mc.cfg.Passwd) == 0 { - return nil, nil - } - // Note: there are edge cases where this should work but doesn't; - // this is currently "wontfix": - // https://github.com/go-sql-driver/mysql/issues/184 - authResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0) - return authResp, nil - - case "mysql_clear_password": - if !mc.cfg.AllowCleartextPasswords { - return nil, ErrCleartextPassword - } - // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html - // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html - return append([]byte(mc.cfg.Passwd), 0), nil - - case "mysql_native_password": - if !mc.cfg.AllowNativePasswords { - return nil, ErrNativePassword - } - // https://dev.mysql.com/doc/internals/en/secure-password-authentication.html - // Native password authentication only need and will need 20-byte challenge. - authResp := scramblePassword(authData[:20], mc.cfg.Passwd) - return authResp, nil - - case "sha256_password": - if len(mc.cfg.Passwd) == 0 { - return []byte{0}, nil - } - if mc.cfg.tls != nil || mc.cfg.Net == "unix" { - // write cleartext auth packet - return append([]byte(mc.cfg.Passwd), 0), nil - } - - pubKey := mc.cfg.pubKey - if pubKey == nil { - // request public key from server - return []byte{1}, nil - } - - // encrypted password - enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey) - return enc, err - - default: - errLog.Print("unknown auth plugin:", plugin) - return nil, ErrUnknownPlugin - } -} - -func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { - // Read Result Packet - authData, newPlugin, err := mc.readAuthResult() - if err != nil { - return err - } - - // handle auth plugin switch, if requested - if newPlugin != "" { - // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is - // sent and we have to keep using the cipher sent in the init packet. - if authData == nil { - authData = oldAuthData - } else { - // copy data from read buffer to owned slice - copy(oldAuthData, authData) - } - - plugin = newPlugin - - authResp, err := mc.auth(authData, plugin) - if err != nil { - return err - } - if err = mc.writeAuthSwitchPacket(authResp); err != nil { - return err - } - - // Read Result Packet - authData, newPlugin, err = mc.readAuthResult() - if err != nil { - return err - } - - // Do not allow to change the auth plugin more than once - if newPlugin != "" { - return ErrMalformPkt - } - } - - switch plugin { - - // https://insidemysql.com/preparing-your-community-connector-for-mysql-8-part-2-sha256/ - case "caching_sha2_password": - switch len(authData) { - case 0: - return nil // auth successful - case 1: - switch authData[0] { - case cachingSha2PasswordFastAuthSuccess: - if err = mc.readResultOK(); err == nil { - return nil // auth successful - } - - case cachingSha2PasswordPerformFullAuthentication: - if mc.cfg.tls != nil || mc.cfg.Net == "unix" { - // write cleartext auth packet - err = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0)) - if err != nil { - return err - } - } else { - pubKey := mc.cfg.pubKey - if pubKey == nil { - // request public key from server - data, err := mc.buf.takeSmallBuffer(4 + 1) - if err != nil { - return err - } - data[4] = cachingSha2PasswordRequestPublicKey - mc.writePacket(data) - - // parse public key - if data, err = mc.readPacket(); err != nil { - return err - } - - block, rest := pem.Decode(data[1:]) - if block == nil { - return fmt.Errorf("No Pem data found, data: %s", rest) - } - pkix, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return err - } - pubKey = pkix.(*rsa.PublicKey) - } - - // send encrypted password - err = mc.sendEncryptedPassword(oldAuthData, pubKey) - if err != nil { - return err - } - } - return mc.readResultOK() - - default: - return ErrMalformPkt - } - default: - return ErrMalformPkt - } - - case "sha256_password": - switch len(authData) { - case 0: - return nil // auth successful - default: - block, _ := pem.Decode(authData) - pub, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return err - } - - // send encrypted password - err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey)) - if err != nil { - return err - } - return mc.readResultOK() - } - - default: - return nil // auth successful - } - - return err -} diff --git a/vendor/github.com/go-sql-driver/mysql/buffer.go b/vendor/github.com/go-sql-driver/mysql/buffer.go deleted file mode 100644 index 0774c5c8..00000000 --- a/vendor/github.com/go-sql-driver/mysql/buffer.go +++ /dev/null @@ -1,182 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "io" - "net" - "time" -) - -const defaultBufSize = 4096 -const maxCachedBufSize = 256 * 1024 - -// A buffer which is used for both reading and writing. -// This is possible since communication on each connection is synchronous. -// In other words, we can't write and read simultaneously on the same connection. -// The buffer is similar to bufio.Reader / Writer but zero-copy-ish -// Also highly optimized for this particular use case. -// This buffer is backed by two byte slices in a double-buffering scheme -type buffer struct { - buf []byte // buf is a byte buffer who's length and capacity are equal. - nc net.Conn - idx int - length int - timeout time.Duration - dbuf [2][]byte // dbuf is an array with the two byte slices that back this buffer - flipcnt uint // flipccnt is the current buffer counter for double-buffering -} - -// newBuffer allocates and returns a new buffer. -func newBuffer(nc net.Conn) buffer { - fg := make([]byte, defaultBufSize) - return buffer{ - buf: fg, - nc: nc, - dbuf: [2][]byte{fg, nil}, - } -} - -// flip replaces the active buffer with the background buffer -// this is a delayed flip that simply increases the buffer counter; -// the actual flip will be performed the next time we call `buffer.fill` -func (b *buffer) flip() { - b.flipcnt += 1 -} - -// fill reads into the buffer until at least _need_ bytes are in it -func (b *buffer) fill(need int) error { - n := b.length - // fill data into its double-buffering target: if we've called - // flip on this buffer, we'll be copying to the background buffer, - // and then filling it with network data; otherwise we'll just move - // the contents of the current buffer to the front before filling it - dest := b.dbuf[b.flipcnt&1] - - // grow buffer if necessary to fit the whole packet. - if need > len(dest) { - // Round up to the next multiple of the default size - dest = make([]byte, ((need/defaultBufSize)+1)*defaultBufSize) - - // if the allocated buffer is not too large, move it to backing storage - // to prevent extra allocations on applications that perform large reads - if len(dest) <= maxCachedBufSize { - b.dbuf[b.flipcnt&1] = dest - } - } - - // if we're filling the fg buffer, move the existing data to the start of it. - // if we're filling the bg buffer, copy over the data - if n > 0 { - copy(dest[:n], b.buf[b.idx:]) - } - - b.buf = dest - b.idx = 0 - - for { - if b.timeout > 0 { - if err := b.nc.SetReadDeadline(time.Now().Add(b.timeout)); err != nil { - return err - } - } - - nn, err := b.nc.Read(b.buf[n:]) - n += nn - - switch err { - case nil: - if n < need { - continue - } - b.length = n - return nil - - case io.EOF: - if n >= need { - b.length = n - return nil - } - return io.ErrUnexpectedEOF - - default: - return err - } - } -} - -// returns next N bytes from buffer. -// The returned slice is only guaranteed to be valid until the next read -func (b *buffer) readNext(need int) ([]byte, error) { - if b.length < need { - // refill - if err := b.fill(need); err != nil { - return nil, err - } - } - - offset := b.idx - b.idx += need - b.length -= need - return b.buf[offset:b.idx], nil -} - -// takeBuffer returns a buffer with the requested size. -// If possible, a slice from the existing buffer is returned. -// Otherwise a bigger buffer is made. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeBuffer(length int) ([]byte, error) { - if b.length > 0 { - return nil, ErrBusyBuffer - } - - // test (cheap) general case first - if length <= cap(b.buf) { - return b.buf[:length], nil - } - - if length < maxPacketSize { - b.buf = make([]byte, length) - return b.buf, nil - } - - // buffer is larger than we want to store. - return make([]byte, length), nil -} - -// takeSmallBuffer is shortcut which can be used if length is -// known to be smaller than defaultBufSize. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeSmallBuffer(length int) ([]byte, error) { - if b.length > 0 { - return nil, ErrBusyBuffer - } - return b.buf[:length], nil -} - -// takeCompleteBuffer returns the complete existing buffer. -// This can be used if the necessary buffer size is unknown. -// cap and len of the returned buffer will be equal. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeCompleteBuffer() ([]byte, error) { - if b.length > 0 { - return nil, ErrBusyBuffer - } - return b.buf, nil -} - -// store stores buf, an updated buffer, if its suitable to do so. -func (b *buffer) store(buf []byte) error { - if b.length > 0 { - return ErrBusyBuffer - } else if cap(buf) <= maxPacketSize && cap(buf) > cap(b.buf) { - b.buf = buf[:cap(buf)] - } - return nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/collations.go b/vendor/github.com/go-sql-driver/mysql/collations.go deleted file mode 100644 index 326a9f7f..00000000 --- a/vendor/github.com/go-sql-driver/mysql/collations.go +++ /dev/null @@ -1,265 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2014 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -const defaultCollation = "utf8mb4_general_ci" -const binaryCollation = "binary" - -// A list of available collations mapped to the internal ID. -// To update this map use the following MySQL query: -// SELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS WHERE ID<256 ORDER BY ID -// -// Handshake packet have only 1 byte for collation_id. So we can't use collations with ID > 255. -// -// ucs2, utf16, and utf32 can't be used for connection charset. -// https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset -// They are commented out to reduce this map. -var collations = map[string]byte{ - "big5_chinese_ci": 1, - "latin2_czech_cs": 2, - "dec8_swedish_ci": 3, - "cp850_general_ci": 4, - "latin1_german1_ci": 5, - "hp8_english_ci": 6, - "koi8r_general_ci": 7, - "latin1_swedish_ci": 8, - "latin2_general_ci": 9, - "swe7_swedish_ci": 10, - "ascii_general_ci": 11, - "ujis_japanese_ci": 12, - "sjis_japanese_ci": 13, - "cp1251_bulgarian_ci": 14, - "latin1_danish_ci": 15, - "hebrew_general_ci": 16, - "tis620_thai_ci": 18, - "euckr_korean_ci": 19, - "latin7_estonian_cs": 20, - "latin2_hungarian_ci": 21, - "koi8u_general_ci": 22, - "cp1251_ukrainian_ci": 23, - "gb2312_chinese_ci": 24, - "greek_general_ci": 25, - "cp1250_general_ci": 26, - "latin2_croatian_ci": 27, - "gbk_chinese_ci": 28, - "cp1257_lithuanian_ci": 29, - "latin5_turkish_ci": 30, - "latin1_german2_ci": 31, - "armscii8_general_ci": 32, - "utf8_general_ci": 33, - "cp1250_czech_cs": 34, - //"ucs2_general_ci": 35, - "cp866_general_ci": 36, - "keybcs2_general_ci": 37, - "macce_general_ci": 38, - "macroman_general_ci": 39, - "cp852_general_ci": 40, - "latin7_general_ci": 41, - "latin7_general_cs": 42, - "macce_bin": 43, - "cp1250_croatian_ci": 44, - "utf8mb4_general_ci": 45, - "utf8mb4_bin": 46, - "latin1_bin": 47, - "latin1_general_ci": 48, - "latin1_general_cs": 49, - "cp1251_bin": 50, - "cp1251_general_ci": 51, - "cp1251_general_cs": 52, - "macroman_bin": 53, - //"utf16_general_ci": 54, - //"utf16_bin": 55, - //"utf16le_general_ci": 56, - "cp1256_general_ci": 57, - "cp1257_bin": 58, - "cp1257_general_ci": 59, - //"utf32_general_ci": 60, - //"utf32_bin": 61, - //"utf16le_bin": 62, - "binary": 63, - "armscii8_bin": 64, - "ascii_bin": 65, - "cp1250_bin": 66, - "cp1256_bin": 67, - "cp866_bin": 68, - "dec8_bin": 69, - "greek_bin": 70, - "hebrew_bin": 71, - "hp8_bin": 72, - "keybcs2_bin": 73, - "koi8r_bin": 74, - "koi8u_bin": 75, - "utf8_tolower_ci": 76, - "latin2_bin": 77, - "latin5_bin": 78, - "latin7_bin": 79, - "cp850_bin": 80, - "cp852_bin": 81, - "swe7_bin": 82, - "utf8_bin": 83, - "big5_bin": 84, - "euckr_bin": 85, - "gb2312_bin": 86, - "gbk_bin": 87, - "sjis_bin": 88, - "tis620_bin": 89, - //"ucs2_bin": 90, - "ujis_bin": 91, - "geostd8_general_ci": 92, - "geostd8_bin": 93, - "latin1_spanish_ci": 94, - "cp932_japanese_ci": 95, - "cp932_bin": 96, - "eucjpms_japanese_ci": 97, - "eucjpms_bin": 98, - "cp1250_polish_ci": 99, - //"utf16_unicode_ci": 101, - //"utf16_icelandic_ci": 102, - //"utf16_latvian_ci": 103, - //"utf16_romanian_ci": 104, - //"utf16_slovenian_ci": 105, - //"utf16_polish_ci": 106, - //"utf16_estonian_ci": 107, - //"utf16_spanish_ci": 108, - //"utf16_swedish_ci": 109, - //"utf16_turkish_ci": 110, - //"utf16_czech_ci": 111, - //"utf16_danish_ci": 112, - //"utf16_lithuanian_ci": 113, - //"utf16_slovak_ci": 114, - //"utf16_spanish2_ci": 115, - //"utf16_roman_ci": 116, - //"utf16_persian_ci": 117, - //"utf16_esperanto_ci": 118, - //"utf16_hungarian_ci": 119, - //"utf16_sinhala_ci": 120, - //"utf16_german2_ci": 121, - //"utf16_croatian_ci": 122, - //"utf16_unicode_520_ci": 123, - //"utf16_vietnamese_ci": 124, - //"ucs2_unicode_ci": 128, - //"ucs2_icelandic_ci": 129, - //"ucs2_latvian_ci": 130, - //"ucs2_romanian_ci": 131, - //"ucs2_slovenian_ci": 132, - //"ucs2_polish_ci": 133, - //"ucs2_estonian_ci": 134, - //"ucs2_spanish_ci": 135, - //"ucs2_swedish_ci": 136, - //"ucs2_turkish_ci": 137, - //"ucs2_czech_ci": 138, - //"ucs2_danish_ci": 139, - //"ucs2_lithuanian_ci": 140, - //"ucs2_slovak_ci": 141, - //"ucs2_spanish2_ci": 142, - //"ucs2_roman_ci": 143, - //"ucs2_persian_ci": 144, - //"ucs2_esperanto_ci": 145, - //"ucs2_hungarian_ci": 146, - //"ucs2_sinhala_ci": 147, - //"ucs2_german2_ci": 148, - //"ucs2_croatian_ci": 149, - //"ucs2_unicode_520_ci": 150, - //"ucs2_vietnamese_ci": 151, - //"ucs2_general_mysql500_ci": 159, - //"utf32_unicode_ci": 160, - //"utf32_icelandic_ci": 161, - //"utf32_latvian_ci": 162, - //"utf32_romanian_ci": 163, - //"utf32_slovenian_ci": 164, - //"utf32_polish_ci": 165, - //"utf32_estonian_ci": 166, - //"utf32_spanish_ci": 167, - //"utf32_swedish_ci": 168, - //"utf32_turkish_ci": 169, - //"utf32_czech_ci": 170, - //"utf32_danish_ci": 171, - //"utf32_lithuanian_ci": 172, - //"utf32_slovak_ci": 173, - //"utf32_spanish2_ci": 174, - //"utf32_roman_ci": 175, - //"utf32_persian_ci": 176, - //"utf32_esperanto_ci": 177, - //"utf32_hungarian_ci": 178, - //"utf32_sinhala_ci": 179, - //"utf32_german2_ci": 180, - //"utf32_croatian_ci": 181, - //"utf32_unicode_520_ci": 182, - //"utf32_vietnamese_ci": 183, - "utf8_unicode_ci": 192, - "utf8_icelandic_ci": 193, - "utf8_latvian_ci": 194, - "utf8_romanian_ci": 195, - "utf8_slovenian_ci": 196, - "utf8_polish_ci": 197, - "utf8_estonian_ci": 198, - "utf8_spanish_ci": 199, - "utf8_swedish_ci": 200, - "utf8_turkish_ci": 201, - "utf8_czech_ci": 202, - "utf8_danish_ci": 203, - "utf8_lithuanian_ci": 204, - "utf8_slovak_ci": 205, - "utf8_spanish2_ci": 206, - "utf8_roman_ci": 207, - "utf8_persian_ci": 208, - "utf8_esperanto_ci": 209, - "utf8_hungarian_ci": 210, - "utf8_sinhala_ci": 211, - "utf8_german2_ci": 212, - "utf8_croatian_ci": 213, - "utf8_unicode_520_ci": 214, - "utf8_vietnamese_ci": 215, - "utf8_general_mysql500_ci": 223, - "utf8mb4_unicode_ci": 224, - "utf8mb4_icelandic_ci": 225, - "utf8mb4_latvian_ci": 226, - "utf8mb4_romanian_ci": 227, - "utf8mb4_slovenian_ci": 228, - "utf8mb4_polish_ci": 229, - "utf8mb4_estonian_ci": 230, - "utf8mb4_spanish_ci": 231, - "utf8mb4_swedish_ci": 232, - "utf8mb4_turkish_ci": 233, - "utf8mb4_czech_ci": 234, - "utf8mb4_danish_ci": 235, - "utf8mb4_lithuanian_ci": 236, - "utf8mb4_slovak_ci": 237, - "utf8mb4_spanish2_ci": 238, - "utf8mb4_roman_ci": 239, - "utf8mb4_persian_ci": 240, - "utf8mb4_esperanto_ci": 241, - "utf8mb4_hungarian_ci": 242, - "utf8mb4_sinhala_ci": 243, - "utf8mb4_german2_ci": 244, - "utf8mb4_croatian_ci": 245, - "utf8mb4_unicode_520_ci": 246, - "utf8mb4_vietnamese_ci": 247, - "gb18030_chinese_ci": 248, - "gb18030_bin": 249, - "gb18030_unicode_520_ci": 250, - "utf8mb4_0900_ai_ci": 255, -} - -// A denylist of collations which is unsafe to interpolate parameters. -// These multibyte encodings may contains 0x5c (`\`) in their trailing bytes. -var unsafeCollations = map[string]bool{ - "big5_chinese_ci": true, - "sjis_japanese_ci": true, - "gbk_chinese_ci": true, - "big5_bin": true, - "gb2312_bin": true, - "gbk_bin": true, - "sjis_bin": true, - "cp932_japanese_ci": true, - "cp932_bin": true, - "gb18030_chinese_ci": true, - "gb18030_bin": true, - "gb18030_unicode_520_ci": true, -} diff --git a/vendor/github.com/go-sql-driver/mysql/connection.go b/vendor/github.com/go-sql-driver/mysql/connection.go deleted file mode 100644 index 835f8972..00000000 --- a/vendor/github.com/go-sql-driver/mysql/connection.go +++ /dev/null @@ -1,650 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "context" - "database/sql" - "database/sql/driver" - "encoding/json" - "io" - "net" - "strconv" - "strings" - "time" -) - -type mysqlConn struct { - buf buffer - netConn net.Conn - rawConn net.Conn // underlying connection when netConn is TLS connection. - affectedRows uint64 - insertId uint64 - cfg *Config - maxAllowedPacket int - maxWriteSize int - writeTimeout time.Duration - flags clientFlag - status statusFlag - sequence uint8 - parseTime bool - reset bool // set when the Go SQL package calls ResetSession - - // for context support (Go 1.8+) - watching bool - watcher chan<- context.Context - closech chan struct{} - finished chan<- struct{} - canceled atomicError // set non-nil if conn is canceled - closed atomicBool // set when conn is closed, before closech is closed -} - -// Handles parameters set in DSN after the connection is established -func (mc *mysqlConn) handleParams() (err error) { - var cmdSet strings.Builder - for param, val := range mc.cfg.Params { - switch param { - // Charset: character_set_connection, character_set_client, character_set_results - case "charset": - charsets := strings.Split(val, ",") - for i := range charsets { - // ignore errors here - a charset may not exist - err = mc.exec("SET NAMES " + charsets[i]) - if err == nil { - break - } - } - if err != nil { - return - } - - // Other system vars accumulated in a single SET command - default: - if cmdSet.Len() == 0 { - // Heuristic: 29 chars for each other key=value to reduce reallocations - cmdSet.Grow(4 + len(param) + 1 + len(val) + 30*(len(mc.cfg.Params)-1)) - cmdSet.WriteString("SET ") - } else { - cmdSet.WriteByte(',') - } - cmdSet.WriteString(param) - cmdSet.WriteByte('=') - cmdSet.WriteString(val) - } - } - - if cmdSet.Len() > 0 { - err = mc.exec(cmdSet.String()) - if err != nil { - return - } - } - - return -} - -func (mc *mysqlConn) markBadConn(err error) error { - if mc == nil { - return err - } - if err != errBadConnNoWrite { - return err - } - return driver.ErrBadConn -} - -func (mc *mysqlConn) Begin() (driver.Tx, error) { - return mc.begin(false) -} - -func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - var q string - if readOnly { - q = "START TRANSACTION READ ONLY" - } else { - q = "START TRANSACTION" - } - err := mc.exec(q) - if err == nil { - return &mysqlTx{mc}, err - } - return nil, mc.markBadConn(err) -} - -func (mc *mysqlConn) Close() (err error) { - // Makes Close idempotent - if !mc.closed.IsSet() { - err = mc.writeCommandPacket(comQuit) - } - - mc.cleanup() - - return -} - -// Closes the network connection and unsets internal variables. Do not call this -// function after successfully authentication, call Close instead. This function -// is called before auth or on auth failure because MySQL will have already -// closed the network connection. -func (mc *mysqlConn) cleanup() { - if !mc.closed.TrySet(true) { - return - } - - // Makes cleanup idempotent - close(mc.closech) - if mc.netConn == nil { - return - } - if err := mc.netConn.Close(); err != nil { - errLog.Print(err) - } -} - -func (mc *mysqlConn) error() error { - if mc.closed.IsSet() { - if err := mc.canceled.Value(); err != nil { - return err - } - return ErrInvalidConn - } - return nil -} - -func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := mc.writeCommandPacketStr(comStmtPrepare, query) - if err != nil { - // STMT_PREPARE is safe to retry. So we can return ErrBadConn here. - errLog.Print(err) - return nil, driver.ErrBadConn - } - - stmt := &mysqlStmt{ - mc: mc, - } - - // Read Result - columnCount, err := stmt.readPrepareResultPacket() - if err == nil { - if stmt.paramCount > 0 { - if err = mc.readUntilEOF(); err != nil { - return nil, err - } - } - - if columnCount > 0 { - err = mc.readUntilEOF() - } - } - - return stmt, err -} - -func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) { - // Number of ? should be same to len(args) - if strings.Count(query, "?") != len(args) { - return "", driver.ErrSkip - } - - buf, err := mc.buf.takeCompleteBuffer() - if err != nil { - // can not take the buffer. Something must be wrong with the connection - errLog.Print(err) - return "", ErrInvalidConn - } - buf = buf[:0] - argPos := 0 - - for i := 0; i < len(query); i++ { - q := strings.IndexByte(query[i:], '?') - if q == -1 { - buf = append(buf, query[i:]...) - break - } - buf = append(buf, query[i:i+q]...) - i += q - - arg := args[argPos] - argPos++ - - if arg == nil { - buf = append(buf, "NULL"...) - continue - } - - switch v := arg.(type) { - case int64: - buf = strconv.AppendInt(buf, v, 10) - case uint64: - // Handle uint64 explicitly because our custom ConvertValue emits unsigned values - buf = strconv.AppendUint(buf, v, 10) - case float64: - buf = strconv.AppendFloat(buf, v, 'g', -1, 64) - case bool: - if v { - buf = append(buf, '1') - } else { - buf = append(buf, '0') - } - case time.Time: - if v.IsZero() { - buf = append(buf, "'0000-00-00'"...) - } else { - buf = append(buf, '\'') - buf, err = appendDateTime(buf, v.In(mc.cfg.Loc)) - if err != nil { - return "", err - } - buf = append(buf, '\'') - } - case json.RawMessage: - buf = append(buf, '\'') - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeBytesBackslash(buf, v) - } else { - buf = escapeBytesQuotes(buf, v) - } - buf = append(buf, '\'') - case []byte: - if v == nil { - buf = append(buf, "NULL"...) - } else { - buf = append(buf, "_binary'"...) - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeBytesBackslash(buf, v) - } else { - buf = escapeBytesQuotes(buf, v) - } - buf = append(buf, '\'') - } - case string: - buf = append(buf, '\'') - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeStringBackslash(buf, v) - } else { - buf = escapeStringQuotes(buf, v) - } - buf = append(buf, '\'') - default: - return "", driver.ErrSkip - } - - if len(buf)+4 > mc.maxAllowedPacket { - return "", driver.ErrSkip - } - } - if argPos != len(args) { - return "", driver.ErrSkip - } - return string(buf), nil -} - -func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - if len(args) != 0 { - if !mc.cfg.InterpolateParams { - return nil, driver.ErrSkip - } - // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement - prepared, err := mc.interpolateParams(query, args) - if err != nil { - return nil, err - } - query = prepared - } - mc.affectedRows = 0 - mc.insertId = 0 - - err := mc.exec(query) - if err == nil { - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, err - } - return nil, mc.markBadConn(err) -} - -// Internal function to execute commands -func (mc *mysqlConn) exec(query string) error { - // Send command - if err := mc.writeCommandPacketStr(comQuery, query); err != nil { - return mc.markBadConn(err) - } - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return err - } - - if resLen > 0 { - // columns - if err := mc.readUntilEOF(); err != nil { - return err - } - - // rows - if err := mc.readUntilEOF(); err != nil { - return err - } - } - - return mc.discardResults() -} - -func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) { - return mc.query(query, args) -} - -func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - if len(args) != 0 { - if !mc.cfg.InterpolateParams { - return nil, driver.ErrSkip - } - // try client-side prepare to reduce roundtrip - prepared, err := mc.interpolateParams(query, args) - if err != nil { - return nil, err - } - query = prepared - } - // Send command - err := mc.writeCommandPacketStr(comQuery, query) - if err == nil { - // Read Result - var resLen int - resLen, err = mc.readResultSetHeaderPacket() - if err == nil { - rows := new(textRows) - rows.mc = mc - - if resLen == 0 { - rows.rs.done = true - - switch err := rows.NextResultSet(); err { - case nil, io.EOF: - return rows, nil - default: - return nil, err - } - } - - // Columns - rows.rs.columns, err = mc.readColumns(resLen) - return rows, err - } - } - return nil, mc.markBadConn(err) -} - -// Gets the value of the given MySQL System Variable -// The returned byte slice is only valid until the next read -func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) { - // Send command - if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil { - return nil, err - } - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err == nil { - rows := new(textRows) - rows.mc = mc - rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}} - - if resLen > 0 { - // Columns - if err := mc.readUntilEOF(); err != nil { - return nil, err - } - } - - dest := make([]driver.Value, resLen) - if err = rows.readRow(dest); err == nil { - return dest[0].([]byte), mc.readUntilEOF() - } - } - return nil, err -} - -// finish is called when the query has canceled. -func (mc *mysqlConn) cancel(err error) { - mc.canceled.Set(err) - mc.cleanup() -} - -// finish is called when the query has succeeded. -func (mc *mysqlConn) finish() { - if !mc.watching || mc.finished == nil { - return - } - select { - case mc.finished <- struct{}{}: - mc.watching = false - case <-mc.closech: - } -} - -// Ping implements driver.Pinger interface -func (mc *mysqlConn) Ping(ctx context.Context) (err error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return driver.ErrBadConn - } - - if err = mc.watchCancel(ctx); err != nil { - return - } - defer mc.finish() - - if err = mc.writeCommandPacket(comPing); err != nil { - return mc.markBadConn(err) - } - - return mc.readResultOK() -} - -// BeginTx implements driver.ConnBeginTx interface -func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - if mc.closed.IsSet() { - return nil, driver.ErrBadConn - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - defer mc.finish() - - if sql.IsolationLevel(opts.Isolation) != sql.LevelDefault { - level, err := mapIsolationLevel(opts.Isolation) - if err != nil { - return nil, err - } - err = mc.exec("SET TRANSACTION ISOLATION LEVEL " + level) - if err != nil { - return nil, err - } - } - - return mc.begin(opts.ReadOnly) -} - -func (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - - rows, err := mc.query(query, dargs) - if err != nil { - mc.finish() - return nil, err - } - rows.finish = mc.finish - return rows, err -} - -func (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - defer mc.finish() - - return mc.Exec(query, dargs) -} - -func (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - - stmt, err := mc.Prepare(query) - mc.finish() - if err != nil { - return nil, err - } - - select { - default: - case <-ctx.Done(): - stmt.Close() - return nil, ctx.Err() - } - return stmt, nil -} - -func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := stmt.mc.watchCancel(ctx); err != nil { - return nil, err - } - - rows, err := stmt.query(dargs) - if err != nil { - stmt.mc.finish() - return nil, err - } - rows.finish = stmt.mc.finish - return rows, err -} - -func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := stmt.mc.watchCancel(ctx); err != nil { - return nil, err - } - defer stmt.mc.finish() - - return stmt.Exec(dargs) -} - -func (mc *mysqlConn) watchCancel(ctx context.Context) error { - if mc.watching { - // Reach here if canceled, - // so the connection is already invalid - mc.cleanup() - return nil - } - // When ctx is already cancelled, don't watch it. - if err := ctx.Err(); err != nil { - return err - } - // When ctx is not cancellable, don't watch it. - if ctx.Done() == nil { - return nil - } - // When watcher is not alive, can't watch it. - if mc.watcher == nil { - return nil - } - - mc.watching = true - mc.watcher <- ctx - return nil -} - -func (mc *mysqlConn) startWatcher() { - watcher := make(chan context.Context, 1) - mc.watcher = watcher - finished := make(chan struct{}) - mc.finished = finished - go func() { - for { - var ctx context.Context - select { - case ctx = <-watcher: - case <-mc.closech: - return - } - - select { - case <-ctx.Done(): - mc.cancel(ctx.Err()) - case <-finished: - case <-mc.closech: - return - } - } - }() -} - -func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) { - nv.Value, err = converter{}.ConvertValue(nv.Value) - return -} - -// ResetSession implements driver.SessionResetter. -// (From Go 1.10) -func (mc *mysqlConn) ResetSession(ctx context.Context) error { - if mc.closed.IsSet() { - return driver.ErrBadConn - } - mc.reset = true - return nil -} - -// IsValid implements driver.Validator interface -// (From Go 1.15) -func (mc *mysqlConn) IsValid() bool { - return !mc.closed.IsSet() -} diff --git a/vendor/github.com/go-sql-driver/mysql/const.go b/vendor/github.com/go-sql-driver/mysql/const.go deleted file mode 100644 index b1e6b85e..00000000 --- a/vendor/github.com/go-sql-driver/mysql/const.go +++ /dev/null @@ -1,174 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -const ( - defaultAuthPlugin = "mysql_native_password" - defaultMaxAllowedPacket = 4 << 20 // 4 MiB - minProtocolVersion = 10 - maxPacketSize = 1<<24 - 1 - timeFormat = "2006-01-02 15:04:05.999999" -) - -// MySQL constants documentation: -// http://dev.mysql.com/doc/internals/en/client-server-protocol.html - -const ( - iOK byte = 0x00 - iAuthMoreData byte = 0x01 - iLocalInFile byte = 0xfb - iEOF byte = 0xfe - iERR byte = 0xff -) - -// https://dev.mysql.com/doc/internals/en/capability-flags.html#packet-Protocol::CapabilityFlags -type clientFlag uint32 - -const ( - clientLongPassword clientFlag = 1 << iota - clientFoundRows - clientLongFlag - clientConnectWithDB - clientNoSchema - clientCompress - clientODBC - clientLocalFiles - clientIgnoreSpace - clientProtocol41 - clientInteractive - clientSSL - clientIgnoreSIGPIPE - clientTransactions - clientReserved - clientSecureConn - clientMultiStatements - clientMultiResults - clientPSMultiResults - clientPluginAuth - clientConnectAttrs - clientPluginAuthLenEncClientData - clientCanHandleExpiredPasswords - clientSessionTrack - clientDeprecateEOF -) - -const ( - comQuit byte = iota + 1 - comInitDB - comQuery - comFieldList - comCreateDB - comDropDB - comRefresh - comShutdown - comStatistics - comProcessInfo - comConnect - comProcessKill - comDebug - comPing - comTime - comDelayedInsert - comChangeUser - comBinlogDump - comTableDump - comConnectOut - comRegisterSlave - comStmtPrepare - comStmtExecute - comStmtSendLongData - comStmtClose - comStmtReset - comSetOption - comStmtFetch -) - -// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType -type fieldType byte - -const ( - fieldTypeDecimal fieldType = iota - fieldTypeTiny - fieldTypeShort - fieldTypeLong - fieldTypeFloat - fieldTypeDouble - fieldTypeNULL - fieldTypeTimestamp - fieldTypeLongLong - fieldTypeInt24 - fieldTypeDate - fieldTypeTime - fieldTypeDateTime - fieldTypeYear - fieldTypeNewDate - fieldTypeVarChar - fieldTypeBit -) -const ( - fieldTypeJSON fieldType = iota + 0xf5 - fieldTypeNewDecimal - fieldTypeEnum - fieldTypeSet - fieldTypeTinyBLOB - fieldTypeMediumBLOB - fieldTypeLongBLOB - fieldTypeBLOB - fieldTypeVarString - fieldTypeString - fieldTypeGeometry -) - -type fieldFlag uint16 - -const ( - flagNotNULL fieldFlag = 1 << iota - flagPriKey - flagUniqueKey - flagMultipleKey - flagBLOB - flagUnsigned - flagZeroFill - flagBinary - flagEnum - flagAutoIncrement - flagTimestamp - flagSet - flagUnknown1 - flagUnknown2 - flagUnknown3 - flagUnknown4 -) - -// http://dev.mysql.com/doc/internals/en/status-flags.html -type statusFlag uint16 - -const ( - statusInTrans statusFlag = 1 << iota - statusInAutocommit - statusReserved // Not in documentation - statusMoreResultsExists - statusNoGoodIndexUsed - statusNoIndexUsed - statusCursorExists - statusLastRowSent - statusDbDropped - statusNoBackslashEscapes - statusMetadataChanged - statusQueryWasSlow - statusPsOutParams - statusInTransReadonly - statusSessionStateChanged -) - -const ( - cachingSha2PasswordRequestPublicKey = 2 - cachingSha2PasswordFastAuthSuccess = 3 - cachingSha2PasswordPerformFullAuthentication = 4 -) diff --git a/vendor/github.com/go-sql-driver/mysql/driver.go b/vendor/github.com/go-sql-driver/mysql/driver.go deleted file mode 100644 index c1bdf119..00000000 --- a/vendor/github.com/go-sql-driver/mysql/driver.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -// Package mysql provides a MySQL driver for Go's database/sql package. -// -// The driver should be used via the database/sql package: -// -// import "database/sql" -// import _ "github.com/go-sql-driver/mysql" -// -// db, err := sql.Open("mysql", "user:password@/dbname") -// -// See https://github.com/go-sql-driver/mysql#usage for details -package mysql - -import ( - "context" - "database/sql" - "database/sql/driver" - "net" - "sync" -) - -// MySQLDriver is exported to make the driver directly accessible. -// In general the driver is used via the database/sql package. -type MySQLDriver struct{} - -// DialFunc is a function which can be used to establish the network connection. -// Custom dial functions must be registered with RegisterDial -// -// Deprecated: users should register a DialContextFunc instead -type DialFunc func(addr string) (net.Conn, error) - -// DialContextFunc is a function which can be used to establish the network connection. -// Custom dial functions must be registered with RegisterDialContext -type DialContextFunc func(ctx context.Context, addr string) (net.Conn, error) - -var ( - dialsLock sync.RWMutex - dials map[string]DialContextFunc -) - -// RegisterDialContext registers a custom dial function. It can then be used by the -// network address mynet(addr), where mynet is the registered new network. -// The current context for the connection and its address is passed to the dial function. -func RegisterDialContext(net string, dial DialContextFunc) { - dialsLock.Lock() - defer dialsLock.Unlock() - if dials == nil { - dials = make(map[string]DialContextFunc) - } - dials[net] = dial -} - -// RegisterDial registers a custom dial function. It can then be used by the -// network address mynet(addr), where mynet is the registered new network. -// addr is passed as a parameter to the dial function. -// -// Deprecated: users should call RegisterDialContext instead -func RegisterDial(network string, dial DialFunc) { - RegisterDialContext(network, func(_ context.Context, addr string) (net.Conn, error) { - return dial(addr) - }) -} - -// Open new Connection. -// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how -// the DSN string is formatted -func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { - cfg, err := ParseDSN(dsn) - if err != nil { - return nil, err - } - c := &connector{ - cfg: cfg, - } - return c.Connect(context.Background()) -} - -func init() { - sql.Register("mysql", &MySQLDriver{}) -} - -// NewConnector returns new driver.Connector. -func NewConnector(cfg *Config) (driver.Connector, error) { - cfg = cfg.Clone() - // normalize the contents of cfg so calls to NewConnector have the same - // behavior as MySQLDriver.OpenConnector - if err := cfg.normalize(); err != nil { - return nil, err - } - return &connector{cfg: cfg}, nil -} - -// OpenConnector implements driver.DriverContext. -func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error) { - cfg, err := ParseDSN(dsn) - if err != nil { - return nil, err - } - return &connector{ - cfg: cfg, - }, nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/dsn.go b/vendor/github.com/go-sql-driver/mysql/dsn.go deleted file mode 100644 index 93f3548c..00000000 --- a/vendor/github.com/go-sql-driver/mysql/dsn.go +++ /dev/null @@ -1,560 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "bytes" - "crypto/rsa" - "crypto/tls" - "errors" - "fmt" - "math/big" - "net" - "net/url" - "sort" - "strconv" - "strings" - "time" -) - -var ( - errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?") - errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)") - errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name") - errInvalidDSNUnsafeCollation = errors.New("invalid DSN: interpolateParams can not be used with unsafe collations") -) - -// Config is a configuration parsed from a DSN string. -// If a new Config is created instead of being parsed from a DSN string, -// the NewConfig function should be used, which sets default values. -type Config struct { - User string // Username - Passwd string // Password (requires User) - Net string // Network type - Addr string // Network address (requires Net) - DBName string // Database name - Params map[string]string // Connection parameters - Collation string // Connection collation - Loc *time.Location // Location for time.Time values - MaxAllowedPacket int // Max packet size allowed - ServerPubKey string // Server public key name - pubKey *rsa.PublicKey // Server public key - TLSConfig string // TLS configuration name - tls *tls.Config // TLS configuration - Timeout time.Duration // Dial timeout - ReadTimeout time.Duration // I/O read timeout - WriteTimeout time.Duration // I/O write timeout - - AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE - AllowCleartextPasswords bool // Allows the cleartext client side plugin - AllowNativePasswords bool // Allows the native password authentication method - AllowOldPasswords bool // Allows the old insecure password method - CheckConnLiveness bool // Check connections for liveness before using them - ClientFoundRows bool // Return number of matching rows instead of rows changed - ColumnsWithAlias bool // Prepend table alias to column names - InterpolateParams bool // Interpolate placeholders into query string - MultiStatements bool // Allow multiple statements in one query - ParseTime bool // Parse time values to time.Time - RejectReadOnly bool // Reject read-only connections -} - -// NewConfig creates a new Config and sets default values. -func NewConfig() *Config { - return &Config{ - Collation: defaultCollation, - Loc: time.UTC, - MaxAllowedPacket: defaultMaxAllowedPacket, - AllowNativePasswords: true, - CheckConnLiveness: true, - } -} - -func (cfg *Config) Clone() *Config { - cp := *cfg - if cp.tls != nil { - cp.tls = cfg.tls.Clone() - } - if len(cp.Params) > 0 { - cp.Params = make(map[string]string, len(cfg.Params)) - for k, v := range cfg.Params { - cp.Params[k] = v - } - } - if cfg.pubKey != nil { - cp.pubKey = &rsa.PublicKey{ - N: new(big.Int).Set(cfg.pubKey.N), - E: cfg.pubKey.E, - } - } - return &cp -} - -func (cfg *Config) normalize() error { - if cfg.InterpolateParams && unsafeCollations[cfg.Collation] { - return errInvalidDSNUnsafeCollation - } - - // Set default network if empty - if cfg.Net == "" { - cfg.Net = "tcp" - } - - // Set default address if empty - if cfg.Addr == "" { - switch cfg.Net { - case "tcp": - cfg.Addr = "127.0.0.1:3306" - case "unix": - cfg.Addr = "/tmp/mysql.sock" - default: - return errors.New("default addr for network '" + cfg.Net + "' unknown") - } - } else if cfg.Net == "tcp" { - cfg.Addr = ensureHavePort(cfg.Addr) - } - - switch cfg.TLSConfig { - case "false", "": - // don't set anything - case "true": - cfg.tls = &tls.Config{} - case "skip-verify", "preferred": - cfg.tls = &tls.Config{InsecureSkipVerify: true} - default: - cfg.tls = getTLSConfigClone(cfg.TLSConfig) - if cfg.tls == nil { - return errors.New("invalid value / unknown config name: " + cfg.TLSConfig) - } - } - - if cfg.tls != nil && cfg.tls.ServerName == "" && !cfg.tls.InsecureSkipVerify { - host, _, err := net.SplitHostPort(cfg.Addr) - if err == nil { - cfg.tls.ServerName = host - } - } - - if cfg.ServerPubKey != "" { - cfg.pubKey = getServerPubKey(cfg.ServerPubKey) - if cfg.pubKey == nil { - return errors.New("invalid value / unknown server pub key name: " + cfg.ServerPubKey) - } - } - - return nil -} - -func writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) { - buf.Grow(1 + len(name) + 1 + len(value)) - if !*hasParam { - *hasParam = true - buf.WriteByte('?') - } else { - buf.WriteByte('&') - } - buf.WriteString(name) - buf.WriteByte('=') - buf.WriteString(value) -} - -// FormatDSN formats the given Config into a DSN string which can be passed to -// the driver. -func (cfg *Config) FormatDSN() string { - var buf bytes.Buffer - - // [username[:password]@] - if len(cfg.User) > 0 { - buf.WriteString(cfg.User) - if len(cfg.Passwd) > 0 { - buf.WriteByte(':') - buf.WriteString(cfg.Passwd) - } - buf.WriteByte('@') - } - - // [protocol[(address)]] - if len(cfg.Net) > 0 { - buf.WriteString(cfg.Net) - if len(cfg.Addr) > 0 { - buf.WriteByte('(') - buf.WriteString(cfg.Addr) - buf.WriteByte(')') - } - } - - // /dbname - buf.WriteByte('/') - buf.WriteString(cfg.DBName) - - // [?param1=value1&...¶mN=valueN] - hasParam := false - - if cfg.AllowAllFiles { - hasParam = true - buf.WriteString("?allowAllFiles=true") - } - - if cfg.AllowCleartextPasswords { - writeDSNParam(&buf, &hasParam, "allowCleartextPasswords", "true") - } - - if !cfg.AllowNativePasswords { - writeDSNParam(&buf, &hasParam, "allowNativePasswords", "false") - } - - if cfg.AllowOldPasswords { - writeDSNParam(&buf, &hasParam, "allowOldPasswords", "true") - } - - if !cfg.CheckConnLiveness { - writeDSNParam(&buf, &hasParam, "checkConnLiveness", "false") - } - - if cfg.ClientFoundRows { - writeDSNParam(&buf, &hasParam, "clientFoundRows", "true") - } - - if col := cfg.Collation; col != defaultCollation && len(col) > 0 { - writeDSNParam(&buf, &hasParam, "collation", col) - } - - if cfg.ColumnsWithAlias { - writeDSNParam(&buf, &hasParam, "columnsWithAlias", "true") - } - - if cfg.InterpolateParams { - writeDSNParam(&buf, &hasParam, "interpolateParams", "true") - } - - if cfg.Loc != time.UTC && cfg.Loc != nil { - writeDSNParam(&buf, &hasParam, "loc", url.QueryEscape(cfg.Loc.String())) - } - - if cfg.MultiStatements { - writeDSNParam(&buf, &hasParam, "multiStatements", "true") - } - - if cfg.ParseTime { - writeDSNParam(&buf, &hasParam, "parseTime", "true") - } - - if cfg.ReadTimeout > 0 { - writeDSNParam(&buf, &hasParam, "readTimeout", cfg.ReadTimeout.String()) - } - - if cfg.RejectReadOnly { - writeDSNParam(&buf, &hasParam, "rejectReadOnly", "true") - } - - if len(cfg.ServerPubKey) > 0 { - writeDSNParam(&buf, &hasParam, "serverPubKey", url.QueryEscape(cfg.ServerPubKey)) - } - - if cfg.Timeout > 0 { - writeDSNParam(&buf, &hasParam, "timeout", cfg.Timeout.String()) - } - - if len(cfg.TLSConfig) > 0 { - writeDSNParam(&buf, &hasParam, "tls", url.QueryEscape(cfg.TLSConfig)) - } - - if cfg.WriteTimeout > 0 { - writeDSNParam(&buf, &hasParam, "writeTimeout", cfg.WriteTimeout.String()) - } - - if cfg.MaxAllowedPacket != defaultMaxAllowedPacket { - writeDSNParam(&buf, &hasParam, "maxAllowedPacket", strconv.Itoa(cfg.MaxAllowedPacket)) - } - - // other params - if cfg.Params != nil { - var params []string - for param := range cfg.Params { - params = append(params, param) - } - sort.Strings(params) - for _, param := range params { - writeDSNParam(&buf, &hasParam, param, url.QueryEscape(cfg.Params[param])) - } - } - - return buf.String() -} - -// ParseDSN parses the DSN string to a Config -func ParseDSN(dsn string) (cfg *Config, err error) { - // New config with some default values - cfg = NewConfig() - - // [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN] - // Find the last '/' (since the password or the net addr might contain a '/') - foundSlash := false - for i := len(dsn) - 1; i >= 0; i-- { - if dsn[i] == '/' { - foundSlash = true - var j, k int - - // left part is empty if i <= 0 - if i > 0 { - // [username[:password]@][protocol[(address)]] - // Find the last '@' in dsn[:i] - for j = i; j >= 0; j-- { - if dsn[j] == '@' { - // username[:password] - // Find the first ':' in dsn[:j] - for k = 0; k < j; k++ { - if dsn[k] == ':' { - cfg.Passwd = dsn[k+1 : j] - break - } - } - cfg.User = dsn[:k] - - break - } - } - - // [protocol[(address)]] - // Find the first '(' in dsn[j+1:i] - for k = j + 1; k < i; k++ { - if dsn[k] == '(' { - // dsn[i-1] must be == ')' if an address is specified - if dsn[i-1] != ')' { - if strings.ContainsRune(dsn[k+1:i], ')') { - return nil, errInvalidDSNUnescaped - } - return nil, errInvalidDSNAddr - } - cfg.Addr = dsn[k+1 : i-1] - break - } - } - cfg.Net = dsn[j+1 : k] - } - - // dbname[?param1=value1&...¶mN=valueN] - // Find the first '?' in dsn[i+1:] - for j = i + 1; j < len(dsn); j++ { - if dsn[j] == '?' { - if err = parseDSNParams(cfg, dsn[j+1:]); err != nil { - return - } - break - } - } - cfg.DBName = dsn[i+1 : j] - - break - } - } - - if !foundSlash && len(dsn) > 0 { - return nil, errInvalidDSNNoSlash - } - - if err = cfg.normalize(); err != nil { - return nil, err - } - return -} - -// parseDSNParams parses the DSN "query string" -// Values must be url.QueryEscape'ed -func parseDSNParams(cfg *Config, params string) (err error) { - for _, v := range strings.Split(params, "&") { - param := strings.SplitN(v, "=", 2) - if len(param) != 2 { - continue - } - - // cfg params - switch value := param[1]; param[0] { - // Disable INFILE allowlist / enable all files - case "allowAllFiles": - var isBool bool - cfg.AllowAllFiles, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use cleartext authentication mode (MySQL 5.5.10+) - case "allowCleartextPasswords": - var isBool bool - cfg.AllowCleartextPasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use native password authentication - case "allowNativePasswords": - var isBool bool - cfg.AllowNativePasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use old authentication mode (pre MySQL 4.1) - case "allowOldPasswords": - var isBool bool - cfg.AllowOldPasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Check connections for Liveness before using them - case "checkConnLiveness": - var isBool bool - cfg.CheckConnLiveness, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Switch "rowsAffected" mode - case "clientFoundRows": - var isBool bool - cfg.ClientFoundRows, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Collation - case "collation": - cfg.Collation = value - break - - case "columnsWithAlias": - var isBool bool - cfg.ColumnsWithAlias, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Compression - case "compress": - return errors.New("compression not implemented yet") - - // Enable client side placeholder substitution - case "interpolateParams": - var isBool bool - cfg.InterpolateParams, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Time Location - case "loc": - if value, err = url.QueryUnescape(value); err != nil { - return - } - cfg.Loc, err = time.LoadLocation(value) - if err != nil { - return - } - - // multiple statements in one query - case "multiStatements": - var isBool bool - cfg.MultiStatements, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // time.Time parsing - case "parseTime": - var isBool bool - cfg.ParseTime, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // I/O read Timeout - case "readTimeout": - cfg.ReadTimeout, err = time.ParseDuration(value) - if err != nil { - return - } - - // Reject read-only connections - case "rejectReadOnly": - var isBool bool - cfg.RejectReadOnly, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Server public key - case "serverPubKey": - name, err := url.QueryUnescape(value) - if err != nil { - return fmt.Errorf("invalid value for server pub key name: %v", err) - } - cfg.ServerPubKey = name - - // Strict mode - case "strict": - panic("strict mode has been removed. See https://github.com/go-sql-driver/mysql/wiki/strict-mode") - - // Dial Timeout - case "timeout": - cfg.Timeout, err = time.ParseDuration(value) - if err != nil { - return - } - - // TLS-Encryption - case "tls": - boolValue, isBool := readBool(value) - if isBool { - if boolValue { - cfg.TLSConfig = "true" - } else { - cfg.TLSConfig = "false" - } - } else if vl := strings.ToLower(value); vl == "skip-verify" || vl == "preferred" { - cfg.TLSConfig = vl - } else { - name, err := url.QueryUnescape(value) - if err != nil { - return fmt.Errorf("invalid value for TLS config name: %v", err) - } - cfg.TLSConfig = name - } - - // I/O write Timeout - case "writeTimeout": - cfg.WriteTimeout, err = time.ParseDuration(value) - if err != nil { - return - } - case "maxAllowedPacket": - cfg.MaxAllowedPacket, err = strconv.Atoi(value) - if err != nil { - return - } - default: - // lazy init - if cfg.Params == nil { - cfg.Params = make(map[string]string) - } - - if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil { - return - } - } - } - - return -} - -func ensureHavePort(addr string) string { - if _, _, err := net.SplitHostPort(addr); err != nil { - return net.JoinHostPort(addr, "3306") - } - return addr -} diff --git a/vendor/github.com/go-sql-driver/mysql/errors.go b/vendor/github.com/go-sql-driver/mysql/errors.go deleted file mode 100644 index 760782ff..00000000 --- a/vendor/github.com/go-sql-driver/mysql/errors.go +++ /dev/null @@ -1,65 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "errors" - "fmt" - "log" - "os" -) - -// Various errors the driver might return. Can change between driver versions. -var ( - ErrInvalidConn = errors.New("invalid connection") - ErrMalformPkt = errors.New("malformed packet") - ErrNoTLS = errors.New("TLS requested but server does not support TLS") - ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") - ErrNativePassword = errors.New("this user requires mysql native password authentication.") - ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") - ErrUnknownPlugin = errors.New("this authentication plugin is not supported") - ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") - ErrPktSync = errors.New("commands out of sync. You can't run this command now") - ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") - ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") - ErrBusyBuffer = errors.New("busy buffer") - - // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. - // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn - // to trigger a resend. - // See https://github.com/go-sql-driver/mysql/pull/302 - errBadConnNoWrite = errors.New("bad connection") -) - -var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) - -// Logger is used to log critical error messages. -type Logger interface { - Print(v ...interface{}) -} - -// SetLogger is used to set the logger for critical errors. -// The initial logger is os.Stderr. -func SetLogger(logger Logger) error { - if logger == nil { - return errors.New("logger is nil") - } - errLog = logger - return nil -} - -// MySQLError is an error type which represents a single MySQL error -type MySQLError struct { - Number uint16 - Message string -} - -func (me *MySQLError) Error() string { - return fmt.Sprintf("Error %d: %s", me.Number, me.Message) -} diff --git a/vendor/github.com/go-sql-driver/mysql/fields.go b/vendor/github.com/go-sql-driver/mysql/fields.go deleted file mode 100644 index ed6c7a37..00000000 --- a/vendor/github.com/go-sql-driver/mysql/fields.go +++ /dev/null @@ -1,194 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "database/sql" - "reflect" -) - -func (mf *mysqlField) typeDatabaseName() string { - switch mf.fieldType { - case fieldTypeBit: - return "BIT" - case fieldTypeBLOB: - if mf.charSet != collations[binaryCollation] { - return "TEXT" - } - return "BLOB" - case fieldTypeDate: - return "DATE" - case fieldTypeDateTime: - return "DATETIME" - case fieldTypeDecimal: - return "DECIMAL" - case fieldTypeDouble: - return "DOUBLE" - case fieldTypeEnum: - return "ENUM" - case fieldTypeFloat: - return "FLOAT" - case fieldTypeGeometry: - return "GEOMETRY" - case fieldTypeInt24: - return "MEDIUMINT" - case fieldTypeJSON: - return "JSON" - case fieldTypeLong: - return "INT" - case fieldTypeLongBLOB: - if mf.charSet != collations[binaryCollation] { - return "LONGTEXT" - } - return "LONGBLOB" - case fieldTypeLongLong: - return "BIGINT" - case fieldTypeMediumBLOB: - if mf.charSet != collations[binaryCollation] { - return "MEDIUMTEXT" - } - return "MEDIUMBLOB" - case fieldTypeNewDate: - return "DATE" - case fieldTypeNewDecimal: - return "DECIMAL" - case fieldTypeNULL: - return "NULL" - case fieldTypeSet: - return "SET" - case fieldTypeShort: - return "SMALLINT" - case fieldTypeString: - if mf.charSet == collations[binaryCollation] { - return "BINARY" - } - return "CHAR" - case fieldTypeTime: - return "TIME" - case fieldTypeTimestamp: - return "TIMESTAMP" - case fieldTypeTiny: - return "TINYINT" - case fieldTypeTinyBLOB: - if mf.charSet != collations[binaryCollation] { - return "TINYTEXT" - } - return "TINYBLOB" - case fieldTypeVarChar: - if mf.charSet == collations[binaryCollation] { - return "VARBINARY" - } - return "VARCHAR" - case fieldTypeVarString: - if mf.charSet == collations[binaryCollation] { - return "VARBINARY" - } - return "VARCHAR" - case fieldTypeYear: - return "YEAR" - default: - return "" - } -} - -var ( - scanTypeFloat32 = reflect.TypeOf(float32(0)) - scanTypeFloat64 = reflect.TypeOf(float64(0)) - scanTypeInt8 = reflect.TypeOf(int8(0)) - scanTypeInt16 = reflect.TypeOf(int16(0)) - scanTypeInt32 = reflect.TypeOf(int32(0)) - scanTypeInt64 = reflect.TypeOf(int64(0)) - scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) - scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) - scanTypeNullTime = reflect.TypeOf(nullTime{}) - scanTypeUint8 = reflect.TypeOf(uint8(0)) - scanTypeUint16 = reflect.TypeOf(uint16(0)) - scanTypeUint32 = reflect.TypeOf(uint32(0)) - scanTypeUint64 = reflect.TypeOf(uint64(0)) - scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{}) - scanTypeUnknown = reflect.TypeOf(new(interface{})) -) - -type mysqlField struct { - tableName string - name string - length uint32 - flags fieldFlag - fieldType fieldType - decimals byte - charSet uint8 -} - -func (mf *mysqlField) scanType() reflect.Type { - switch mf.fieldType { - case fieldTypeTiny: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint8 - } - return scanTypeInt8 - } - return scanTypeNullInt - - case fieldTypeShort, fieldTypeYear: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint16 - } - return scanTypeInt16 - } - return scanTypeNullInt - - case fieldTypeInt24, fieldTypeLong: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint32 - } - return scanTypeInt32 - } - return scanTypeNullInt - - case fieldTypeLongLong: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint64 - } - return scanTypeInt64 - } - return scanTypeNullInt - - case fieldTypeFloat: - if mf.flags&flagNotNULL != 0 { - return scanTypeFloat32 - } - return scanTypeNullFloat - - case fieldTypeDouble: - if mf.flags&flagNotNULL != 0 { - return scanTypeFloat64 - } - return scanTypeNullFloat - - case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, - fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, - fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, - fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON, - fieldTypeTime: - return scanTypeRawBytes - - case fieldTypeDate, fieldTypeNewDate, - fieldTypeTimestamp, fieldTypeDateTime: - // NullTime is always returned for more consistent behavior as it can - // handle both cases of parseTime regardless if the field is nullable. - return scanTypeNullTime - - default: - return scanTypeUnknown - } -} diff --git a/vendor/github.com/go-sql-driver/mysql/infile.go b/vendor/github.com/go-sql-driver/mysql/infile.go deleted file mode 100644 index 60effdfc..00000000 --- a/vendor/github.com/go-sql-driver/mysql/infile.go +++ /dev/null @@ -1,182 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "fmt" - "io" - "os" - "strings" - "sync" -) - -var ( - fileRegister map[string]bool - fileRegisterLock sync.RWMutex - readerRegister map[string]func() io.Reader - readerRegisterLock sync.RWMutex -) - -// RegisterLocalFile adds the given file to the file allowlist, -// so that it can be used by "LOAD DATA LOCAL INFILE ". -// Alternatively you can allow the use of all local files with -// the DSN parameter 'allowAllFiles=true' -// -// filePath := "/home/gopher/data.csv" -// mysql.RegisterLocalFile(filePath) -// err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") -// if err != nil { -// ... -// -func RegisterLocalFile(filePath string) { - fileRegisterLock.Lock() - // lazy map init - if fileRegister == nil { - fileRegister = make(map[string]bool) - } - - fileRegister[strings.Trim(filePath, `"`)] = true - fileRegisterLock.Unlock() -} - -// DeregisterLocalFile removes the given filepath from the allowlist. -func DeregisterLocalFile(filePath string) { - fileRegisterLock.Lock() - delete(fileRegister, strings.Trim(filePath, `"`)) - fileRegisterLock.Unlock() -} - -// RegisterReaderHandler registers a handler function which is used -// to receive a io.Reader. -// The Reader can be used by "LOAD DATA LOCAL INFILE Reader::". -// If the handler returns a io.ReadCloser Close() is called when the -// request is finished. -// -// mysql.RegisterReaderHandler("data", func() io.Reader { -// var csvReader io.Reader // Some Reader that returns CSV data -// ... // Open Reader here -// return csvReader -// }) -// err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo") -// if err != nil { -// ... -// -func RegisterReaderHandler(name string, handler func() io.Reader) { - readerRegisterLock.Lock() - // lazy map init - if readerRegister == nil { - readerRegister = make(map[string]func() io.Reader) - } - - readerRegister[name] = handler - readerRegisterLock.Unlock() -} - -// DeregisterReaderHandler removes the ReaderHandler function with -// the given name from the registry. -func DeregisterReaderHandler(name string) { - readerRegisterLock.Lock() - delete(readerRegister, name) - readerRegisterLock.Unlock() -} - -func deferredClose(err *error, closer io.Closer) { - closeErr := closer.Close() - if *err == nil { - *err = closeErr - } -} - -func (mc *mysqlConn) handleInFileRequest(name string) (err error) { - var rdr io.Reader - var data []byte - packetSize := 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP - if mc.maxWriteSize < packetSize { - packetSize = mc.maxWriteSize - } - - if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader - // The server might return an an absolute path. See issue #355. - name = name[idx+8:] - - readerRegisterLock.RLock() - handler, inMap := readerRegister[name] - readerRegisterLock.RUnlock() - - if inMap { - rdr = handler() - if rdr != nil { - if cl, ok := rdr.(io.Closer); ok { - defer deferredClose(&err, cl) - } - } else { - err = fmt.Errorf("Reader '%s' is ", name) - } - } else { - err = fmt.Errorf("Reader '%s' is not registered", name) - } - } else { // File - name = strings.Trim(name, `"`) - fileRegisterLock.RLock() - fr := fileRegister[name] - fileRegisterLock.RUnlock() - if mc.cfg.AllowAllFiles || fr { - var file *os.File - var fi os.FileInfo - - if file, err = os.Open(name); err == nil { - defer deferredClose(&err, file) - - // get file size - if fi, err = file.Stat(); err == nil { - rdr = file - if fileSize := int(fi.Size()); fileSize < packetSize { - packetSize = fileSize - } - } - } - } else { - err = fmt.Errorf("local file '%s' is not registered", name) - } - } - - // send content packets - // if packetSize == 0, the Reader contains no data - if err == nil && packetSize > 0 { - data := make([]byte, 4+packetSize) - var n int - for err == nil { - n, err = rdr.Read(data[4:]) - if n > 0 { - if ioErr := mc.writePacket(data[:4+n]); ioErr != nil { - return ioErr - } - } - } - if err == io.EOF { - err = nil - } - } - - // send empty packet (termination) - if data == nil { - data = make([]byte, 4) - } - if ioErr := mc.writePacket(data[:4]); ioErr != nil { - return ioErr - } - - // read OK packet - if err == nil { - return mc.readResultOK() - } - - mc.readPacket() - return err -} diff --git a/vendor/github.com/go-sql-driver/mysql/packets.go b/vendor/github.com/go-sql-driver/mysql/packets.go deleted file mode 100644 index 6664e5ae..00000000 --- a/vendor/github.com/go-sql-driver/mysql/packets.go +++ /dev/null @@ -1,1349 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "bytes" - "crypto/tls" - "database/sql/driver" - "encoding/binary" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "time" -) - -// Packets documentation: -// http://dev.mysql.com/doc/internals/en/client-server-protocol.html - -// Read packet to buffer 'data' -func (mc *mysqlConn) readPacket() ([]byte, error) { - var prevData []byte - for { - // read packet header - data, err := mc.buf.readNext(4) - if err != nil { - if cerr := mc.canceled.Value(); cerr != nil { - return nil, cerr - } - errLog.Print(err) - mc.Close() - return nil, ErrInvalidConn - } - - // packet length [24 bit] - pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16) - - // check packet sync [8 bit] - if data[3] != mc.sequence { - if data[3] > mc.sequence { - return nil, ErrPktSyncMul - } - return nil, ErrPktSync - } - mc.sequence++ - - // packets with length 0 terminate a previous packet which is a - // multiple of (2^24)-1 bytes long - if pktLen == 0 { - // there was no previous packet - if prevData == nil { - errLog.Print(ErrMalformPkt) - mc.Close() - return nil, ErrInvalidConn - } - - return prevData, nil - } - - // read packet body [pktLen bytes] - data, err = mc.buf.readNext(pktLen) - if err != nil { - if cerr := mc.canceled.Value(); cerr != nil { - return nil, cerr - } - errLog.Print(err) - mc.Close() - return nil, ErrInvalidConn - } - - // return data if this was the last packet - if pktLen < maxPacketSize { - // zero allocations for non-split packets - if prevData == nil { - return data, nil - } - - return append(prevData, data...), nil - } - - prevData = append(prevData, data...) - } -} - -// Write packet buffer 'data' -func (mc *mysqlConn) writePacket(data []byte) error { - pktLen := len(data) - 4 - - if pktLen > mc.maxAllowedPacket { - return ErrPktTooLarge - } - - // Perform a stale connection check. We only perform this check for - // the first query on a connection that has been checked out of the - // connection pool: a fresh connection from the pool is more likely - // to be stale, and it has not performed any previous writes that - // could cause data corruption, so it's safe to return ErrBadConn - // if the check fails. - if mc.reset { - mc.reset = false - conn := mc.netConn - if mc.rawConn != nil { - conn = mc.rawConn - } - var err error - // If this connection has a ReadTimeout which we've been setting on - // reads, reset it to its default value before we attempt a non-blocking - // read, otherwise the scheduler will just time us out before we can read - if mc.cfg.ReadTimeout != 0 { - err = conn.SetReadDeadline(time.Time{}) - } - if err == nil && mc.cfg.CheckConnLiveness { - err = connCheck(conn) - } - if err != nil { - errLog.Print("closing bad idle connection: ", err) - mc.Close() - return driver.ErrBadConn - } - } - - for { - var size int - if pktLen >= maxPacketSize { - data[0] = 0xff - data[1] = 0xff - data[2] = 0xff - size = maxPacketSize - } else { - data[0] = byte(pktLen) - data[1] = byte(pktLen >> 8) - data[2] = byte(pktLen >> 16) - size = pktLen - } - data[3] = mc.sequence - - // Write packet - if mc.writeTimeout > 0 { - if err := mc.netConn.SetWriteDeadline(time.Now().Add(mc.writeTimeout)); err != nil { - return err - } - } - - n, err := mc.netConn.Write(data[:4+size]) - if err == nil && n == 4+size { - mc.sequence++ - if size != maxPacketSize { - return nil - } - pktLen -= size - data = data[size:] - continue - } - - // Handle error - if err == nil { // n != len(data) - mc.cleanup() - errLog.Print(ErrMalformPkt) - } else { - if cerr := mc.canceled.Value(); cerr != nil { - return cerr - } - if n == 0 && pktLen == len(data)-4 { - // only for the first loop iteration when nothing was written yet - return errBadConnNoWrite - } - mc.cleanup() - errLog.Print(err) - } - return ErrInvalidConn - } -} - -/****************************************************************************** -* Initialization Process * -******************************************************************************/ - -// Handshake Initialization Packet -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake -func (mc *mysqlConn) readHandshakePacket() (data []byte, plugin string, err error) { - data, err = mc.readPacket() - if err != nil { - // for init we can rewrite this to ErrBadConn for sql.Driver to retry, since - // in connection initialization we don't risk retrying non-idempotent actions. - if err == ErrInvalidConn { - return nil, "", driver.ErrBadConn - } - return - } - - if data[0] == iERR { - return nil, "", mc.handleErrorPacket(data) - } - - // protocol version [1 byte] - if data[0] < minProtocolVersion { - return nil, "", fmt.Errorf( - "unsupported protocol version %d. Version %d or higher is required", - data[0], - minProtocolVersion, - ) - } - - // server version [null terminated string] - // connection id [4 bytes] - pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4 - - // first part of the password cipher [8 bytes] - authData := data[pos : pos+8] - - // (filler) always 0x00 [1 byte] - pos += 8 + 1 - - // capability flags (lower 2 bytes) [2 bytes] - mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) - if mc.flags&clientProtocol41 == 0 { - return nil, "", ErrOldProtocol - } - if mc.flags&clientSSL == 0 && mc.cfg.tls != nil { - if mc.cfg.TLSConfig == "preferred" { - mc.cfg.tls = nil - } else { - return nil, "", ErrNoTLS - } - } - pos += 2 - - if len(data) > pos { - // character set [1 byte] - // status flags [2 bytes] - // capability flags (upper 2 bytes) [2 bytes] - // length of auth-plugin-data [1 byte] - // reserved (all [00]) [10 bytes] - pos += 1 + 2 + 2 + 1 + 10 - - // second part of the password cipher [mininum 13 bytes], - // where len=MAX(13, length of auth-plugin-data - 8) - // - // The web documentation is ambiguous about the length. However, - // according to mysql-5.7/sql/auth/sql_authentication.cc line 538, - // the 13th byte is "\0 byte, terminating the second part of - // a scramble". So the second part of the password cipher is - // a NULL terminated string that's at least 13 bytes with the - // last byte being NULL. - // - // The official Python library uses the fixed length 12 - // which seems to work but technically could have a hidden bug. - authData = append(authData, data[pos:pos+12]...) - pos += 13 - - // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2) - // \NUL otherwise - if end := bytes.IndexByte(data[pos:], 0x00); end != -1 { - plugin = string(data[pos : pos+end]) - } else { - plugin = string(data[pos:]) - } - - // make a memory safe copy of the cipher slice - var b [20]byte - copy(b[:], authData) - return b[:], plugin, nil - } - - // make a memory safe copy of the cipher slice - var b [8]byte - copy(b[:], authData) - return b[:], plugin, nil -} - -// Client Authentication Packet -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse -func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string) error { - // Adjust client flags based on server support - clientFlags := clientProtocol41 | - clientSecureConn | - clientLongPassword | - clientTransactions | - clientLocalFiles | - clientPluginAuth | - clientMultiResults | - mc.flags&clientLongFlag - - if mc.cfg.ClientFoundRows { - clientFlags |= clientFoundRows - } - - // To enable TLS / SSL - if mc.cfg.tls != nil { - clientFlags |= clientSSL - } - - if mc.cfg.MultiStatements { - clientFlags |= clientMultiStatements - } - - // encode length of the auth plugin data - var authRespLEIBuf [9]byte - authRespLen := len(authResp) - authRespLEI := appendLengthEncodedInteger(authRespLEIBuf[:0], uint64(authRespLen)) - if len(authRespLEI) > 1 { - // if the length can not be written in 1 byte, it must be written as a - // length encoded integer - clientFlags |= clientPluginAuthLenEncClientData - } - - pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1 + len(authRespLEI) + len(authResp) + 21 + 1 - - // To specify a db name - if n := len(mc.cfg.DBName); n > 0 { - clientFlags |= clientConnectWithDB - pktLen += n + 1 - } - - // Calculate packet length and get buffer with that size - data, err := mc.buf.takeSmallBuffer(pktLen + 4) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // ClientFlags [32 bit] - data[4] = byte(clientFlags) - data[5] = byte(clientFlags >> 8) - data[6] = byte(clientFlags >> 16) - data[7] = byte(clientFlags >> 24) - - // MaxPacketSize [32 bit] (none) - data[8] = 0x00 - data[9] = 0x00 - data[10] = 0x00 - data[11] = 0x00 - - // Charset [1 byte] - var found bool - data[12], found = collations[mc.cfg.Collation] - if !found { - // Note possibility for false negatives: - // could be triggered although the collation is valid if the - // collations map does not contain entries the server supports. - return errors.New("unknown collation") - } - - // Filler [23 bytes] (all 0x00) - pos := 13 - for ; pos < 13+23; pos++ { - data[pos] = 0 - } - - // SSL Connection Request Packet - // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest - if mc.cfg.tls != nil { - // Send TLS / SSL request packet - if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil { - return err - } - - // Switch to TLS - tlsConn := tls.Client(mc.netConn, mc.cfg.tls) - if err := tlsConn.Handshake(); err != nil { - return err - } - mc.rawConn = mc.netConn - mc.netConn = tlsConn - mc.buf.nc = tlsConn - } - - // User [null terminated string] - if len(mc.cfg.User) > 0 { - pos += copy(data[pos:], mc.cfg.User) - } - data[pos] = 0x00 - pos++ - - // Auth Data [length encoded integer] - pos += copy(data[pos:], authRespLEI) - pos += copy(data[pos:], authResp) - - // Databasename [null terminated string] - if len(mc.cfg.DBName) > 0 { - pos += copy(data[pos:], mc.cfg.DBName) - data[pos] = 0x00 - pos++ - } - - pos += copy(data[pos:], plugin) - data[pos] = 0x00 - pos++ - - // Send Auth packet - return mc.writePacket(data[:pos]) -} - -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse -func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error { - pktLen := 4 + len(authData) - data, err := mc.buf.takeSmallBuffer(pktLen) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add the auth data [EOF] - copy(data[4:], authData) - return mc.writePacket(data) -} - -/****************************************************************************** -* Command Packets * -******************************************************************************/ - -func (mc *mysqlConn) writeCommandPacket(command byte) error { - // Reset Packet Sequence - mc.sequence = 0 - - data, err := mc.buf.takeSmallBuffer(4 + 1) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Send CMD packet - return mc.writePacket(data) -} - -func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { - // Reset Packet Sequence - mc.sequence = 0 - - pktLen := 1 + len(arg) - data, err := mc.buf.takeBuffer(pktLen + 4) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Add arg - copy(data[5:], arg) - - // Send CMD packet - return mc.writePacket(data) -} - -func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error { - // Reset Packet Sequence - mc.sequence = 0 - - data, err := mc.buf.takeSmallBuffer(4 + 1 + 4) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Add arg [32 bit] - data[5] = byte(arg) - data[6] = byte(arg >> 8) - data[7] = byte(arg >> 16) - data[8] = byte(arg >> 24) - - // Send CMD packet - return mc.writePacket(data) -} - -/****************************************************************************** -* Result Packets * -******************************************************************************/ - -func (mc *mysqlConn) readAuthResult() ([]byte, string, error) { - data, err := mc.readPacket() - if err != nil { - return nil, "", err - } - - // packet indicator - switch data[0] { - - case iOK: - return nil, "", mc.handleOkPacket(data) - - case iAuthMoreData: - return data[1:], "", err - - case iEOF: - if len(data) == 1 { - // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest - return nil, "mysql_old_password", nil - } - pluginEndIndex := bytes.IndexByte(data, 0x00) - if pluginEndIndex < 0 { - return nil, "", ErrMalformPkt - } - plugin := string(data[1:pluginEndIndex]) - authData := data[pluginEndIndex+1:] - return authData, plugin, nil - - default: // Error otherwise - return nil, "", mc.handleErrorPacket(data) - } -} - -// Returns error if Packet is not an 'Result OK'-Packet -func (mc *mysqlConn) readResultOK() error { - data, err := mc.readPacket() - if err != nil { - return err - } - - if data[0] == iOK { - return mc.handleOkPacket(data) - } - return mc.handleErrorPacket(data) -} - -// Result Set Header Packet -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::Resultset -func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) { - data, err := mc.readPacket() - if err == nil { - switch data[0] { - - case iOK: - return 0, mc.handleOkPacket(data) - - case iERR: - return 0, mc.handleErrorPacket(data) - - case iLocalInFile: - return 0, mc.handleInFileRequest(string(data[1:])) - } - - // column count - num, _, n := readLengthEncodedInteger(data) - if n-len(data) == 0 { - return int(num), nil - } - - return 0, ErrMalformPkt - } - return 0, err -} - -// Error Packet -// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-ERR_Packet -func (mc *mysqlConn) handleErrorPacket(data []byte) error { - if data[0] != iERR { - return ErrMalformPkt - } - - // 0xff [1 byte] - - // Error Number [16 bit uint] - errno := binary.LittleEndian.Uint16(data[1:3]) - - // 1792: ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION - // 1290: ER_OPTION_PREVENTS_STATEMENT (returned by Aurora during failover) - if (errno == 1792 || errno == 1290) && mc.cfg.RejectReadOnly { - // Oops; we are connected to a read-only connection, and won't be able - // to issue any write statements. Since RejectReadOnly is configured, - // we throw away this connection hoping this one would have write - // permission. This is specifically for a possible race condition - // during failover (e.g. on AWS Aurora). See README.md for more. - // - // We explicitly close the connection before returning - // driver.ErrBadConn to ensure that `database/sql` purges this - // connection and initiates a new one for next statement next time. - mc.Close() - return driver.ErrBadConn - } - - pos := 3 - - // SQL State [optional: # + 5bytes string] - if data[3] == 0x23 { - //sqlstate := string(data[4 : 4+5]) - pos = 9 - } - - // Error Message [string] - return &MySQLError{ - Number: errno, - Message: string(data[pos:]), - } -} - -func readStatus(b []byte) statusFlag { - return statusFlag(b[0]) | statusFlag(b[1])<<8 -} - -// Ok Packet -// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-OK_Packet -func (mc *mysqlConn) handleOkPacket(data []byte) error { - var n, m int - - // 0x00 [1 byte] - - // Affected rows [Length Coded Binary] - mc.affectedRows, _, n = readLengthEncodedInteger(data[1:]) - - // Insert id [Length Coded Binary] - mc.insertId, _, m = readLengthEncodedInteger(data[1+n:]) - - // server_status [2 bytes] - mc.status = readStatus(data[1+n+m : 1+n+m+2]) - if mc.status&statusMoreResultsExists != 0 { - return nil - } - - // warning count [2 bytes] - - return nil -} - -// Read Packets as Field Packets until EOF-Packet or an Error appears -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnDefinition41 -func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) { - columns := make([]mysqlField, count) - - for i := 0; ; i++ { - data, err := mc.readPacket() - if err != nil { - return nil, err - } - - // EOF Packet - if data[0] == iEOF && (len(data) == 5 || len(data) == 1) { - if i == count { - return columns, nil - } - return nil, fmt.Errorf("column count mismatch n:%d len:%d", count, len(columns)) - } - - // Catalog - pos, err := skipLengthEncodedString(data) - if err != nil { - return nil, err - } - - // Database [len coded string] - n, err := skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Table [len coded string] - if mc.cfg.ColumnsWithAlias { - tableName, _, n, err := readLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - columns[i].tableName = string(tableName) - } else { - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - } - - // Original table [len coded string] - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Name [len coded string] - name, _, n, err := readLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - columns[i].name = string(name) - pos += n - - // Original name [len coded string] - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Filler [uint8] - pos++ - - // Charset [charset, collation uint8] - columns[i].charSet = data[pos] - pos += 2 - - // Length [uint32] - columns[i].length = binary.LittleEndian.Uint32(data[pos : pos+4]) - pos += 4 - - // Field type [uint8] - columns[i].fieldType = fieldType(data[pos]) - pos++ - - // Flags [uint16] - columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) - pos += 2 - - // Decimals [uint8] - columns[i].decimals = data[pos] - //pos++ - - // Default value [len coded binary] - //if pos < len(data) { - // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:]) - //} - } -} - -// Read Packets as Field Packets until EOF-Packet or an Error appears -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow -func (rows *textRows) readRow(dest []driver.Value) error { - mc := rows.mc - - if rows.rs.done { - return io.EOF - } - - data, err := mc.readPacket() - if err != nil { - return err - } - - // EOF Packet - if data[0] == iEOF && len(data) == 5 { - // server_status [2 bytes] - rows.mc.status = readStatus(data[3:]) - rows.rs.done = true - if !rows.HasNextResultSet() { - rows.mc = nil - } - return io.EOF - } - if data[0] == iERR { - rows.mc = nil - return mc.handleErrorPacket(data) - } - - // RowSet Packet - var n int - var isNull bool - pos := 0 - - for i := range dest { - // Read bytes and convert to string - dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) - pos += n - if err == nil { - if !isNull { - if !mc.parseTime { - continue - } else { - switch rows.rs.columns[i].fieldType { - case fieldTypeTimestamp, fieldTypeDateTime, - fieldTypeDate, fieldTypeNewDate: - dest[i], err = parseDateTime( - dest[i].([]byte), - mc.cfg.Loc, - ) - if err == nil { - continue - } - default: - continue - } - } - - } else { - dest[i] = nil - continue - } - } - return err // err != nil - } - - return nil -} - -// Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read -func (mc *mysqlConn) readUntilEOF() error { - for { - data, err := mc.readPacket() - if err != nil { - return err - } - - switch data[0] { - case iERR: - return mc.handleErrorPacket(data) - case iEOF: - if len(data) == 5 { - mc.status = readStatus(data[3:]) - } - return nil - } - } -} - -/****************************************************************************** -* Prepared Statements * -******************************************************************************/ - -// Prepare Result Packets -// http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html -func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) { - data, err := stmt.mc.readPacket() - if err == nil { - // packet indicator [1 byte] - if data[0] != iOK { - return 0, stmt.mc.handleErrorPacket(data) - } - - // statement id [4 bytes] - stmt.id = binary.LittleEndian.Uint32(data[1:5]) - - // Column count [16 bit uint] - columnCount := binary.LittleEndian.Uint16(data[5:7]) - - // Param count [16 bit uint] - stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9])) - - // Reserved [8 bit] - - // Warning count [16 bit uint] - - return columnCount, nil - } - return 0, err -} - -// http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html -func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error { - maxLen := stmt.mc.maxAllowedPacket - 1 - pktLen := maxLen - - // After the header (bytes 0-3) follows before the data: - // 1 byte command - // 4 bytes stmtID - // 2 bytes paramID - const dataOffset = 1 + 4 + 2 - - // Cannot use the write buffer since - // a) the buffer is too small - // b) it is in use - data := make([]byte, 4+1+4+2+len(arg)) - - copy(data[4+dataOffset:], arg) - - for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset { - if dataOffset+argLen < maxLen { - pktLen = dataOffset + argLen - } - - stmt.mc.sequence = 0 - // Add command byte [1 byte] - data[4] = comStmtSendLongData - - // Add stmtID [32 bit] - data[5] = byte(stmt.id) - data[6] = byte(stmt.id >> 8) - data[7] = byte(stmt.id >> 16) - data[8] = byte(stmt.id >> 24) - - // Add paramID [16 bit] - data[9] = byte(paramID) - data[10] = byte(paramID >> 8) - - // Send CMD packet - err := stmt.mc.writePacket(data[:4+pktLen]) - if err == nil { - data = data[pktLen-dataOffset:] - continue - } - return err - - } - - // Reset Packet Sequence - stmt.mc.sequence = 0 - return nil -} - -// Execute Prepared Statement -// http://dev.mysql.com/doc/internals/en/com-stmt-execute.html -func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { - if len(args) != stmt.paramCount { - return fmt.Errorf( - "argument count mismatch (got: %d; has: %d)", - len(args), - stmt.paramCount, - ) - } - - const minPktLen = 4 + 1 + 4 + 1 + 4 - mc := stmt.mc - - // Determine threshold dynamically to avoid packet size shortage. - longDataSize := mc.maxAllowedPacket / (stmt.paramCount + 1) - if longDataSize < 64 { - longDataSize = 64 - } - - // Reset packet-sequence - mc.sequence = 0 - - var data []byte - var err error - - if len(args) == 0 { - data, err = mc.buf.takeBuffer(minPktLen) - } else { - data, err = mc.buf.takeCompleteBuffer() - // In this case the len(data) == cap(data) which is used to optimise the flow below. - } - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // command [1 byte] - data[4] = comStmtExecute - - // statement_id [4 bytes] - data[5] = byte(stmt.id) - data[6] = byte(stmt.id >> 8) - data[7] = byte(stmt.id >> 16) - data[8] = byte(stmt.id >> 24) - - // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte] - data[9] = 0x00 - - // iteration_count (uint32(1)) [4 bytes] - data[10] = 0x01 - data[11] = 0x00 - data[12] = 0x00 - data[13] = 0x00 - - if len(args) > 0 { - pos := minPktLen - - var nullMask []byte - if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= cap(data) { - // buffer has to be extended but we don't know by how much so - // we depend on append after all data with known sizes fit. - // We stop at that because we deal with a lot of columns here - // which makes the required allocation size hard to guess. - tmp := make([]byte, pos+maskLen+typesLen) - copy(tmp[:pos], data[:pos]) - data = tmp - nullMask = data[pos : pos+maskLen] - // No need to clean nullMask as make ensures that. - pos += maskLen - } else { - nullMask = data[pos : pos+maskLen] - for i := range nullMask { - nullMask[i] = 0 - } - pos += maskLen - } - - // newParameterBoundFlag 1 [1 byte] - data[pos] = 0x01 - pos++ - - // type of each parameter [len(args)*2 bytes] - paramTypes := data[pos:] - pos += len(args) * 2 - - // value of each parameter [n bytes] - paramValues := data[pos:pos] - valuesCap := cap(paramValues) - - for i, arg := range args { - // build NULL-bitmap - if arg == nil { - nullMask[i/8] |= 1 << (uint(i) & 7) - paramTypes[i+i] = byte(fieldTypeNULL) - paramTypes[i+i+1] = 0x00 - continue - } - - if v, ok := arg.(json.RawMessage); ok { - arg = []byte(v) - } - // cache types and values - switch v := arg.(type) { - case int64: - paramTypes[i+i] = byte(fieldTypeLongLong) - paramTypes[i+i+1] = 0x00 - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - uint64(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(uint64(v))..., - ) - } - - case uint64: - paramTypes[i+i] = byte(fieldTypeLongLong) - paramTypes[i+i+1] = 0x80 // type is unsigned - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - uint64(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(uint64(v))..., - ) - } - - case float64: - paramTypes[i+i] = byte(fieldTypeDouble) - paramTypes[i+i+1] = 0x00 - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - math.Float64bits(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(math.Float64bits(v))..., - ) - } - - case bool: - paramTypes[i+i] = byte(fieldTypeTiny) - paramTypes[i+i+1] = 0x00 - - if v { - paramValues = append(paramValues, 0x01) - } else { - paramValues = append(paramValues, 0x00) - } - - case []byte: - // Common case (non-nil value) first - if v != nil { - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - if len(v) < longDataSize { - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(v)), - ) - paramValues = append(paramValues, v...) - } else { - if err := stmt.writeCommandLongData(i, v); err != nil { - return err - } - } - continue - } - - // Handle []byte(nil) as a NULL value - nullMask[i/8] |= 1 << (uint(i) & 7) - paramTypes[i+i] = byte(fieldTypeNULL) - paramTypes[i+i+1] = 0x00 - - case string: - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - if len(v) < longDataSize { - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(v)), - ) - paramValues = append(paramValues, v...) - } else { - if err := stmt.writeCommandLongData(i, []byte(v)); err != nil { - return err - } - } - - case time.Time: - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - var a [64]byte - var b = a[:0] - - if v.IsZero() { - b = append(b, "0000-00-00"...) - } else { - b, err = appendDateTime(b, v.In(mc.cfg.Loc)) - if err != nil { - return err - } - } - - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(b)), - ) - paramValues = append(paramValues, b...) - - default: - return fmt.Errorf("cannot convert type: %T", arg) - } - } - - // Check if param values exceeded the available buffer - // In that case we must build the data packet with the new values buffer - if valuesCap != cap(paramValues) { - data = append(data[:pos], paramValues...) - if err = mc.buf.store(data); err != nil { - errLog.Print(err) - return errBadConnNoWrite - } - } - - pos += len(paramValues) - data = data[:pos] - } - - return mc.writePacket(data) -} - -func (mc *mysqlConn) discardResults() error { - for mc.status&statusMoreResultsExists != 0 { - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return err - } - if resLen > 0 { - // columns - if err := mc.readUntilEOF(); err != nil { - return err - } - // rows - if err := mc.readUntilEOF(); err != nil { - return err - } - } - } - return nil -} - -// http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html -func (rows *binaryRows) readRow(dest []driver.Value) error { - data, err := rows.mc.readPacket() - if err != nil { - return err - } - - // packet indicator [1 byte] - if data[0] != iOK { - // EOF Packet - if data[0] == iEOF && len(data) == 5 { - rows.mc.status = readStatus(data[3:]) - rows.rs.done = true - if !rows.HasNextResultSet() { - rows.mc = nil - } - return io.EOF - } - mc := rows.mc - rows.mc = nil - - // Error otherwise - return mc.handleErrorPacket(data) - } - - // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes] - pos := 1 + (len(dest)+7+2)>>3 - nullMask := data[1:pos] - - for i := range dest { - // Field is NULL - // (byte >> bit-pos) % 2 == 1 - if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 { - dest[i] = nil - continue - } - - // Convert to byte-coded string - switch rows.rs.columns[i].fieldType { - case fieldTypeNULL: - dest[i] = nil - continue - - // Numeric Types - case fieldTypeTiny: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(data[pos]) - } else { - dest[i] = int64(int8(data[pos])) - } - pos++ - continue - - case fieldTypeShort, fieldTypeYear: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2])) - } else { - dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2]))) - } - pos += 2 - continue - - case fieldTypeInt24, fieldTypeLong: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4])) - } else { - dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4]))) - } - pos += 4 - continue - - case fieldTypeLongLong: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - val := binary.LittleEndian.Uint64(data[pos : pos+8]) - if val > math.MaxInt64 { - dest[i] = uint64ToString(val) - } else { - dest[i] = int64(val) - } - } else { - dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8])) - } - pos += 8 - continue - - case fieldTypeFloat: - dest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])) - pos += 4 - continue - - case fieldTypeDouble: - dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8])) - pos += 8 - continue - - // Length coded Binary Strings - case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, - fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, - fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, - fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON: - var isNull bool - var n int - dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) - pos += n - if err == nil { - if !isNull { - continue - } else { - dest[i] = nil - continue - } - } - return err - - case - fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD - fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal] - fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal] - - num, isNull, n := readLengthEncodedInteger(data[pos:]) - pos += n - - switch { - case isNull: - dest[i] = nil - continue - case rows.rs.columns[i].fieldType == fieldTypeTime: - // database/sql does not support an equivalent to TIME, return a string - var dstlen uint8 - switch decimals := rows.rs.columns[i].decimals; decimals { - case 0x00, 0x1f: - dstlen = 8 - case 1, 2, 3, 4, 5, 6: - dstlen = 8 + 1 + decimals - default: - return fmt.Errorf( - "protocol error, illegal decimals value %d", - rows.rs.columns[i].decimals, - ) - } - dest[i], err = formatBinaryTime(data[pos:pos+int(num)], dstlen) - case rows.mc.parseTime: - dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc) - default: - var dstlen uint8 - if rows.rs.columns[i].fieldType == fieldTypeDate { - dstlen = 10 - } else { - switch decimals := rows.rs.columns[i].decimals; decimals { - case 0x00, 0x1f: - dstlen = 19 - case 1, 2, 3, 4, 5, 6: - dstlen = 19 + 1 + decimals - default: - return fmt.Errorf( - "protocol error, illegal decimals value %d", - rows.rs.columns[i].decimals, - ) - } - } - dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen) - } - - if err == nil { - pos += int(num) - continue - } else { - return err - } - - // Please report if this happens! - default: - return fmt.Errorf("unknown field type %d", rows.rs.columns[i].fieldType) - } - } - - return nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/result.go b/vendor/github.com/go-sql-driver/mysql/result.go deleted file mode 100644 index c6438d03..00000000 --- a/vendor/github.com/go-sql-driver/mysql/result.go +++ /dev/null @@ -1,22 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -type mysqlResult struct { - affectedRows int64 - insertId int64 -} - -func (res *mysqlResult) LastInsertId() (int64, error) { - return res.insertId, nil -} - -func (res *mysqlResult) RowsAffected() (int64, error) { - return res.affectedRows, nil -} diff --git a/vendor/github.com/go-sql-driver/mysql/rows.go b/vendor/github.com/go-sql-driver/mysql/rows.go deleted file mode 100644 index 888bdb5f..00000000 --- a/vendor/github.com/go-sql-driver/mysql/rows.go +++ /dev/null @@ -1,223 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "database/sql/driver" - "io" - "math" - "reflect" -) - -type resultSet struct { - columns []mysqlField - columnNames []string - done bool -} - -type mysqlRows struct { - mc *mysqlConn - rs resultSet - finish func() -} - -type binaryRows struct { - mysqlRows -} - -type textRows struct { - mysqlRows -} - -func (rows *mysqlRows) Columns() []string { - if rows.rs.columnNames != nil { - return rows.rs.columnNames - } - - columns := make([]string, len(rows.rs.columns)) - if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias { - for i := range columns { - if tableName := rows.rs.columns[i].tableName; len(tableName) > 0 { - columns[i] = tableName + "." + rows.rs.columns[i].name - } else { - columns[i] = rows.rs.columns[i].name - } - } - } else { - for i := range columns { - columns[i] = rows.rs.columns[i].name - } - } - - rows.rs.columnNames = columns - return columns -} - -func (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string { - return rows.rs.columns[i].typeDatabaseName() -} - -// func (rows *mysqlRows) ColumnTypeLength(i int) (length int64, ok bool) { -// return int64(rows.rs.columns[i].length), true -// } - -func (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) { - return rows.rs.columns[i].flags&flagNotNULL == 0, true -} - -func (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, bool) { - column := rows.rs.columns[i] - decimals := int64(column.decimals) - - switch column.fieldType { - case fieldTypeDecimal, fieldTypeNewDecimal: - if decimals > 0 { - return int64(column.length) - 2, decimals, true - } - return int64(column.length) - 1, decimals, true - case fieldTypeTimestamp, fieldTypeDateTime, fieldTypeTime: - return decimals, decimals, true - case fieldTypeFloat, fieldTypeDouble: - if decimals == 0x1f { - return math.MaxInt64, math.MaxInt64, true - } - return math.MaxInt64, decimals, true - } - - return 0, 0, false -} - -func (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type { - return rows.rs.columns[i].scanType() -} - -func (rows *mysqlRows) Close() (err error) { - if f := rows.finish; f != nil { - f() - rows.finish = nil - } - - mc := rows.mc - if mc == nil { - return nil - } - if err := mc.error(); err != nil { - return err - } - - // flip the buffer for this connection if we need to drain it. - // note that for a successful query (i.e. one where rows.next() - // has been called until it returns false), `rows.mc` will be nil - // by the time the user calls `(*Rows).Close`, so we won't reach this - // see: https://github.com/golang/go/commit/651ddbdb5056ded455f47f9c494c67b389622a47 - mc.buf.flip() - - // Remove unread packets from stream - if !rows.rs.done { - err = mc.readUntilEOF() - } - if err == nil { - if err = mc.discardResults(); err != nil { - return err - } - } - - rows.mc = nil - return err -} - -func (rows *mysqlRows) HasNextResultSet() (b bool) { - if rows.mc == nil { - return false - } - return rows.mc.status&statusMoreResultsExists != 0 -} - -func (rows *mysqlRows) nextResultSet() (int, error) { - if rows.mc == nil { - return 0, io.EOF - } - if err := rows.mc.error(); err != nil { - return 0, err - } - - // Remove unread packets from stream - if !rows.rs.done { - if err := rows.mc.readUntilEOF(); err != nil { - return 0, err - } - rows.rs.done = true - } - - if !rows.HasNextResultSet() { - rows.mc = nil - return 0, io.EOF - } - rows.rs = resultSet{} - return rows.mc.readResultSetHeaderPacket() -} - -func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) { - for { - resLen, err := rows.nextResultSet() - if err != nil { - return 0, err - } - - if resLen > 0 { - return resLen, nil - } - - rows.rs.done = true - } -} - -func (rows *binaryRows) NextResultSet() error { - resLen, err := rows.nextNotEmptyResultSet() - if err != nil { - return err - } - - rows.rs.columns, err = rows.mc.readColumns(resLen) - return err -} - -func (rows *binaryRows) Next(dest []driver.Value) error { - if mc := rows.mc; mc != nil { - if err := mc.error(); err != nil { - return err - } - - // Fetch next row from stream - return rows.readRow(dest) - } - return io.EOF -} - -func (rows *textRows) NextResultSet() (err error) { - resLen, err := rows.nextNotEmptyResultSet() - if err != nil { - return err - } - - rows.rs.columns, err = rows.mc.readColumns(resLen) - return err -} - -func (rows *textRows) Next(dest []driver.Value) error { - if mc := rows.mc; mc != nil { - if err := mc.error(); err != nil { - return err - } - - // Fetch next row from stream - return rows.readRow(dest) - } - return io.EOF -} diff --git a/vendor/github.com/go-sql-driver/mysql/statement.go b/vendor/github.com/go-sql-driver/mysql/statement.go deleted file mode 100644 index 18a3ae49..00000000 --- a/vendor/github.com/go-sql-driver/mysql/statement.go +++ /dev/null @@ -1,220 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "database/sql/driver" - "encoding/json" - "fmt" - "io" - "reflect" -) - -type mysqlStmt struct { - mc *mysqlConn - id uint32 - paramCount int -} - -func (stmt *mysqlStmt) Close() error { - if stmt.mc == nil || stmt.mc.closed.IsSet() { - // driver.Stmt.Close can be called more than once, thus this function - // has to be idempotent. - // See also Issue #450 and golang/go#16019. - //errLog.Print(ErrInvalidConn) - return driver.ErrBadConn - } - - err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id) - stmt.mc = nil - return err -} - -func (stmt *mysqlStmt) NumInput() int { - return stmt.paramCount -} - -func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter { - return converter{} -} - -func (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err error) { - nv.Value, err = converter{}.ConvertValue(nv.Value) - return -} - -func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { - if stmt.mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := stmt.writeExecutePacket(args) - if err != nil { - return nil, stmt.mc.markBadConn(err) - } - - mc := stmt.mc - - mc.affectedRows = 0 - mc.insertId = 0 - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return nil, err - } - - if resLen > 0 { - // Columns - if err = mc.readUntilEOF(); err != nil { - return nil, err - } - - // Rows - if err := mc.readUntilEOF(); err != nil { - return nil, err - } - } - - if err := mc.discardResults(); err != nil { - return nil, err - } - - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, nil -} - -func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { - return stmt.query(args) -} - -func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { - if stmt.mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := stmt.writeExecutePacket(args) - if err != nil { - return nil, stmt.mc.markBadConn(err) - } - - mc := stmt.mc - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return nil, err - } - - rows := new(binaryRows) - - if resLen > 0 { - rows.mc = mc - rows.rs.columns, err = mc.readColumns(resLen) - } else { - rows.rs.done = true - - switch err := rows.NextResultSet(); err { - case nil, io.EOF: - return rows, nil - default: - return nil, err - } - } - - return rows, err -} - -var jsonType = reflect.TypeOf(json.RawMessage{}) - -type converter struct{} - -// ConvertValue mirrors the reference/default converter in database/sql/driver -// with _one_ exception. We support uint64 with their high bit and the default -// implementation does not. This function should be kept in sync with -// database/sql/driver defaultConverter.ConvertValue() except for that -// deliberate difference. -func (c converter) ConvertValue(v interface{}) (driver.Value, error) { - if driver.IsValue(v) { - return v, nil - } - - if vr, ok := v.(driver.Valuer); ok { - sv, err := callValuerValue(vr) - if err != nil { - return nil, err - } - if driver.IsValue(sv) { - return sv, nil - } - // A value returend from the Valuer interface can be "a type handled by - // a database driver's NamedValueChecker interface" so we should accept - // uint64 here as well. - if u, ok := sv.(uint64); ok { - return u, nil - } - return nil, fmt.Errorf("non-Value type %T returned from Value", sv) - } - rv := reflect.ValueOf(v) - switch rv.Kind() { - case reflect.Ptr: - // indirect pointers - if rv.IsNil() { - return nil, nil - } else { - return c.ConvertValue(rv.Elem().Interface()) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int(), nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return rv.Uint(), nil - case reflect.Float32, reflect.Float64: - return rv.Float(), nil - case reflect.Bool: - return rv.Bool(), nil - case reflect.Slice: - switch t := rv.Type(); { - case t == jsonType: - return v, nil - case t.Elem().Kind() == reflect.Uint8: - return rv.Bytes(), nil - default: - return nil, fmt.Errorf("unsupported type %T, a slice of %s", v, t.Elem().Kind()) - } - case reflect.String: - return rv.String(), nil - } - return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) -} - -var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() - -// callValuerValue returns vr.Value(), with one exception: -// If vr.Value is an auto-generated method on a pointer type and the -// pointer is nil, it would panic at runtime in the panicwrap -// method. Treat it like nil instead. -// -// This is so people can implement driver.Value on value types and -// still use nil pointers to those types to mean nil/NULL, just like -// string/*string. -// -// This is an exact copy of the same-named unexported function from the -// database/sql package. -func callValuerValue(vr driver.Valuer) (v driver.Value, err error) { - if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr && - rv.IsNil() && - rv.Type().Elem().Implements(valuerReflectType) { - return nil, nil - } - return vr.Value() -} diff --git a/vendor/github.com/go-sql-driver/mysql/transaction.go b/vendor/github.com/go-sql-driver/mysql/transaction.go deleted file mode 100644 index 417d7279..00000000 --- a/vendor/github.com/go-sql-driver/mysql/transaction.go +++ /dev/null @@ -1,31 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -type mysqlTx struct { - mc *mysqlConn -} - -func (tx *mysqlTx) Commit() (err error) { - if tx.mc == nil || tx.mc.closed.IsSet() { - return ErrInvalidConn - } - err = tx.mc.exec("COMMIT") - tx.mc = nil - return -} - -func (tx *mysqlTx) Rollback() (err error) { - if tx.mc == nil || tx.mc.closed.IsSet() { - return ErrInvalidConn - } - err = tx.mc.exec("ROLLBACK") - tx.mc = nil - return -} diff --git a/vendor/github.com/go-sql-driver/mysql/utils.go b/vendor/github.com/go-sql-driver/mysql/utils.go deleted file mode 100644 index d6545f5b..00000000 --- a/vendor/github.com/go-sql-driver/mysql/utils.go +++ /dev/null @@ -1,868 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "crypto/tls" - "database/sql" - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "io" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -// Registry for custom tls.Configs -var ( - tlsConfigLock sync.RWMutex - tlsConfigRegistry map[string]*tls.Config -) - -// RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. -// Use the key as a value in the DSN where tls=value. -// -// Note: The provided tls.Config is exclusively owned by the driver after -// registering it. -// -// rootCertPool := x509.NewCertPool() -// pem, err := ioutil.ReadFile("/path/ca-cert.pem") -// if err != nil { -// log.Fatal(err) -// } -// if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { -// log.Fatal("Failed to append PEM.") -// } -// clientCert := make([]tls.Certificate, 0, 1) -// certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem") -// if err != nil { -// log.Fatal(err) -// } -// clientCert = append(clientCert, certs) -// mysql.RegisterTLSConfig("custom", &tls.Config{ -// RootCAs: rootCertPool, -// Certificates: clientCert, -// }) -// db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom") -// -func RegisterTLSConfig(key string, config *tls.Config) error { - if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" || strings.ToLower(key) == "preferred" { - return fmt.Errorf("key '%s' is reserved", key) - } - - tlsConfigLock.Lock() - if tlsConfigRegistry == nil { - tlsConfigRegistry = make(map[string]*tls.Config) - } - - tlsConfigRegistry[key] = config - tlsConfigLock.Unlock() - return nil -} - -// DeregisterTLSConfig removes the tls.Config associated with key. -func DeregisterTLSConfig(key string) { - tlsConfigLock.Lock() - if tlsConfigRegistry != nil { - delete(tlsConfigRegistry, key) - } - tlsConfigLock.Unlock() -} - -func getTLSConfigClone(key string) (config *tls.Config) { - tlsConfigLock.RLock() - if v, ok := tlsConfigRegistry[key]; ok { - config = v.Clone() - } - tlsConfigLock.RUnlock() - return -} - -// Returns the bool value of the input. -// The 2nd return value indicates if the input was a valid bool value -func readBool(input string) (value bool, valid bool) { - switch input { - case "1", "true", "TRUE", "True": - return true, true - case "0", "false", "FALSE", "False": - return false, true - } - - // Not a valid bool value - return -} - -/****************************************************************************** -* Time related utils * -******************************************************************************/ - -func parseDateTime(b []byte, loc *time.Location) (time.Time, error) { - const base = "0000-00-00 00:00:00.000000" - switch len(b) { - case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM" - if string(b) == base[:len(b)] { - return time.Time{}, nil - } - - year, err := parseByteYear(b) - if err != nil { - return time.Time{}, err - } - if year <= 0 { - year = 1 - } - - if b[4] != '-' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[4]) - } - - m, err := parseByte2Digits(b[5], b[6]) - if err != nil { - return time.Time{}, err - } - if m <= 0 { - m = 1 - } - month := time.Month(m) - - if b[7] != '-' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[7]) - } - - day, err := parseByte2Digits(b[8], b[9]) - if err != nil { - return time.Time{}, err - } - if day <= 0 { - day = 1 - } - if len(b) == 10 { - return time.Date(year, month, day, 0, 0, 0, 0, loc), nil - } - - if b[10] != ' ' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[10]) - } - - hour, err := parseByte2Digits(b[11], b[12]) - if err != nil { - return time.Time{}, err - } - if b[13] != ':' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[13]) - } - - min, err := parseByte2Digits(b[14], b[15]) - if err != nil { - return time.Time{}, err - } - if b[16] != ':' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[16]) - } - - sec, err := parseByte2Digits(b[17], b[18]) - if err != nil { - return time.Time{}, err - } - if len(b) == 19 { - return time.Date(year, month, day, hour, min, sec, 0, loc), nil - } - - if b[19] != '.' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[19]) - } - nsec, err := parseByteNanoSec(b[20:]) - if err != nil { - return time.Time{}, err - } - return time.Date(year, month, day, hour, min, sec, nsec, loc), nil - default: - return time.Time{}, fmt.Errorf("invalid time bytes: %s", b) - } -} - -func parseByteYear(b []byte) (int, error) { - year, n := 0, 1000 - for i := 0; i < 4; i++ { - v, err := bToi(b[i]) - if err != nil { - return 0, err - } - year += v * n - n = n / 10 - } - return year, nil -} - -func parseByte2Digits(b1, b2 byte) (int, error) { - d1, err := bToi(b1) - if err != nil { - return 0, err - } - d2, err := bToi(b2) - if err != nil { - return 0, err - } - return d1*10 + d2, nil -} - -func parseByteNanoSec(b []byte) (int, error) { - ns, digit := 0, 100000 // max is 6-digits - for i := 0; i < len(b); i++ { - v, err := bToi(b[i]) - if err != nil { - return 0, err - } - ns += v * digit - digit /= 10 - } - // nanoseconds has 10-digits. (needs to scale digits) - // 10 - 6 = 4, so we have to multiple 1000. - return ns * 1000, nil -} - -func bToi(b byte) (int, error) { - if b < '0' || b > '9' { - return 0, errors.New("not [0-9]") - } - return int(b - '0'), nil -} - -func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) { - switch num { - case 0: - return time.Time{}, nil - case 4: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - 0, 0, 0, 0, - loc, - ), nil - case 7: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds - 0, - loc, - ), nil - case 11: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds - int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds - loc, - ), nil - } - return nil, fmt.Errorf("invalid DATETIME packet length %d", num) -} - -func appendDateTime(buf []byte, t time.Time) ([]byte, error) { - year, month, day := t.Date() - hour, min, sec := t.Clock() - nsec := t.Nanosecond() - - if year < 1 || year > 9999 { - return buf, errors.New("year is not in the range [1, 9999]: " + strconv.Itoa(year)) // use errors.New instead of fmt.Errorf to avoid year escape to heap - } - year100 := year / 100 - year1 := year % 100 - - var localBuf [len("2006-01-02T15:04:05.999999999")]byte // does not escape - localBuf[0], localBuf[1], localBuf[2], localBuf[3] = digits10[year100], digits01[year100], digits10[year1], digits01[year1] - localBuf[4] = '-' - localBuf[5], localBuf[6] = digits10[month], digits01[month] - localBuf[7] = '-' - localBuf[8], localBuf[9] = digits10[day], digits01[day] - - if hour == 0 && min == 0 && sec == 0 && nsec == 0 { - return append(buf, localBuf[:10]...), nil - } - - localBuf[10] = ' ' - localBuf[11], localBuf[12] = digits10[hour], digits01[hour] - localBuf[13] = ':' - localBuf[14], localBuf[15] = digits10[min], digits01[min] - localBuf[16] = ':' - localBuf[17], localBuf[18] = digits10[sec], digits01[sec] - - if nsec == 0 { - return append(buf, localBuf[:19]...), nil - } - nsec100000000 := nsec / 100000000 - nsec1000000 := (nsec / 1000000) % 100 - nsec10000 := (nsec / 10000) % 100 - nsec100 := (nsec / 100) % 100 - nsec1 := nsec % 100 - localBuf[19] = '.' - - // milli second - localBuf[20], localBuf[21], localBuf[22] = - digits01[nsec100000000], digits10[nsec1000000], digits01[nsec1000000] - // micro second - localBuf[23], localBuf[24], localBuf[25] = - digits10[nsec10000], digits01[nsec10000], digits10[nsec100] - // nano second - localBuf[26], localBuf[27], localBuf[28] = - digits01[nsec100], digits10[nsec1], digits01[nsec1] - - // trim trailing zeros - n := len(localBuf) - for n > 0 && localBuf[n-1] == '0' { - n-- - } - - return append(buf, localBuf[:n]...), nil -} - -// zeroDateTime is used in formatBinaryDateTime to avoid an allocation -// if the DATE or DATETIME has the zero value. -// It must never be changed. -// The current behavior depends on database/sql copying the result. -var zeroDateTime = []byte("0000-00-00 00:00:00.000000") - -const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" -const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999" - -func appendMicrosecs(dst, src []byte, decimals int) []byte { - if decimals <= 0 { - return dst - } - if len(src) == 0 { - return append(dst, ".000000"[:decimals+1]...) - } - - microsecs := binary.LittleEndian.Uint32(src[:4]) - p1 := byte(microsecs / 10000) - microsecs -= 10000 * uint32(p1) - p2 := byte(microsecs / 100) - microsecs -= 100 * uint32(p2) - p3 := byte(microsecs) - - switch decimals { - default: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - digits10[p3], digits01[p3], - ) - case 1: - return append(dst, '.', - digits10[p1], - ) - case 2: - return append(dst, '.', - digits10[p1], digits01[p1], - ) - case 3: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], - ) - case 4: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - ) - case 5: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - digits10[p3], - ) - } -} - -func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) { - // length expects the deterministic length of the zero value, - // negative time and 100+ hours are automatically added if needed - if len(src) == 0 { - return zeroDateTime[:length], nil - } - var dst []byte // return value - var p1, p2, p3 byte // current digit pair - - switch length { - case 10, 19, 21, 22, 23, 24, 25, 26: - default: - t := "DATE" - if length > 10 { - t += "TIME" - } - return nil, fmt.Errorf("illegal %s length %d", t, length) - } - switch len(src) { - case 4, 7, 11: - default: - t := "DATE" - if length > 10 { - t += "TIME" - } - return nil, fmt.Errorf("illegal %s packet length %d", t, len(src)) - } - dst = make([]byte, 0, length) - // start with the date - year := binary.LittleEndian.Uint16(src[:2]) - pt := year / 100 - p1 = byte(year - 100*uint16(pt)) - p2, p3 = src[2], src[3] - dst = append(dst, - digits10[pt], digits01[pt], - digits10[p1], digits01[p1], '-', - digits10[p2], digits01[p2], '-', - digits10[p3], digits01[p3], - ) - if length == 10 { - return dst, nil - } - if len(src) == 4 { - return append(dst, zeroDateTime[10:length]...), nil - } - dst = append(dst, ' ') - p1 = src[4] // hour - src = src[5:] - - // p1 is 2-digit hour, src is after hour - p2, p3 = src[0], src[1] - dst = append(dst, - digits10[p1], digits01[p1], ':', - digits10[p2], digits01[p2], ':', - digits10[p3], digits01[p3], - ) - return appendMicrosecs(dst, src[2:], int(length)-20), nil -} - -func formatBinaryTime(src []byte, length uint8) (driver.Value, error) { - // length expects the deterministic length of the zero value, - // negative time and 100+ hours are automatically added if needed - if len(src) == 0 { - return zeroDateTime[11 : 11+length], nil - } - var dst []byte // return value - - switch length { - case - 8, // time (can be up to 10 when negative and 100+ hours) - 10, 11, 12, 13, 14, 15: // time with fractional seconds - default: - return nil, fmt.Errorf("illegal TIME length %d", length) - } - switch len(src) { - case 8, 12: - default: - return nil, fmt.Errorf("invalid TIME packet length %d", len(src)) - } - // +2 to enable negative time and 100+ hours - dst = make([]byte, 0, length+2) - if src[0] == 1 { - dst = append(dst, '-') - } - days := binary.LittleEndian.Uint32(src[1:5]) - hours := int64(days)*24 + int64(src[5]) - - if hours >= 100 { - dst = strconv.AppendInt(dst, hours, 10) - } else { - dst = append(dst, digits10[hours], digits01[hours]) - } - - min, sec := src[6], src[7] - dst = append(dst, ':', - digits10[min], digits01[min], ':', - digits10[sec], digits01[sec], - ) - return appendMicrosecs(dst, src[8:], int(length)-9), nil -} - -/****************************************************************************** -* Convert from and to bytes * -******************************************************************************/ - -func uint64ToBytes(n uint64) []byte { - return []byte{ - byte(n), - byte(n >> 8), - byte(n >> 16), - byte(n >> 24), - byte(n >> 32), - byte(n >> 40), - byte(n >> 48), - byte(n >> 56), - } -} - -func uint64ToString(n uint64) []byte { - var a [20]byte - i := 20 - - // U+0030 = 0 - // ... - // U+0039 = 9 - - var q uint64 - for n >= 10 { - i-- - q = n / 10 - a[i] = uint8(n-q*10) + 0x30 - n = q - } - - i-- - a[i] = uint8(n) + 0x30 - - return a[i:] -} - -// treats string value as unsigned integer representation -func stringToInt(b []byte) int { - val := 0 - for i := range b { - val *= 10 - val += int(b[i] - 0x30) - } - return val -} - -// returns the string read as a bytes slice, wheter the value is NULL, -// the number of bytes read and an error, in case the string is longer than -// the input slice -func readLengthEncodedString(b []byte) ([]byte, bool, int, error) { - // Get length - num, isNull, n := readLengthEncodedInteger(b) - if num < 1 { - return b[n:n], isNull, n, nil - } - - n += int(num) - - // Check data length - if len(b) >= n { - return b[n-int(num) : n : n], false, n, nil - } - return nil, false, n, io.EOF -} - -// returns the number of bytes skipped and an error, in case the string is -// longer than the input slice -func skipLengthEncodedString(b []byte) (int, error) { - // Get length - num, _, n := readLengthEncodedInteger(b) - if num < 1 { - return n, nil - } - - n += int(num) - - // Check data length - if len(b) >= n { - return n, nil - } - return n, io.EOF -} - -// returns the number read, whether the value is NULL and the number of bytes read -func readLengthEncodedInteger(b []byte) (uint64, bool, int) { - // See issue #349 - if len(b) == 0 { - return 0, true, 1 - } - - switch b[0] { - // 251: NULL - case 0xfb: - return 0, true, 1 - - // 252: value of following 2 - case 0xfc: - return uint64(b[1]) | uint64(b[2])<<8, false, 3 - - // 253: value of following 3 - case 0xfd: - return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4 - - // 254: value of following 8 - case 0xfe: - return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 | - uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 | - uint64(b[7])<<48 | uint64(b[8])<<56, - false, 9 - } - - // 0-250: value of first byte - return uint64(b[0]), false, 1 -} - -// encodes a uint64 value and appends it to the given bytes slice -func appendLengthEncodedInteger(b []byte, n uint64) []byte { - switch { - case n <= 250: - return append(b, byte(n)) - - case n <= 0xffff: - return append(b, 0xfc, byte(n), byte(n>>8)) - - case n <= 0xffffff: - return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16)) - } - return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24), - byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56)) -} - -// reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize. -// If cap(buf) is not enough, reallocate new buffer. -func reserveBuffer(buf []byte, appendSize int) []byte { - newSize := len(buf) + appendSize - if cap(buf) < newSize { - // Grow buffer exponentially - newBuf := make([]byte, len(buf)*2+appendSize) - copy(newBuf, buf) - buf = newBuf - } - return buf[:newSize] -} - -// escapeBytesBackslash escapes []byte with backslashes (\) -// This escapes the contents of a string (provided as []byte) by adding backslashes before special -// characters, and turning others into specific escape sequences, such as -// turning newlines into \n and null bytes into \0. -// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932 -func escapeBytesBackslash(buf, v []byte) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for _, c := range v { - switch c { - case '\x00': - buf[pos] = '\\' - buf[pos+1] = '0' - pos += 2 - case '\n': - buf[pos] = '\\' - buf[pos+1] = 'n' - pos += 2 - case '\r': - buf[pos] = '\\' - buf[pos+1] = 'r' - pos += 2 - case '\x1a': - buf[pos] = '\\' - buf[pos+1] = 'Z' - pos += 2 - case '\'': - buf[pos] = '\\' - buf[pos+1] = '\'' - pos += 2 - case '"': - buf[pos] = '\\' - buf[pos+1] = '"' - pos += 2 - case '\\': - buf[pos] = '\\' - buf[pos+1] = '\\' - pos += 2 - default: - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeStringBackslash is similar to escapeBytesBackslash but for string. -func escapeStringBackslash(buf []byte, v string) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for i := 0; i < len(v); i++ { - c := v[i] - switch c { - case '\x00': - buf[pos] = '\\' - buf[pos+1] = '0' - pos += 2 - case '\n': - buf[pos] = '\\' - buf[pos+1] = 'n' - pos += 2 - case '\r': - buf[pos] = '\\' - buf[pos+1] = 'r' - pos += 2 - case '\x1a': - buf[pos] = '\\' - buf[pos+1] = 'Z' - pos += 2 - case '\'': - buf[pos] = '\\' - buf[pos+1] = '\'' - pos += 2 - case '"': - buf[pos] = '\\' - buf[pos+1] = '"' - pos += 2 - case '\\': - buf[pos] = '\\' - buf[pos+1] = '\\' - pos += 2 - default: - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeBytesQuotes escapes apostrophes in []byte by doubling them up. -// This escapes the contents of a string by doubling up any apostrophes that -// it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in -// effect on the server. -// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038 -func escapeBytesQuotes(buf, v []byte) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for _, c := range v { - if c == '\'' { - buf[pos] = '\'' - buf[pos+1] = '\'' - pos += 2 - } else { - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeStringQuotes is similar to escapeBytesQuotes but for string. -func escapeStringQuotes(buf []byte, v string) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for i := 0; i < len(v); i++ { - c := v[i] - if c == '\'' { - buf[pos] = '\'' - buf[pos+1] = '\'' - pos += 2 - } else { - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -/****************************************************************************** -* Sync utils * -******************************************************************************/ - -// noCopy may be embedded into structs which must not be copied -// after the first use. -// -// See https://github.com/golang/go/issues/8005#issuecomment-190753527 -// for details. -type noCopy struct{} - -// Lock is a no-op used by -copylocks checker from `go vet`. -func (*noCopy) Lock() {} - -// atomicBool is a wrapper around uint32 for usage as a boolean value with -// atomic access. -type atomicBool struct { - _noCopy noCopy - value uint32 -} - -// IsSet returns whether the current boolean value is true -func (ab *atomicBool) IsSet() bool { - return atomic.LoadUint32(&ab.value) > 0 -} - -// Set sets the value of the bool regardless of the previous value -func (ab *atomicBool) Set(value bool) { - if value { - atomic.StoreUint32(&ab.value, 1) - } else { - atomic.StoreUint32(&ab.value, 0) - } -} - -// TrySet sets the value of the bool and returns whether the value changed -func (ab *atomicBool) TrySet(value bool) bool { - if value { - return atomic.SwapUint32(&ab.value, 1) == 0 - } - return atomic.SwapUint32(&ab.value, 0) > 0 -} - -// atomicError is a wrapper for atomically accessed error values -type atomicError struct { - _noCopy noCopy - value atomic.Value -} - -// Set sets the error value regardless of the previous value. -// The value must not be nil -func (ae *atomicError) Set(value error) { - ae.value.Store(value) -} - -// Value returns the current error value -func (ae *atomicError) Value() error { - if v := ae.value.Load(); v != nil { - // this will panic if the value doesn't implement the error interface - return v.(error) - } - return nil -} - -func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) { - dargs := make([]driver.Value, len(named)) - for n, param := range named { - if len(param.Name) > 0 { - // TODO: support the use of Named Parameters #561 - return nil, errors.New("mysql: driver does not support the use of Named Parameters") - } - dargs[n] = param.Value - } - return dargs, nil -} - -func mapIsolationLevel(level driver.IsolationLevel) (string, error) { - switch sql.IsolationLevel(level) { - case sql.LevelRepeatableRead: - return "REPEATABLE READ", nil - case sql.LevelReadCommitted: - return "READ COMMITTED", nil - case sql.LevelReadUncommitted: - return "READ UNCOMMITTED", nil - case sql.LevelSerializable: - return "SERIALIZABLE", nil - default: - return "", fmt.Errorf("mysql: unsupported isolation level: %v", level) - } -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/.gitignore b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/.gitignore deleted file mode 100644 index eb7a23b2..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.idea/ -coverage.out -tmp/ -book/ diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/LICENSE.txt b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/LICENSE.txt deleted file mode 100644 index b1fef93b..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Syfaro - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/README.md b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/README.md deleted file mode 100644 index 45d3e1db..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# Golang bindings for the Telegram Bot API - -[![Go Reference](https://pkg.go.dev/badge/github.com/go-telegram-bot-api/telegram-bot-api/v5.svg)](https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5) -[![Test](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml/badge.svg)](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml) - -All methods are fairly self-explanatory, and reading the [godoc](https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5) page should -explain everything. If something isn't clear, open an issue or submit -a pull request. - -There are more tutorials and high-level information on the website, [go-telegram-bot-api.dev](https://go-telegram-bot-api.dev). - -The scope of this project is just to provide a wrapper around the API -without any additional features. There are other projects for creating -something with plugins and command handlers without having to design -all that yourself. - -Join [the development group](https://telegram.me/go_telegram_bot_api) if -you want to ask questions or discuss development. - -## Example - -First, ensure the library is installed and up to date by running -`go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5`. - -This is a very simple bot that just displays any gotten updates, -then replies it to that chat. - -```go -package main - -import ( - "log" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := tgbotapi.NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - for update := range updates { - if update.Message != nil { // If we got a message - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - - msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyToMessageID = update.Message.MessageID - - bot.Send(msg) - } - } -} -``` - -If you need to use webhooks (if you wish to run on Google App Engine), -you may use a slightly different method. - -```go -package main - -import ( - "log" - "net/http" - - "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Fatal(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - wh, _ := tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem") - - _, err = bot.SetWebhook(wh) - if err != nil { - log.Fatal(err) - } - - info, err := bot.GetWebhookInfo() - if err != nil { - log.Fatal(err) - } - - if info.LastErrorDate != 0 { - log.Printf("Telegram callback failed: %s", info.LastErrorMessage) - } - - updates := bot.ListenForWebhook("/" + bot.Token) - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) - - for update := range updates { - log.Printf("%+v\n", update) - } -} -``` - -If you need, you may generate a self-signed certificate, as this requires -HTTPS / TLS. The above example tells Telegram that this is your -certificate and that it should be trusted, even though it is not -properly signed. - - openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes - -Now that [Let's Encrypt](https://letsencrypt.org) is available, -you may wish to generate your free TLS certificate there. diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/bot.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/bot.go deleted file mode 100644 index c58afec4..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/bot.go +++ /dev/null @@ -1,726 +0,0 @@ -// Package tgbotapi has functions and types used for interacting with -// the Telegram Bot API. -package tgbotapi - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "strings" - "time" -) - -// HTTPClient is the type needed for the bot to perform HTTP requests. -type HTTPClient interface { - Do(req *http.Request) (*http.Response, error) -} - -// BotAPI allows you to interact with the Telegram Bot API. -type BotAPI struct { - Token string `json:"token"` - Debug bool `json:"debug"` - Buffer int `json:"buffer"` - - Self User `json:"-"` - Client HTTPClient `json:"-"` - shutdownChannel chan interface{} - - apiEndpoint string -} - -// NewBotAPI creates a new BotAPI instance. -// -// It requires a token, provided by @BotFather on Telegram. -func NewBotAPI(token string) (*BotAPI, error) { - return NewBotAPIWithClient(token, APIEndpoint, &http.Client{}) -} - -// NewBotAPIWithAPIEndpoint creates a new BotAPI instance -// and allows you to pass API endpoint. -// -// It requires a token, provided by @BotFather on Telegram and API endpoint. -func NewBotAPIWithAPIEndpoint(token, apiEndpoint string) (*BotAPI, error) { - return NewBotAPIWithClient(token, apiEndpoint, &http.Client{}) -} - -// NewBotAPIWithClient creates a new BotAPI instance -// and allows you to pass a http.Client. -// -// It requires a token, provided by @BotFather on Telegram and API endpoint. -func NewBotAPIWithClient(token, apiEndpoint string, client HTTPClient) (*BotAPI, error) { - bot := &BotAPI{ - Token: token, - Client: client, - Buffer: 100, - shutdownChannel: make(chan interface{}), - - apiEndpoint: apiEndpoint, - } - - self, err := bot.GetMe() - if err != nil { - return nil, err - } - - bot.Self = self - - return bot, nil -} - -// SetAPIEndpoint changes the Telegram Bot API endpoint used by the instance. -func (bot *BotAPI) SetAPIEndpoint(apiEndpoint string) { - bot.apiEndpoint = apiEndpoint -} - -func buildParams(in Params) url.Values { - if in == nil { - return url.Values{} - } - - out := url.Values{} - - for key, value := range in { - out.Set(key, value) - } - - return out -} - -// MakeRequest makes a request to a specific endpoint with our token. -func (bot *BotAPI) MakeRequest(endpoint string, params Params) (*APIResponse, error) { - if bot.Debug { - log.Printf("Endpoint: %s, params: %v\n", endpoint, params) - } - - method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint) - - values := buildParams(params) - - req, err := http.NewRequest("POST", method, strings.NewReader(values.Encode())) - if err != nil { - return &APIResponse{}, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - resp, err := bot.Client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var apiResp APIResponse - bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp) - if err != nil { - return &apiResp, err - } - - if bot.Debug { - log.Printf("Endpoint: %s, response: %s\n", endpoint, string(bytes)) - } - - if !apiResp.Ok { - var parameters ResponseParameters - - if apiResp.Parameters != nil { - parameters = *apiResp.Parameters - } - - return &apiResp, &Error{ - Code: apiResp.ErrorCode, - Message: apiResp.Description, - ResponseParameters: parameters, - } - } - - return &apiResp, nil -} - -// decodeAPIResponse decode response and return slice of bytes if debug enabled. -// If debug disabled, just decode http.Response.Body stream to APIResponse struct -// for efficient memory usage -func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) ([]byte, error) { - if !bot.Debug { - dec := json.NewDecoder(responseBody) - err := dec.Decode(resp) - return nil, err - } - - // if debug, read response body - data, err := ioutil.ReadAll(responseBody) - if err != nil { - return nil, err - } - - err = json.Unmarshal(data, resp) - if err != nil { - return nil, err - } - - return data, nil -} - -// UploadFiles makes a request to the API with files. -func (bot *BotAPI) UploadFiles(endpoint string, params Params, files []RequestFile) (*APIResponse, error) { - r, w := io.Pipe() - m := multipart.NewWriter(w) - - // This code modified from the very helpful @HirbodBehnam - // https://github.com/go-telegram-bot-api/telegram-bot-api/issues/354#issuecomment-663856473 - go func() { - defer w.Close() - defer m.Close() - - for field, value := range params { - if err := m.WriteField(field, value); err != nil { - w.CloseWithError(err) - return - } - } - - for _, file := range files { - if file.Data.NeedsUpload() { - name, reader, err := file.Data.UploadData() - if err != nil { - w.CloseWithError(err) - return - } - - part, err := m.CreateFormFile(file.Name, name) - if err != nil { - w.CloseWithError(err) - return - } - - if _, err := io.Copy(part, reader); err != nil { - w.CloseWithError(err) - return - } - - if closer, ok := reader.(io.ReadCloser); ok { - if err = closer.Close(); err != nil { - w.CloseWithError(err) - return - } - } - } else { - value := file.Data.SendData() - - if err := m.WriteField(file.Name, value); err != nil { - w.CloseWithError(err) - return - } - } - } - }() - - if bot.Debug { - log.Printf("Endpoint: %s, params: %v, with %d files\n", endpoint, params, len(files)) - } - - method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint) - - req, err := http.NewRequest("POST", method, r) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", m.FormDataContentType()) - - resp, err := bot.Client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var apiResp APIResponse - bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp) - if err != nil { - return &apiResp, err - } - - if bot.Debug { - log.Printf("Endpoint: %s, response: %s\n", endpoint, string(bytes)) - } - - if !apiResp.Ok { - var parameters ResponseParameters - - if apiResp.Parameters != nil { - parameters = *apiResp.Parameters - } - - return &apiResp, &Error{ - Message: apiResp.Description, - ResponseParameters: parameters, - } - } - - return &apiResp, nil -} - -// GetFileDirectURL returns direct URL to file -// -// It requires the FileID. -func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) { - file, err := bot.GetFile(FileConfig{fileID}) - - if err != nil { - return "", err - } - - return file.Link(bot.Token), nil -} - -// GetMe fetches the currently authenticated bot. -// -// This method is called upon creation to validate the token, -// and so you may get this data from BotAPI.Self without the need for -// another request. -func (bot *BotAPI) GetMe() (User, error) { - resp, err := bot.MakeRequest("getMe", nil) - if err != nil { - return User{}, err - } - - var user User - err = json.Unmarshal(resp.Result, &user) - - return user, err -} - -// IsMessageToMe returns true if message directed to this bot. -// -// It requires the Message. -func (bot *BotAPI) IsMessageToMe(message Message) bool { - return strings.Contains(message.Text, "@"+bot.Self.UserName) -} - -func hasFilesNeedingUpload(files []RequestFile) bool { - for _, file := range files { - if file.Data.NeedsUpload() { - return true - } - } - - return false -} - -// Request sends a Chattable to Telegram, and returns the APIResponse. -func (bot *BotAPI) Request(c Chattable) (*APIResponse, error) { - params, err := c.params() - if err != nil { - return nil, err - } - - if t, ok := c.(Fileable); ok { - files := t.files() - - // If we have files that need to be uploaded, we should delegate the - // request to UploadFile. - if hasFilesNeedingUpload(files) { - return bot.UploadFiles(t.method(), params, files) - } - - // However, if there are no files to be uploaded, there's likely things - // that need to be turned into params instead. - for _, file := range files { - params[file.Name] = file.Data.SendData() - } - } - - return bot.MakeRequest(c.method(), params) -} - -// Send will send a Chattable item to Telegram and provides the -// returned Message. -func (bot *BotAPI) Send(c Chattable) (Message, error) { - resp, err := bot.Request(c) - if err != nil { - return Message{}, err - } - - var message Message - err = json.Unmarshal(resp.Result, &message) - - return message, err -} - -// SendMediaGroup sends a media group and returns the resulting messages. -func (bot *BotAPI) SendMediaGroup(config MediaGroupConfig) ([]Message, error) { - resp, err := bot.Request(config) - if err != nil { - return nil, err - } - - var messages []Message - err = json.Unmarshal(resp.Result, &messages) - - return messages, err -} - -// GetUserProfilePhotos gets a user's profile photos. -// -// It requires UserID. -// Offset and Limit are optional. -func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) { - resp, err := bot.Request(config) - if err != nil { - return UserProfilePhotos{}, err - } - - var profilePhotos UserProfilePhotos - err = json.Unmarshal(resp.Result, &profilePhotos) - - return profilePhotos, err -} - -// GetFile returns a File which can download a file from Telegram. -// -// Requires FileID. -func (bot *BotAPI) GetFile(config FileConfig) (File, error) { - resp, err := bot.Request(config) - if err != nil { - return File{}, err - } - - var file File - err = json.Unmarshal(resp.Result, &file) - - return file, err -} - -// GetUpdates fetches updates. -// If a WebHook is set, this will not return any data! -// -// Offset, Limit, Timeout, and AllowedUpdates are optional. -// To avoid stale items, set Offset to one higher than the previous item. -// Set Timeout to a large number to reduce requests, so you can get updates -// instantly instead of having to wait between requests. -func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { - resp, err := bot.Request(config) - if err != nil { - return []Update{}, err - } - - var updates []Update - err = json.Unmarshal(resp.Result, &updates) - - return updates, err -} - -// GetWebhookInfo allows you to fetch information about a webhook and if -// one currently is set, along with pending update count and error messages. -func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { - resp, err := bot.MakeRequest("getWebhookInfo", nil) - if err != nil { - return WebhookInfo{}, err - } - - var info WebhookInfo - err = json.Unmarshal(resp.Result, &info) - - return info, err -} - -// GetUpdatesChan starts and returns a channel for getting updates. -func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) UpdatesChannel { - ch := make(chan Update, bot.Buffer) - - go func() { - for { - select { - case <-bot.shutdownChannel: - close(ch) - return - default: - } - - updates, err := bot.GetUpdates(config) - if err != nil { - log.Println(err) - log.Println("Failed to get updates, retrying in 3 seconds...") - time.Sleep(time.Second * 3) - - continue - } - - for _, update := range updates { - if update.UpdateID >= config.Offset { - config.Offset = update.UpdateID + 1 - ch <- update - } - } - } - }() - - return ch -} - -// StopReceivingUpdates stops the go routine which receives updates -func (bot *BotAPI) StopReceivingUpdates() { - if bot.Debug { - log.Println("Stopping the update receiver routine...") - } - close(bot.shutdownChannel) -} - -// ListenForWebhook registers a http handler for a webhook. -func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel { - ch := make(chan Update, bot.Buffer) - - http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - update, err := bot.HandleUpdate(r) - if err != nil { - errMsg, _ := json.Marshal(map[string]string{"error": err.Error()}) - w.WriteHeader(http.StatusBadRequest) - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write(errMsg) - return - } - - ch <- *update - }) - - return ch -} - -// ListenForWebhookRespReqFormat registers a http handler for a single incoming webhook. -func (bot *BotAPI) ListenForWebhookRespReqFormat(w http.ResponseWriter, r *http.Request) UpdatesChannel { - ch := make(chan Update, bot.Buffer) - - func(w http.ResponseWriter, r *http.Request) { - update, err := bot.HandleUpdate(r) - if err != nil { - errMsg, _ := json.Marshal(map[string]string{"error": err.Error()}) - w.WriteHeader(http.StatusBadRequest) - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write(errMsg) - return - } - - ch <- *update - close(ch) - }(w, r) - - return ch -} - -// HandleUpdate parses and returns update received via webhook -func (bot *BotAPI) HandleUpdate(r *http.Request) (*Update, error) { - if r.Method != http.MethodPost { - err := errors.New("wrong HTTP method required POST") - return nil, err - } - - var update Update - err := json.NewDecoder(r.Body).Decode(&update) - if err != nil { - return nil, err - } - - return &update, nil -} - -// WriteToHTTPResponse writes the request to the HTTP ResponseWriter. -// -// It doesn't support uploading files. -// -// See https://core.telegram.org/bots/api#making-requests-when-getting-updates -// for details. -func WriteToHTTPResponse(w http.ResponseWriter, c Chattable) error { - params, err := c.params() - if err != nil { - return err - } - - if t, ok := c.(Fileable); ok { - if hasFilesNeedingUpload(t.files()) { - return errors.New("unable to use http response to upload files") - } - } - - values := buildParams(params) - values.Set("method", c.method()) - - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - _, err = w.Write([]byte(values.Encode())) - return err -} - -// GetChat gets information about a chat. -func (bot *BotAPI) GetChat(config ChatInfoConfig) (Chat, error) { - resp, err := bot.Request(config) - if err != nil { - return Chat{}, err - } - - var chat Chat - err = json.Unmarshal(resp.Result, &chat) - - return chat, err -} - -// GetChatAdministrators gets a list of administrators in the chat. -// -// If none have been appointed, only the creator will be returned. -// Bots are not shown, even if they are an administrator. -func (bot *BotAPI) GetChatAdministrators(config ChatAdministratorsConfig) ([]ChatMember, error) { - resp, err := bot.Request(config) - if err != nil { - return []ChatMember{}, err - } - - var members []ChatMember - err = json.Unmarshal(resp.Result, &members) - - return members, err -} - -// GetChatMembersCount gets the number of users in a chat. -func (bot *BotAPI) GetChatMembersCount(config ChatMemberCountConfig) (int, error) { - resp, err := bot.Request(config) - if err != nil { - return -1, err - } - - var count int - err = json.Unmarshal(resp.Result, &count) - - return count, err -} - -// GetChatMember gets a specific chat member. -func (bot *BotAPI) GetChatMember(config GetChatMemberConfig) (ChatMember, error) { - resp, err := bot.Request(config) - if err != nil { - return ChatMember{}, err - } - - var member ChatMember - err = json.Unmarshal(resp.Result, &member) - - return member, err -} - -// GetGameHighScores allows you to get the high scores for a game. -func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) { - resp, err := bot.Request(config) - if err != nil { - return []GameHighScore{}, err - } - - var highScores []GameHighScore - err = json.Unmarshal(resp.Result, &highScores) - - return highScores, err -} - -// GetInviteLink get InviteLink for a chat -func (bot *BotAPI) GetInviteLink(config ChatInviteLinkConfig) (string, error) { - resp, err := bot.Request(config) - if err != nil { - return "", err - } - - var inviteLink string - err = json.Unmarshal(resp.Result, &inviteLink) - - return inviteLink, err -} - -// GetStickerSet returns a StickerSet. -func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) { - resp, err := bot.Request(config) - if err != nil { - return StickerSet{}, err - } - - var stickers StickerSet - err = json.Unmarshal(resp.Result, &stickers) - - return stickers, err -} - -// StopPoll stops a poll and returns the result. -func (bot *BotAPI) StopPoll(config StopPollConfig) (Poll, error) { - resp, err := bot.Request(config) - if err != nil { - return Poll{}, err - } - - var poll Poll - err = json.Unmarshal(resp.Result, &poll) - - return poll, err -} - -// GetMyCommands gets the currently registered commands. -func (bot *BotAPI) GetMyCommands() ([]BotCommand, error) { - return bot.GetMyCommandsWithConfig(GetMyCommandsConfig{}) -} - -// GetMyCommandsWithConfig gets the currently registered commands with a config. -func (bot *BotAPI) GetMyCommandsWithConfig(config GetMyCommandsConfig) ([]BotCommand, error) { - resp, err := bot.Request(config) - if err != nil { - return nil, err - } - - var commands []BotCommand - err = json.Unmarshal(resp.Result, &commands) - - return commands, err -} - -// CopyMessage copy messages of any kind. The method is analogous to the method -// forwardMessage, but the copied message doesn't have a link to the original -// message. Returns the MessageID of the sent message on success. -func (bot *BotAPI) CopyMessage(config CopyMessageConfig) (MessageID, error) { - params, err := config.params() - if err != nil { - return MessageID{}, err - } - - resp, err := bot.MakeRequest(config.method(), params) - if err != nil { - return MessageID{}, err - } - - var messageID MessageID - err = json.Unmarshal(resp.Result, &messageID) - - return messageID, err -} - -// EscapeText takes an input text and escape Telegram markup symbols. -// In this way we can send a text without being afraid of having to escape the characters manually. -// Note that you don't have to include the formatting style in the input text, or it will be escaped too. -// If there is an error, an empty string will be returned. -// -// parseMode is the text formatting mode (ModeMarkdown, ModeMarkdownV2 or ModeHTML) -// text is the input string that will be escaped -func EscapeText(parseMode string, text string) string { - var replacer *strings.Replacer - - if parseMode == ModeHTML { - replacer = strings.NewReplacer("<", "<", ">", ">", "&", "&") - } else if parseMode == ModeMarkdown { - replacer = strings.NewReplacer("_", "\\_", "*", "\\*", "`", "\\`", "[", "\\[") - } else if parseMode == ModeMarkdownV2 { - replacer = strings.NewReplacer( - "_", "\\_", "*", "\\*", "[", "\\[", "]", "\\]", "(", - "\\(", ")", "\\)", "~", "\\~", "`", "\\`", ">", "\\>", - "#", "\\#", "+", "\\+", "-", "\\-", "=", "\\=", "|", - "\\|", "{", "\\{", "}", "\\}", ".", "\\.", "!", "\\!", - ) - } else { - return "" - } - - return replacer.Replace(text) -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/configs.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/configs.go deleted file mode 100644 index 5e43af49..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/configs.go +++ /dev/null @@ -1,2468 +0,0 @@ -package tgbotapi - -import ( - "bytes" - "fmt" - "io" - "net/url" - "os" - "strconv" -) - -// Telegram constants -const ( - // APIEndpoint is the endpoint for all API methods, - // with formatting for Sprintf. - APIEndpoint = "https://api.telegram.org/bot%s/%s" - // FileEndpoint is the endpoint for downloading a file from Telegram. - FileEndpoint = "https://api.telegram.org/file/bot%s/%s" -) - -// Constant values for ChatActions -const ( - ChatTyping = "typing" - ChatUploadPhoto = "upload_photo" - ChatRecordVideo = "record_video" - ChatUploadVideo = "upload_video" - ChatRecordVoice = "record_voice" - ChatUploadVoice = "upload_voice" - ChatUploadDocument = "upload_document" - ChatChooseSticker = "choose_sticker" - ChatFindLocation = "find_location" - ChatRecordVideoNote = "record_video_note" - ChatUploadVideoNote = "upload_video_note" -) - -// API errors -const ( - // ErrAPIForbidden happens when a token is bad - ErrAPIForbidden = "forbidden" -) - -// Constant values for ParseMode in MessageConfig -const ( - ModeMarkdown = "Markdown" - ModeMarkdownV2 = "MarkdownV2" - ModeHTML = "HTML" -) - -// Constant values for update types -const ( - // UpdateTypeMessage is new incoming message of any kind — text, photo, sticker, etc. - UpdateTypeMessage = "message" - - // UpdateTypeEditedMessage is new version of a message that is known to the bot and was edited - UpdateTypeEditedMessage = "edited_message" - - // UpdateTypeChannelPost is new incoming channel post of any kind — text, photo, sticker, etc. - UpdateTypeChannelPost = "channel_post" - - // UpdateTypeEditedChannelPost is new version of a channel post that is known to the bot and was edited - UpdateTypeEditedChannelPost = "edited_channel_post" - - // UpdateTypeInlineQuery is new incoming inline query - UpdateTypeInlineQuery = "inline_query" - - // UpdateTypeChosenInlineResult i the result of an inline query that was chosen by a user and sent to their - // chat partner. Please see the documentation on the feedback collecting for - // details on how to enable these updates for your bot. - UpdateTypeChosenInlineResult = "chosen_inline_result" - - // UpdateTypeCallbackQuery is new incoming callback query - UpdateTypeCallbackQuery = "callback_query" - - // UpdateTypeShippingQuery is new incoming shipping query. Only for invoices with flexible price - UpdateTypeShippingQuery = "shipping_query" - - // UpdateTypePreCheckoutQuery is new incoming pre-checkout query. Contains full information about checkout - UpdateTypePreCheckoutQuery = "pre_checkout_query" - - // UpdateTypePoll is new poll state. Bots receive only updates about stopped polls and polls - // which are sent by the bot - UpdateTypePoll = "poll" - - // UpdateTypePollAnswer is when user changed their answer in a non-anonymous poll. Bots receive new votes - // only in polls that were sent by the bot itself. - UpdateTypePollAnswer = "poll_answer" - - // UpdateTypeMyChatMember is when the bot's chat member status was updated in a chat. For private chats, this - // update is received only when the bot is blocked or unblocked by the user. - UpdateTypeMyChatMember = "my_chat_member" - - // UpdateTypeChatMember is when the bot must be an administrator in the chat and must explicitly specify - // this update in the list of allowed_updates to receive these updates. - UpdateTypeChatMember = "chat_member" -) - -// Library errors -const ( - ErrBadURL = "bad or empty url" -) - -// Chattable is any config type that can be sent. -type Chattable interface { - params() (Params, error) - method() string -} - -// Fileable is any config type that can be sent that includes a file. -type Fileable interface { - Chattable - files() []RequestFile -} - -// RequestFile represents a file associated with a field name. -type RequestFile struct { - // The file field name. - Name string - // The file data to include. - Data RequestFileData -} - -// RequestFileData represents the data to be used for a file. -type RequestFileData interface { - // NeedsUpload shows if the file needs to be uploaded. - NeedsUpload() bool - - // UploadData gets the file name and an `io.Reader` for the file to be uploaded. This - // must only be called when the file needs to be uploaded. - UploadData() (string, io.Reader, error) - // SendData gets the file data to send when a file does not need to be uploaded. This - // must only be called when the file does not need to be uploaded. - SendData() string -} - -// FileBytes contains information about a set of bytes to upload -// as a File. -type FileBytes struct { - Name string - Bytes []byte -} - -func (fb FileBytes) NeedsUpload() bool { - return true -} - -func (fb FileBytes) UploadData() (string, io.Reader, error) { - return fb.Name, bytes.NewReader(fb.Bytes), nil -} - -func (fb FileBytes) SendData() string { - panic("FileBytes must be uploaded") -} - -// FileReader contains information about a reader to upload as a File. -type FileReader struct { - Name string - Reader io.Reader -} - -func (fr FileReader) NeedsUpload() bool { - return true -} - -func (fr FileReader) UploadData() (string, io.Reader, error) { - return fr.Name, fr.Reader, nil -} - -func (fr FileReader) SendData() string { - panic("FileReader must be uploaded") -} - -// FilePath is a path to a local file. -type FilePath string - -func (fp FilePath) NeedsUpload() bool { - return true -} - -func (fp FilePath) UploadData() (string, io.Reader, error) { - fileHandle, err := os.Open(string(fp)) - if err != nil { - return "", nil, err - } - - name := fileHandle.Name() - return name, fileHandle, err -} - -func (fp FilePath) SendData() string { - panic("FilePath must be uploaded") -} - -// FileURL is a URL to use as a file for a request. -type FileURL string - -func (fu FileURL) NeedsUpload() bool { - return false -} - -func (fu FileURL) UploadData() (string, io.Reader, error) { - panic("FileURL cannot be uploaded") -} - -func (fu FileURL) SendData() string { - return string(fu) -} - -// FileID is an ID of a file already uploaded to Telegram. -type FileID string - -func (fi FileID) NeedsUpload() bool { - return false -} - -func (fi FileID) UploadData() (string, io.Reader, error) { - panic("FileID cannot be uploaded") -} - -func (fi FileID) SendData() string { - return string(fi) -} - -// fileAttach is an internal file type used for processed media groups. -type fileAttach string - -func (fa fileAttach) NeedsUpload() bool { - return false -} - -func (fa fileAttach) UploadData() (string, io.Reader, error) { - panic("fileAttach cannot be uploaded") -} - -func (fa fileAttach) SendData() string { - return string(fa) -} - -// LogOutConfig is a request to log out of the cloud Bot API server. -// -// Note that you may not log back in for at least 10 minutes. -type LogOutConfig struct{} - -func (LogOutConfig) method() string { - return "logOut" -} - -func (LogOutConfig) params() (Params, error) { - return nil, nil -} - -// CloseConfig is a request to close the bot instance on a local server. -// -// Note that you may not close an instance for the first 10 minutes after the -// bot has started. -type CloseConfig struct{} - -func (CloseConfig) method() string { - return "close" -} - -func (CloseConfig) params() (Params, error) { - return nil, nil -} - -// BaseChat is base type for all chat config types. -type BaseChat struct { - ChatID int64 // required - ChannelUsername string - ReplyToMessageID int - ReplyMarkup interface{} - DisableNotification bool - AllowSendingWithoutReply bool -} - -func (chat *BaseChat) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", chat.ChatID, chat.ChannelUsername) - params.AddNonZero("reply_to_message_id", chat.ReplyToMessageID) - params.AddBool("disable_notification", chat.DisableNotification) - params.AddBool("allow_sending_without_reply", chat.AllowSendingWithoutReply) - - err := params.AddInterface("reply_markup", chat.ReplyMarkup) - - return params, err -} - -// BaseFile is a base type for all file config types. -type BaseFile struct { - BaseChat - File RequestFileData -} - -func (file BaseFile) params() (Params, error) { - return file.BaseChat.params() -} - -// BaseEdit is base type of all chat edits. -type BaseEdit struct { - ChatID int64 - ChannelUsername string - MessageID int - InlineMessageID string - ReplyMarkup *InlineKeyboardMarkup -} - -func (edit BaseEdit) params() (Params, error) { - params := make(Params) - - if edit.InlineMessageID != "" { - params["inline_message_id"] = edit.InlineMessageID - } else { - params.AddFirstValid("chat_id", edit.ChatID, edit.ChannelUsername) - params.AddNonZero("message_id", edit.MessageID) - } - - err := params.AddInterface("reply_markup", edit.ReplyMarkup) - - return params, err -} - -// MessageConfig contains information about a SendMessage request. -type MessageConfig struct { - BaseChat - Text string - ParseMode string - Entities []MessageEntity - DisableWebPagePreview bool -} - -func (config MessageConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddNonEmpty("text", config.Text) - params.AddBool("disable_web_page_preview", config.DisableWebPagePreview) - params.AddNonEmpty("parse_mode", config.ParseMode) - err = params.AddInterface("entities", config.Entities) - - return params, err -} - -func (config MessageConfig) method() string { - return "sendMessage" -} - -// ForwardConfig contains information about a ForwardMessage request. -type ForwardConfig struct { - BaseChat - FromChatID int64 // required - FromChannelUsername string - MessageID int // required -} - -func (config ForwardConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddNonZero64("from_chat_id", config.FromChatID) - params.AddNonZero("message_id", config.MessageID) - - return params, nil -} - -func (config ForwardConfig) method() string { - return "forwardMessage" -} - -// CopyMessageConfig contains information about a copyMessage request. -type CopyMessageConfig struct { - BaseChat - FromChatID int64 - FromChannelUsername string - MessageID int - Caption string - ParseMode string - CaptionEntities []MessageEntity -} - -func (config CopyMessageConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddFirstValid("from_chat_id", config.FromChatID, config.FromChannelUsername) - params.AddNonZero("message_id", config.MessageID) - params.AddNonEmpty("caption", config.Caption) - params.AddNonEmpty("parse_mode", config.ParseMode) - err = params.AddInterface("caption_entities", config.CaptionEntities) - - return params, err -} - -func (config CopyMessageConfig) method() string { - return "copyMessage" -} - -// PhotoConfig contains information about a SendPhoto request. -type PhotoConfig struct { - BaseFile - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity -} - -func (config PhotoConfig) params() (Params, error) { - params, err := config.BaseFile.params() - if err != nil { - return params, err - } - - params.AddNonEmpty("caption", config.Caption) - params.AddNonEmpty("parse_mode", config.ParseMode) - err = params.AddInterface("caption_entities", config.CaptionEntities) - - return params, err -} - -func (config PhotoConfig) method() string { - return "sendPhoto" -} - -func (config PhotoConfig) files() []RequestFile { - files := []RequestFile{{ - Name: "photo", - Data: config.File, - }} - - if config.Thumb != nil { - files = append(files, RequestFile{ - Name: "thumb", - Data: config.Thumb, - }) - } - - return files -} - -// AudioConfig contains information about a SendAudio request. -type AudioConfig struct { - BaseFile - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity - Duration int - Performer string - Title string -} - -func (config AudioConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddNonZero("duration", config.Duration) - params.AddNonEmpty("performer", config.Performer) - params.AddNonEmpty("title", config.Title) - params.AddNonEmpty("caption", config.Caption) - params.AddNonEmpty("parse_mode", config.ParseMode) - err = params.AddInterface("caption_entities", config.CaptionEntities) - - return params, err -} - -func (config AudioConfig) method() string { - return "sendAudio" -} - -func (config AudioConfig) files() []RequestFile { - files := []RequestFile{{ - Name: "audio", - Data: config.File, - }} - - if config.Thumb != nil { - files = append(files, RequestFile{ - Name: "thumb", - Data: config.Thumb, - }) - } - - return files -} - -// DocumentConfig contains information about a SendDocument request. -type DocumentConfig struct { - BaseFile - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity - DisableContentTypeDetection bool -} - -func (config DocumentConfig) params() (Params, error) { - params, err := config.BaseFile.params() - - params.AddNonEmpty("caption", config.Caption) - params.AddNonEmpty("parse_mode", config.ParseMode) - params.AddBool("disable_content_type_detection", config.DisableContentTypeDetection) - - return params, err -} - -func (config DocumentConfig) method() string { - return "sendDocument" -} - -func (config DocumentConfig) files() []RequestFile { - files := []RequestFile{{ - Name: "document", - Data: config.File, - }} - - if config.Thumb != nil { - files = append(files, RequestFile{ - Name: "thumb", - Data: config.Thumb, - }) - } - - return files -} - -// StickerConfig contains information about a SendSticker request. -type StickerConfig struct { - BaseFile -} - -func (config StickerConfig) params() (Params, error) { - return config.BaseChat.params() -} - -func (config StickerConfig) method() string { - return "sendSticker" -} - -func (config StickerConfig) files() []RequestFile { - return []RequestFile{{ - Name: "sticker", - Data: config.File, - }} -} - -// VideoConfig contains information about a SendVideo request. -type VideoConfig struct { - BaseFile - Thumb RequestFileData - Duration int - Caption string - ParseMode string - CaptionEntities []MessageEntity - SupportsStreaming bool -} - -func (config VideoConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddNonZero("duration", config.Duration) - params.AddNonEmpty("caption", config.Caption) - params.AddNonEmpty("parse_mode", config.ParseMode) - params.AddBool("supports_streaming", config.SupportsStreaming) - err = params.AddInterface("caption_entities", config.CaptionEntities) - - return params, err -} - -func (config VideoConfig) method() string { - return "sendVideo" -} - -func (config VideoConfig) files() []RequestFile { - files := []RequestFile{{ - Name: "video", - Data: config.File, - }} - - if config.Thumb != nil { - files = append(files, RequestFile{ - Name: "thumb", - Data: config.Thumb, - }) - } - - return files -} - -// AnimationConfig contains information about a SendAnimation request. -type AnimationConfig struct { - BaseFile - Duration int - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity -} - -func (config AnimationConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddNonZero("duration", config.Duration) - params.AddNonEmpty("caption", config.Caption) - params.AddNonEmpty("parse_mode", config.ParseMode) - err = params.AddInterface("caption_entities", config.CaptionEntities) - - return params, err -} - -func (config AnimationConfig) method() string { - return "sendAnimation" -} - -func (config AnimationConfig) files() []RequestFile { - files := []RequestFile{{ - Name: "animation", - Data: config.File, - }} - - if config.Thumb != nil { - files = append(files, RequestFile{ - Name: "thumb", - Data: config.Thumb, - }) - } - - return files -} - -// VideoNoteConfig contains information about a SendVideoNote request. -type VideoNoteConfig struct { - BaseFile - Thumb RequestFileData - Duration int - Length int -} - -func (config VideoNoteConfig) params() (Params, error) { - params, err := config.BaseChat.params() - - params.AddNonZero("duration", config.Duration) - params.AddNonZero("length", config.Length) - - return params, err -} - -func (config VideoNoteConfig) method() string { - return "sendVideoNote" -} - -func (config VideoNoteConfig) files() []RequestFile { - files := []RequestFile{{ - Name: "video_note", - Data: config.File, - }} - - if config.Thumb != nil { - files = append(files, RequestFile{ - Name: "thumb", - Data: config.Thumb, - }) - } - - return files -} - -// VoiceConfig contains information about a SendVoice request. -type VoiceConfig struct { - BaseFile - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity - Duration int -} - -func (config VoiceConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddNonZero("duration", config.Duration) - params.AddNonEmpty("caption", config.Caption) - params.AddNonEmpty("parse_mode", config.ParseMode) - err = params.AddInterface("caption_entities", config.CaptionEntities) - - return params, err -} - -func (config VoiceConfig) method() string { - return "sendVoice" -} - -func (config VoiceConfig) files() []RequestFile { - files := []RequestFile{{ - Name: "voice", - Data: config.File, - }} - - if config.Thumb != nil { - files = append(files, RequestFile{ - Name: "thumb", - Data: config.Thumb, - }) - } - - return files -} - -// LocationConfig contains information about a SendLocation request. -type LocationConfig struct { - BaseChat - Latitude float64 // required - Longitude float64 // required - HorizontalAccuracy float64 // optional - LivePeriod int // optional - Heading int // optional - ProximityAlertRadius int // optional -} - -func (config LocationConfig) params() (Params, error) { - params, err := config.BaseChat.params() - - params.AddNonZeroFloat("latitude", config.Latitude) - params.AddNonZeroFloat("longitude", config.Longitude) - params.AddNonZeroFloat("horizontal_accuracy", config.HorizontalAccuracy) - params.AddNonZero("live_period", config.LivePeriod) - params.AddNonZero("heading", config.Heading) - params.AddNonZero("proximity_alert_radius", config.ProximityAlertRadius) - - return params, err -} - -func (config LocationConfig) method() string { - return "sendLocation" -} - -// EditMessageLiveLocationConfig allows you to update a live location. -type EditMessageLiveLocationConfig struct { - BaseEdit - Latitude float64 // required - Longitude float64 // required - HorizontalAccuracy float64 // optional - Heading int // optional - ProximityAlertRadius int // optional -} - -func (config EditMessageLiveLocationConfig) params() (Params, error) { - params, err := config.BaseEdit.params() - - params.AddNonZeroFloat("latitude", config.Latitude) - params.AddNonZeroFloat("longitude", config.Longitude) - params.AddNonZeroFloat("horizontal_accuracy", config.HorizontalAccuracy) - params.AddNonZero("heading", config.Heading) - params.AddNonZero("proximity_alert_radius", config.ProximityAlertRadius) - - return params, err -} - -func (config EditMessageLiveLocationConfig) method() string { - return "editMessageLiveLocation" -} - -// StopMessageLiveLocationConfig stops updating a live location. -type StopMessageLiveLocationConfig struct { - BaseEdit -} - -func (config StopMessageLiveLocationConfig) params() (Params, error) { - return config.BaseEdit.params() -} - -func (config StopMessageLiveLocationConfig) method() string { - return "stopMessageLiveLocation" -} - -// VenueConfig contains information about a SendVenue request. -type VenueConfig struct { - BaseChat - Latitude float64 // required - Longitude float64 // required - Title string // required - Address string // required - FoursquareID string - FoursquareType string - GooglePlaceID string - GooglePlaceType string -} - -func (config VenueConfig) params() (Params, error) { - params, err := config.BaseChat.params() - - params.AddNonZeroFloat("latitude", config.Latitude) - params.AddNonZeroFloat("longitude", config.Longitude) - params["title"] = config.Title - params["address"] = config.Address - params.AddNonEmpty("foursquare_id", config.FoursquareID) - params.AddNonEmpty("foursquare_type", config.FoursquareType) - params.AddNonEmpty("google_place_id", config.GooglePlaceID) - params.AddNonEmpty("google_place_type", config.GooglePlaceType) - - return params, err -} - -func (config VenueConfig) method() string { - return "sendVenue" -} - -// ContactConfig allows you to send a contact. -type ContactConfig struct { - BaseChat - PhoneNumber string - FirstName string - LastName string - VCard string -} - -func (config ContactConfig) params() (Params, error) { - params, err := config.BaseChat.params() - - params["phone_number"] = config.PhoneNumber - params["first_name"] = config.FirstName - - params.AddNonEmpty("last_name", config.LastName) - params.AddNonEmpty("vcard", config.VCard) - - return params, err -} - -func (config ContactConfig) method() string { - return "sendContact" -} - -// SendPollConfig allows you to send a poll. -type SendPollConfig struct { - BaseChat - Question string - Options []string - IsAnonymous bool - Type string - AllowsMultipleAnswers bool - CorrectOptionID int64 - Explanation string - ExplanationParseMode string - ExplanationEntities []MessageEntity - OpenPeriod int - CloseDate int - IsClosed bool -} - -func (config SendPollConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params["question"] = config.Question - if err = params.AddInterface("options", config.Options); err != nil { - return params, err - } - params["is_anonymous"] = strconv.FormatBool(config.IsAnonymous) - params.AddNonEmpty("type", config.Type) - params["allows_multiple_answers"] = strconv.FormatBool(config.AllowsMultipleAnswers) - params["correct_option_id"] = strconv.FormatInt(config.CorrectOptionID, 10) - params.AddBool("is_closed", config.IsClosed) - params.AddNonEmpty("explanation", config.Explanation) - params.AddNonEmpty("explanation_parse_mode", config.ExplanationParseMode) - params.AddNonZero("open_period", config.OpenPeriod) - params.AddNonZero("close_date", config.CloseDate) - err = params.AddInterface("explanation_entities", config.ExplanationEntities) - - return params, err -} - -func (SendPollConfig) method() string { - return "sendPoll" -} - -// GameConfig allows you to send a game. -type GameConfig struct { - BaseChat - GameShortName string -} - -func (config GameConfig) params() (Params, error) { - params, err := config.BaseChat.params() - - params["game_short_name"] = config.GameShortName - - return params, err -} - -func (config GameConfig) method() string { - return "sendGame" -} - -// SetGameScoreConfig allows you to update the game score in a chat. -type SetGameScoreConfig struct { - UserID int64 - Score int - Force bool - DisableEditMessage bool - ChatID int64 - ChannelUsername string - MessageID int - InlineMessageID string -} - -func (config SetGameScoreConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero64("user_id", config.UserID) - params.AddNonZero("scrore", config.Score) - params.AddBool("disable_edit_message", config.DisableEditMessage) - - if config.InlineMessageID != "" { - params["inline_message_id"] = config.InlineMessageID - } else { - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) - } - - return params, nil -} - -func (config SetGameScoreConfig) method() string { - return "setGameScore" -} - -// GetGameHighScoresConfig allows you to fetch the high scores for a game. -type GetGameHighScoresConfig struct { - UserID int64 - ChatID int64 - ChannelUsername string - MessageID int - InlineMessageID string -} - -func (config GetGameHighScoresConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero64("user_id", config.UserID) - - if config.InlineMessageID != "" { - params["inline_message_id"] = config.InlineMessageID - } else { - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) - } - - return params, nil -} - -func (config GetGameHighScoresConfig) method() string { - return "getGameHighScores" -} - -// ChatActionConfig contains information about a SendChatAction request. -type ChatActionConfig struct { - BaseChat - Action string // required -} - -func (config ChatActionConfig) params() (Params, error) { - params, err := config.BaseChat.params() - - params["action"] = config.Action - - return params, err -} - -func (config ChatActionConfig) method() string { - return "sendChatAction" -} - -// EditMessageTextConfig allows you to modify the text in a message. -type EditMessageTextConfig struct { - BaseEdit - Text string - ParseMode string - Entities []MessageEntity - DisableWebPagePreview bool -} - -func (config EditMessageTextConfig) params() (Params, error) { - params, err := config.BaseEdit.params() - if err != nil { - return params, err - } - - params["text"] = config.Text - params.AddNonEmpty("parse_mode", config.ParseMode) - params.AddBool("disable_web_page_preview", config.DisableWebPagePreview) - err = params.AddInterface("entities", config.Entities) - - return params, err -} - -func (config EditMessageTextConfig) method() string { - return "editMessageText" -} - -// EditMessageCaptionConfig allows you to modify the caption of a message. -type EditMessageCaptionConfig struct { - BaseEdit - Caption string - ParseMode string - CaptionEntities []MessageEntity -} - -func (config EditMessageCaptionConfig) params() (Params, error) { - params, err := config.BaseEdit.params() - if err != nil { - return params, err - } - - params["caption"] = config.Caption - params.AddNonEmpty("parse_mode", config.ParseMode) - err = params.AddInterface("caption_entities", config.CaptionEntities) - - return params, err -} - -func (config EditMessageCaptionConfig) method() string { - return "editMessageCaption" -} - -// EditMessageMediaConfig allows you to make an editMessageMedia request. -type EditMessageMediaConfig struct { - BaseEdit - - Media interface{} -} - -func (EditMessageMediaConfig) method() string { - return "editMessageMedia" -} - -func (config EditMessageMediaConfig) params() (Params, error) { - params, err := config.BaseEdit.params() - if err != nil { - return params, err - } - - err = params.AddInterface("media", prepareInputMediaParam(config.Media, 0)) - - return params, err -} - -func (config EditMessageMediaConfig) files() []RequestFile { - return prepareInputMediaFile(config.Media, 0) -} - -// EditMessageReplyMarkupConfig allows you to modify the reply markup -// of a message. -type EditMessageReplyMarkupConfig struct { - BaseEdit -} - -func (config EditMessageReplyMarkupConfig) params() (Params, error) { - return config.BaseEdit.params() -} - -func (config EditMessageReplyMarkupConfig) method() string { - return "editMessageReplyMarkup" -} - -// StopPollConfig allows you to stop a poll sent by the bot. -type StopPollConfig struct { - BaseEdit -} - -func (config StopPollConfig) params() (Params, error) { - return config.BaseEdit.params() -} - -func (StopPollConfig) method() string { - return "stopPoll" -} - -// UserProfilePhotosConfig contains information about a -// GetUserProfilePhotos request. -type UserProfilePhotosConfig struct { - UserID int64 - Offset int - Limit int -} - -func (UserProfilePhotosConfig) method() string { - return "getUserProfilePhotos" -} - -func (config UserProfilePhotosConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero64("user_id", config.UserID) - params.AddNonZero("offset", config.Offset) - params.AddNonZero("limit", config.Limit) - - return params, nil -} - -// FileConfig has information about a file hosted on Telegram. -type FileConfig struct { - FileID string -} - -func (FileConfig) method() string { - return "getFile" -} - -func (config FileConfig) params() (Params, error) { - params := make(Params) - - params["file_id"] = config.FileID - - return params, nil -} - -// UpdateConfig contains information about a GetUpdates request. -type UpdateConfig struct { - Offset int - Limit int - Timeout int - AllowedUpdates []string -} - -func (UpdateConfig) method() string { - return "getUpdates" -} - -func (config UpdateConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero("offset", config.Offset) - params.AddNonZero("limit", config.Limit) - params.AddNonZero("timeout", config.Timeout) - params.AddInterface("allowed_updates", config.AllowedUpdates) - - return params, nil -} - -// WebhookConfig contains information about a SetWebhook request. -type WebhookConfig struct { - URL *url.URL - Certificate RequestFileData - IPAddress string - MaxConnections int - AllowedUpdates []string - DropPendingUpdates bool -} - -func (config WebhookConfig) method() string { - return "setWebhook" -} - -func (config WebhookConfig) params() (Params, error) { - params := make(Params) - - if config.URL != nil { - params["url"] = config.URL.String() - } - - params.AddNonEmpty("ip_address", config.IPAddress) - params.AddNonZero("max_connections", config.MaxConnections) - err := params.AddInterface("allowed_updates", config.AllowedUpdates) - params.AddBool("drop_pending_updates", config.DropPendingUpdates) - - return params, err -} - -func (config WebhookConfig) files() []RequestFile { - if config.Certificate != nil { - return []RequestFile{{ - Name: "certificate", - Data: config.Certificate, - }} - } - - return nil -} - -// DeleteWebhookConfig is a helper to delete a webhook. -type DeleteWebhookConfig struct { - DropPendingUpdates bool -} - -func (config DeleteWebhookConfig) method() string { - return "deleteWebhook" -} - -func (config DeleteWebhookConfig) params() (Params, error) { - params := make(Params) - - params.AddBool("drop_pending_updates", config.DropPendingUpdates) - - return params, nil -} - -// InlineConfig contains information on making an InlineQuery response. -type InlineConfig struct { - InlineQueryID string `json:"inline_query_id"` - Results []interface{} `json:"results"` - CacheTime int `json:"cache_time"` - IsPersonal bool `json:"is_personal"` - NextOffset string `json:"next_offset"` - SwitchPMText string `json:"switch_pm_text"` - SwitchPMParameter string `json:"switch_pm_parameter"` -} - -func (config InlineConfig) method() string { - return "answerInlineQuery" -} - -func (config InlineConfig) params() (Params, error) { - params := make(Params) - - params["inline_query_id"] = config.InlineQueryID - params.AddNonZero("cache_time", config.CacheTime) - params.AddBool("is_personal", config.IsPersonal) - params.AddNonEmpty("next_offset", config.NextOffset) - params.AddNonEmpty("switch_pm_text", config.SwitchPMText) - params.AddNonEmpty("switch_pm_parameter", config.SwitchPMParameter) - err := params.AddInterface("results", config.Results) - - return params, err -} - -// CallbackConfig contains information on making a CallbackQuery response. -type CallbackConfig struct { - CallbackQueryID string `json:"callback_query_id"` - Text string `json:"text"` - ShowAlert bool `json:"show_alert"` - URL string `json:"url"` - CacheTime int `json:"cache_time"` -} - -func (config CallbackConfig) method() string { - return "answerCallbackQuery" -} - -func (config CallbackConfig) params() (Params, error) { - params := make(Params) - - params["callback_query_id"] = config.CallbackQueryID - params.AddNonEmpty("text", config.Text) - params.AddBool("show_alert", config.ShowAlert) - params.AddNonEmpty("url", config.URL) - params.AddNonZero("cache_time", config.CacheTime) - - return params, nil -} - -// ChatMemberConfig contains information about a user in a chat for use -// with administrative functions such as kicking or unbanning a user. -type ChatMemberConfig struct { - ChatID int64 - SuperGroupUsername string - ChannelUsername string - UserID int64 -} - -// UnbanChatMemberConfig allows you to unban a user. -type UnbanChatMemberConfig struct { - ChatMemberConfig - OnlyIfBanned bool -} - -func (config UnbanChatMemberConfig) method() string { - return "unbanChatMember" -} - -func (config UnbanChatMemberConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) - params.AddBool("only_if_banned", config.OnlyIfBanned) - - return params, nil -} - -// BanChatMemberConfig contains extra fields to kick user. -type BanChatMemberConfig struct { - ChatMemberConfig - UntilDate int64 - RevokeMessages bool -} - -func (config BanChatMemberConfig) method() string { - return "banChatMember" -} - -func (config BanChatMemberConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero64("user_id", config.UserID) - params.AddNonZero64("until_date", config.UntilDate) - params.AddBool("revoke_messages", config.RevokeMessages) - - return params, nil -} - -// KickChatMemberConfig contains extra fields to ban user. -// -// This was renamed to BanChatMember in later versions of the Telegram Bot API. -type KickChatMemberConfig = BanChatMemberConfig - -// RestrictChatMemberConfig contains fields to restrict members of chat -type RestrictChatMemberConfig struct { - ChatMemberConfig - UntilDate int64 - Permissions *ChatPermissions -} - -func (config RestrictChatMemberConfig) method() string { - return "restrictChatMember" -} - -func (config RestrictChatMemberConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) - - err := params.AddInterface("permissions", config.Permissions) - params.AddNonZero64("until_date", config.UntilDate) - - return params, err -} - -// PromoteChatMemberConfig contains fields to promote members of chat -type PromoteChatMemberConfig struct { - ChatMemberConfig - IsAnonymous bool - CanManageChat bool - CanChangeInfo bool - CanPostMessages bool - CanEditMessages bool - CanDeleteMessages bool - CanManageVoiceChats bool - CanInviteUsers bool - CanRestrictMembers bool - CanPinMessages bool - CanPromoteMembers bool -} - -func (config PromoteChatMemberConfig) method() string { - return "promoteChatMember" -} - -func (config PromoteChatMemberConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) - - params.AddBool("is_anonymous", config.IsAnonymous) - params.AddBool("can_manage_chat", config.CanManageChat) - params.AddBool("can_change_info", config.CanChangeInfo) - params.AddBool("can_post_messages", config.CanPostMessages) - params.AddBool("can_edit_messages", config.CanEditMessages) - params.AddBool("can_delete_messages", config.CanDeleteMessages) - params.AddBool("can_manage_voice_chats", config.CanManageVoiceChats) - params.AddBool("can_invite_users", config.CanInviteUsers) - params.AddBool("can_restrict_members", config.CanRestrictMembers) - params.AddBool("can_pin_messages", config.CanPinMessages) - params.AddBool("can_promote_members", config.CanPromoteMembers) - - return params, nil -} - -// SetChatAdministratorCustomTitle sets the title of an administrative user -// promoted by the bot for a chat. -type SetChatAdministratorCustomTitle struct { - ChatMemberConfig - CustomTitle string -} - -func (SetChatAdministratorCustomTitle) method() string { - return "setChatAdministratorCustomTitle" -} - -func (config SetChatAdministratorCustomTitle) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) - params.AddNonEmpty("custom_title", config.CustomTitle) - - return params, nil -} - -// BanChatSenderChatConfig bans a channel chat in a supergroup or a channel. The -// owner of the chat will not be able to send messages and join live streams on -// behalf of the chat, unless it is unbanned first. The bot must be an -// administrator in the supergroup or channel for this to work and must have the -// appropriate administrator rights. -type BanChatSenderChatConfig struct { - ChatID int64 - ChannelUsername string - SenderChatID int64 - UntilDate int -} - -func (config BanChatSenderChatConfig) method() string { - return "banChatSenderChat" -} - -func (config BanChatSenderChatConfig) params() (Params, error) { - params := make(Params) - - _ = params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero64("sender_chat_id", config.SenderChatID) - params.AddNonZero("until_date", config.UntilDate) - - return params, nil -} - -// UnbanChatSenderChatConfig unbans a previously banned channel chat in a -// supergroup or channel. The bot must be an administrator for this to work and -// must have the appropriate administrator rights. -type UnbanChatSenderChatConfig struct { - ChatID int64 - ChannelUsername string - SenderChatID int64 -} - -func (config UnbanChatSenderChatConfig) method() string { - return "unbanChatSenderChat" -} - -func (config UnbanChatSenderChatConfig) params() (Params, error) { - params := make(Params) - - _ = params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero64("sender_chat_id", config.SenderChatID) - - return params, nil -} - -// ChatConfig contains information about getting information on a chat. -type ChatConfig struct { - ChatID int64 - SuperGroupUsername string -} - -func (config ChatConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil -} - -// ChatInfoConfig contains information about getting chat information. -type ChatInfoConfig struct { - ChatConfig -} - -func (ChatInfoConfig) method() string { - return "getChat" -} - -// ChatMemberCountConfig contains information about getting the number of users in a chat. -type ChatMemberCountConfig struct { - ChatConfig -} - -func (ChatMemberCountConfig) method() string { - return "getChatMembersCount" -} - -// ChatAdministratorsConfig contains information about getting chat administrators. -type ChatAdministratorsConfig struct { - ChatConfig -} - -func (ChatAdministratorsConfig) method() string { - return "getChatAdministrators" -} - -// SetChatPermissionsConfig allows you to set default permissions for the -// members in a group. The bot must be an administrator and have rights to -// restrict members. -type SetChatPermissionsConfig struct { - ChatConfig - Permissions *ChatPermissions -} - -func (SetChatPermissionsConfig) method() string { - return "setChatPermissions" -} - -func (config SetChatPermissionsConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - err := params.AddInterface("permissions", config.Permissions) - - return params, err -} - -// ChatInviteLinkConfig contains information about getting a chat link. -// -// Note that generating a new link will revoke any previous links. -type ChatInviteLinkConfig struct { - ChatConfig -} - -func (ChatInviteLinkConfig) method() string { - return "exportChatInviteLink" -} - -func (config ChatInviteLinkConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil -} - -// CreateChatInviteLinkConfig allows you to create an additional invite link for -// a chat. The bot must be an administrator in the chat for this to work and -// must have the appropriate admin rights. The link can be revoked using the -// RevokeChatInviteLinkConfig. -type CreateChatInviteLinkConfig struct { - ChatConfig - Name string - ExpireDate int - MemberLimit int - CreatesJoinRequest bool -} - -func (CreateChatInviteLinkConfig) method() string { - return "createChatInviteLink" -} - -func (config CreateChatInviteLinkConfig) params() (Params, error) { - params := make(Params) - - params.AddNonEmpty("name", config.Name) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("expire_date", config.ExpireDate) - params.AddNonZero("member_limit", config.MemberLimit) - params.AddBool("creates_join_request", config.CreatesJoinRequest) - - return params, nil -} - -// EditChatInviteLinkConfig allows you to edit a non-primary invite link created -// by the bot. The bot must be an administrator in the chat for this to work and -// must have the appropriate admin rights. -type EditChatInviteLinkConfig struct { - ChatConfig - InviteLink string - Name string - ExpireDate int - MemberLimit int - CreatesJoinRequest bool -} - -func (EditChatInviteLinkConfig) method() string { - return "editChatInviteLink" -} - -func (config EditChatInviteLinkConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonEmpty("name", config.Name) - params["invite_link"] = config.InviteLink - params.AddNonZero("expire_date", config.ExpireDate) - params.AddNonZero("member_limit", config.MemberLimit) - params.AddBool("creates_join_request", config.CreatesJoinRequest) - - return params, nil -} - -// RevokeChatInviteLinkConfig allows you to revoke an invite link created by the -// bot. If the primary link is revoked, a new link is automatically generated. -// The bot must be an administrator in the chat for this to work and must have -// the appropriate admin rights. -type RevokeChatInviteLinkConfig struct { - ChatConfig - InviteLink string -} - -func (RevokeChatInviteLinkConfig) method() string { - return "revokeChatInviteLink" -} - -func (config RevokeChatInviteLinkConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params["invite_link"] = config.InviteLink - - return params, nil -} - -// ApproveChatJoinRequestConfig allows you to approve a chat join request. -type ApproveChatJoinRequestConfig struct { - ChatConfig - UserID int64 -} - -func (ApproveChatJoinRequestConfig) method() string { - return "approveChatJoinRequest" -} - -func (config ApproveChatJoinRequestConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("user_id", int(config.UserID)) - - return params, nil -} - -// DeclineChatJoinRequest allows you to decline a chat join request. -type DeclineChatJoinRequest struct { - ChatConfig - UserID int64 -} - -func (DeclineChatJoinRequest) method() string { - return "declineChatJoinRequest" -} - -func (config DeclineChatJoinRequest) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("user_id", int(config.UserID)) - - return params, nil -} - -// LeaveChatConfig allows you to leave a chat. -type LeaveChatConfig struct { - ChatID int64 - ChannelUsername string -} - -func (config LeaveChatConfig) method() string { - return "leaveChat" -} - -func (config LeaveChatConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil -} - -// ChatConfigWithUser contains information about a chat and a user. -type ChatConfigWithUser struct { - ChatID int64 - SuperGroupUsername string - UserID int64 -} - -func (config ChatConfigWithUser) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero64("user_id", config.UserID) - - return params, nil -} - -// GetChatMemberConfig is information about getting a specific member in a chat. -type GetChatMemberConfig struct { - ChatConfigWithUser -} - -func (GetChatMemberConfig) method() string { - return "getChatMember" -} - -// InvoiceConfig contains information for sendInvoice request. -type InvoiceConfig struct { - BaseChat - Title string // required - Description string // required - Payload string // required - ProviderToken string // required - Currency string // required - Prices []LabeledPrice // required - MaxTipAmount int - SuggestedTipAmounts []int - StartParameter string - ProviderData string - PhotoURL string - PhotoSize int - PhotoWidth int - PhotoHeight int - NeedName bool - NeedPhoneNumber bool - NeedEmail bool - NeedShippingAddress bool - SendPhoneNumberToProvider bool - SendEmailToProvider bool - IsFlexible bool -} - -func (config InvoiceConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params["title"] = config.Title - params["description"] = config.Description - params["payload"] = config.Payload - params["provider_token"] = config.ProviderToken - params["currency"] = config.Currency - if err = params.AddInterface("prices", config.Prices); err != nil { - return params, err - } - - params.AddNonZero("max_tip_amount", config.MaxTipAmount) - err = params.AddInterface("suggested_tip_amounts", config.SuggestedTipAmounts) - params.AddNonEmpty("start_parameter", config.StartParameter) - params.AddNonEmpty("provider_data", config.ProviderData) - params.AddNonEmpty("photo_url", config.PhotoURL) - params.AddNonZero("photo_size", config.PhotoSize) - params.AddNonZero("photo_width", config.PhotoWidth) - params.AddNonZero("photo_height", config.PhotoHeight) - params.AddBool("need_name", config.NeedName) - params.AddBool("need_phone_number", config.NeedPhoneNumber) - params.AddBool("need_email", config.NeedEmail) - params.AddBool("need_shipping_address", config.NeedShippingAddress) - params.AddBool("is_flexible", config.IsFlexible) - params.AddBool("send_phone_number_to_provider", config.SendPhoneNumberToProvider) - params.AddBool("send_email_to_provider", config.SendEmailToProvider) - - return params, err -} - -func (config InvoiceConfig) method() string { - return "sendInvoice" -} - -// ShippingConfig contains information for answerShippingQuery request. -type ShippingConfig struct { - ShippingQueryID string // required - OK bool // required - ShippingOptions []ShippingOption - ErrorMessage string -} - -func (config ShippingConfig) method() string { - return "answerShippingQuery" -} - -func (config ShippingConfig) params() (Params, error) { - params := make(Params) - - params["shipping_query_id"] = config.ShippingQueryID - params.AddBool("ok", config.OK) - err := params.AddInterface("shipping_options", config.ShippingOptions) - params.AddNonEmpty("error_message", config.ErrorMessage) - - return params, err -} - -// PreCheckoutConfig conatins information for answerPreCheckoutQuery request. -type PreCheckoutConfig struct { - PreCheckoutQueryID string // required - OK bool // required - ErrorMessage string -} - -func (config PreCheckoutConfig) method() string { - return "answerPreCheckoutQuery" -} - -func (config PreCheckoutConfig) params() (Params, error) { - params := make(Params) - - params["pre_checkout_query_id"] = config.PreCheckoutQueryID - params.AddBool("ok", config.OK) - params.AddNonEmpty("error_message", config.ErrorMessage) - - return params, nil -} - -// DeleteMessageConfig contains information of a message in a chat to delete. -type DeleteMessageConfig struct { - ChannelUsername string - ChatID int64 - MessageID int -} - -func (config DeleteMessageConfig) method() string { - return "deleteMessage" -} - -func (config DeleteMessageConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) - - return params, nil -} - -// PinChatMessageConfig contains information of a message in a chat to pin. -type PinChatMessageConfig struct { - ChatID int64 - ChannelUsername string - MessageID int - DisableNotification bool -} - -func (config PinChatMessageConfig) method() string { - return "pinChatMessage" -} - -func (config PinChatMessageConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) - params.AddBool("disable_notification", config.DisableNotification) - - return params, nil -} - -// UnpinChatMessageConfig contains information of a chat message to unpin. -// -// If MessageID is not specified, it will unpin the most recent pin. -type UnpinChatMessageConfig struct { - ChatID int64 - ChannelUsername string - MessageID int -} - -func (config UnpinChatMessageConfig) method() string { - return "unpinChatMessage" -} - -func (config UnpinChatMessageConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) - - return params, nil -} - -// UnpinAllChatMessagesConfig contains information of all messages to unpin in -// a chat. -type UnpinAllChatMessagesConfig struct { - ChatID int64 - ChannelUsername string -} - -func (config UnpinAllChatMessagesConfig) method() string { - return "unpinAllChatMessages" -} - -func (config UnpinAllChatMessagesConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil -} - -// SetChatPhotoConfig allows you to set a group, supergroup, or channel's photo. -type SetChatPhotoConfig struct { - BaseFile -} - -func (config SetChatPhotoConfig) method() string { - return "setChatPhoto" -} - -func (config SetChatPhotoConfig) files() []RequestFile { - return []RequestFile{{ - Name: "photo", - Data: config.File, - }} -} - -// DeleteChatPhotoConfig allows you to delete a group, supergroup, or channel's photo. -type DeleteChatPhotoConfig struct { - ChatID int64 - ChannelUsername string -} - -func (config DeleteChatPhotoConfig) method() string { - return "deleteChatPhoto" -} - -func (config DeleteChatPhotoConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil -} - -// SetChatTitleConfig allows you to set the title of something other than a private chat. -type SetChatTitleConfig struct { - ChatID int64 - ChannelUsername string - - Title string -} - -func (config SetChatTitleConfig) method() string { - return "setChatTitle" -} - -func (config SetChatTitleConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params["title"] = config.Title - - return params, nil -} - -// SetChatDescriptionConfig allows you to set the description of a supergroup or channel. -type SetChatDescriptionConfig struct { - ChatID int64 - ChannelUsername string - - Description string -} - -func (config SetChatDescriptionConfig) method() string { - return "setChatDescription" -} - -func (config SetChatDescriptionConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params["description"] = config.Description - - return params, nil -} - -// GetStickerSetConfig allows you to get the stickers in a set. -type GetStickerSetConfig struct { - Name string -} - -func (config GetStickerSetConfig) method() string { - return "getStickerSet" -} - -func (config GetStickerSetConfig) params() (Params, error) { - params := make(Params) - - params["name"] = config.Name - - return params, nil -} - -// UploadStickerConfig allows you to upload a sticker for use in a set later. -type UploadStickerConfig struct { - UserID int64 - PNGSticker RequestFileData -} - -func (config UploadStickerConfig) method() string { - return "uploadStickerFile" -} - -func (config UploadStickerConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero64("user_id", config.UserID) - - return params, nil -} - -func (config UploadStickerConfig) files() []RequestFile { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} -} - -// NewStickerSetConfig allows creating a new sticker set. -// -// You must set either PNGSticker or TGSSticker. -type NewStickerSetConfig struct { - UserID int64 - Name string - Title string - PNGSticker RequestFileData - TGSSticker RequestFileData - Emojis string - ContainsMasks bool - MaskPosition *MaskPosition -} - -func (config NewStickerSetConfig) method() string { - return "createNewStickerSet" -} - -func (config NewStickerSetConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero64("user_id", config.UserID) - params["name"] = config.Name - params["title"] = config.Title - - params["emojis"] = config.Emojis - - params.AddBool("contains_masks", config.ContainsMasks) - - err := params.AddInterface("mask_position", config.MaskPosition) - - return params, err -} - -func (config NewStickerSetConfig) files() []RequestFile { - if config.PNGSticker != nil { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} - } - - return []RequestFile{{ - Name: "tgs_sticker", - Data: config.TGSSticker, - }} -} - -// AddStickerConfig allows you to add a sticker to a set. -type AddStickerConfig struct { - UserID int64 - Name string - PNGSticker RequestFileData - TGSSticker RequestFileData - Emojis string - MaskPosition *MaskPosition -} - -func (config AddStickerConfig) method() string { - return "addStickerToSet" -} - -func (config AddStickerConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero64("user_id", config.UserID) - params["name"] = config.Name - params["emojis"] = config.Emojis - - err := params.AddInterface("mask_position", config.MaskPosition) - - return params, err -} - -func (config AddStickerConfig) files() []RequestFile { - if config.PNGSticker != nil { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} - } - - return []RequestFile{{ - Name: "tgs_sticker", - Data: config.TGSSticker, - }} - -} - -// SetStickerPositionConfig allows you to change the position of a sticker in a set. -type SetStickerPositionConfig struct { - Sticker string - Position int -} - -func (config SetStickerPositionConfig) method() string { - return "setStickerPositionInSet" -} - -func (config SetStickerPositionConfig) params() (Params, error) { - params := make(Params) - - params["sticker"] = config.Sticker - params.AddNonZero("position", config.Position) - - return params, nil -} - -// DeleteStickerConfig allows you to delete a sticker from a set. -type DeleteStickerConfig struct { - Sticker string -} - -func (config DeleteStickerConfig) method() string { - return "deleteStickerFromSet" -} - -func (config DeleteStickerConfig) params() (Params, error) { - params := make(Params) - - params["sticker"] = config.Sticker - - return params, nil -} - -// SetStickerSetThumbConfig allows you to set the thumbnail for a sticker set. -type SetStickerSetThumbConfig struct { - Name string - UserID int64 - Thumb RequestFileData -} - -func (config SetStickerSetThumbConfig) method() string { - return "setStickerSetThumb" -} - -func (config SetStickerSetThumbConfig) params() (Params, error) { - params := make(Params) - - params["name"] = config.Name - params.AddNonZero64("user_id", config.UserID) - - return params, nil -} - -func (config SetStickerSetThumbConfig) files() []RequestFile { - return []RequestFile{{ - Name: "thumb", - Data: config.Thumb, - }} -} - -// SetChatStickerSetConfig allows you to set the sticker set for a supergroup. -type SetChatStickerSetConfig struct { - ChatID int64 - SuperGroupUsername string - - StickerSetName string -} - -func (config SetChatStickerSetConfig) method() string { - return "setChatStickerSet" -} - -func (config SetChatStickerSetConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params["sticker_set_name"] = config.StickerSetName - - return params, nil -} - -// DeleteChatStickerSetConfig allows you to remove a supergroup's sticker set. -type DeleteChatStickerSetConfig struct { - ChatID int64 - SuperGroupUsername string -} - -func (config DeleteChatStickerSetConfig) method() string { - return "deleteChatStickerSet" -} - -func (config DeleteChatStickerSetConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil -} - -// MediaGroupConfig allows you to send a group of media. -// -// Media consist of InputMedia items (InputMediaPhoto, InputMediaVideo). -type MediaGroupConfig struct { - ChatID int64 - ChannelUsername string - - Media []interface{} - DisableNotification bool - ReplyToMessageID int -} - -func (config MediaGroupConfig) method() string { - return "sendMediaGroup" -} - -func (config MediaGroupConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddBool("disable_notification", config.DisableNotification) - params.AddNonZero("reply_to_message_id", config.ReplyToMessageID) - - err := params.AddInterface("media", prepareInputMediaForParams(config.Media)) - - return params, err -} - -func (config MediaGroupConfig) files() []RequestFile { - return prepareInputMediaForFiles(config.Media) -} - -// DiceConfig contains information about a sendDice request. -type DiceConfig struct { - BaseChat - // Emoji on which the dice throw animation is based. - // Currently, must be one of 🎲, 🎯, 🏀, ⚽, 🎳, or 🎰. - // Dice can have values 1-6 for 🎲, 🎯, and 🎳, values 1-5 for 🏀 and ⚽, - // and values 1-64 for 🎰. - // Defaults to “🎲” - Emoji string -} - -func (config DiceConfig) method() string { - return "sendDice" -} - -func (config DiceConfig) params() (Params, error) { - params, err := config.BaseChat.params() - if err != nil { - return params, err - } - - params.AddNonEmpty("emoji", config.Emoji) - - return params, err -} - -// GetMyCommandsConfig gets a list of the currently registered commands. -type GetMyCommandsConfig struct { - Scope *BotCommandScope - LanguageCode string -} - -func (config GetMyCommandsConfig) method() string { - return "getMyCommands" -} - -func (config GetMyCommandsConfig) params() (Params, error) { - params := make(Params) - - err := params.AddInterface("scope", config.Scope) - params.AddNonEmpty("language_code", config.LanguageCode) - - return params, err -} - -// SetMyCommandsConfig sets a list of commands the bot understands. -type SetMyCommandsConfig struct { - Commands []BotCommand - Scope *BotCommandScope - LanguageCode string -} - -func (config SetMyCommandsConfig) method() string { - return "setMyCommands" -} - -func (config SetMyCommandsConfig) params() (Params, error) { - params := make(Params) - - if err := params.AddInterface("commands", config.Commands); err != nil { - return params, err - } - err := params.AddInterface("scope", config.Scope) - params.AddNonEmpty("language_code", config.LanguageCode) - - return params, err -} - -type DeleteMyCommandsConfig struct { - Scope *BotCommandScope - LanguageCode string -} - -func (config DeleteMyCommandsConfig) method() string { - return "deleteMyCommands" -} - -func (config DeleteMyCommandsConfig) params() (Params, error) { - params := make(Params) - - err := params.AddInterface("scope", config.Scope) - params.AddNonEmpty("language_code", config.LanguageCode) - - return params, err -} - -// prepareInputMediaParam evaluates a single InputMedia and determines if it -// needs to be modified for a successful upload. If it returns nil, then the -// value does not need to be included in the params. Otherwise, it will return -// the same type as was originally provided. -// -// The idx is used to calculate the file field name. If you only have a single -// file, 0 may be used. It is formatted into "attach://file-%d" for the primary -// media and "attach://file-%d-thumb" for thumbnails. -// -// It is expected to be used in conjunction with prepareInputMediaFile. -func prepareInputMediaParam(inputMedia interface{}, idx int) interface{} { - switch m := inputMedia.(type) { - case InputMediaPhoto: - if m.Media.NeedsUpload() { - m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) - } - - return m - case InputMediaVideo: - if m.Media.NeedsUpload() { - m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) - } - - if m.Thumb != nil && m.Thumb.NeedsUpload() { - m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) - } - - return m - case InputMediaAudio: - if m.Media.NeedsUpload() { - m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) - } - - if m.Thumb != nil && m.Thumb.NeedsUpload() { - m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) - } - - return m - case InputMediaDocument: - if m.Media.NeedsUpload() { - m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) - } - - if m.Thumb != nil && m.Thumb.NeedsUpload() { - m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) - } - - return m - } - - return nil -} - -// prepareInputMediaFile generates an array of RequestFile to provide for -// Fileable's files method. It returns an array as a single InputMedia may have -// multiple files, for the primary media and a thumbnail. -// -// The idx parameter is used to generate file field names. It uses the names -// "file-%d" for the main file and "file-%d-thumb" for the thumbnail. -// -// It is expected to be used in conjunction with prepareInputMediaParam. -func prepareInputMediaFile(inputMedia interface{}, idx int) []RequestFile { - files := []RequestFile{} - - switch m := inputMedia.(type) { - case InputMediaPhoto: - if m.Media.NeedsUpload() { - files = append(files, RequestFile{ - Name: fmt.Sprintf("file-%d", idx), - Data: m.Media, - }) - } - case InputMediaVideo: - if m.Media.NeedsUpload() { - files = append(files, RequestFile{ - Name: fmt.Sprintf("file-%d", idx), - Data: m.Media, - }) - } - - if m.Thumb != nil && m.Thumb.NeedsUpload() { - files = append(files, RequestFile{ - Name: fmt.Sprintf("file-%d", idx), - Data: m.Thumb, - }) - } - case InputMediaDocument: - if m.Media.NeedsUpload() { - files = append(files, RequestFile{ - Name: fmt.Sprintf("file-%d", idx), - Data: m.Media, - }) - } - - if m.Thumb != nil && m.Thumb.NeedsUpload() { - files = append(files, RequestFile{ - Name: fmt.Sprintf("file-%d", idx), - Data: m.Thumb, - }) - } - case InputMediaAudio: - if m.Media.NeedsUpload() { - files = append(files, RequestFile{ - Name: fmt.Sprintf("file-%d", idx), - Data: m.Media, - }) - } - - if m.Thumb != nil && m.Thumb.NeedsUpload() { - files = append(files, RequestFile{ - Name: fmt.Sprintf("file-%d", idx), - Data: m.Thumb, - }) - } - } - - return files -} - -// prepareInputMediaForParams calls prepareInputMediaParam for each item -// provided and returns a new array with the correct params for a request. -// -// It is expected that files will get data from the associated function, -// prepareInputMediaForFiles. -func prepareInputMediaForParams(inputMedia []interface{}) []interface{} { - newMedia := make([]interface{}, len(inputMedia)) - copy(newMedia, inputMedia) - - for idx, media := range inputMedia { - if param := prepareInputMediaParam(media, idx); param != nil { - newMedia[idx] = param - } - } - - return newMedia -} - -// prepareInputMediaForFiles calls prepareInputMediaFile for each item -// provided and returns a new array with the correct files for a request. -// -// It is expected that params will get data from the associated function, -// prepareInputMediaForParams. -func prepareInputMediaForFiles(inputMedia []interface{}) []RequestFile { - files := []RequestFile{} - - for idx, media := range inputMedia { - if file := prepareInputMediaFile(media, idx); file != nil { - files = append(files, file...) - } - } - - return files -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/go.mod b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/go.mod deleted file mode 100644 index 167e5e45..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/go-telegram-bot-api/telegram-bot-api/v5 - -go 1.16 diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/go.sum b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/go.sum deleted file mode 100644 index e69de29b..00000000 diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/helpers.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/helpers.go deleted file mode 100644 index 8220e74e..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/helpers.go +++ /dev/null @@ -1,927 +0,0 @@ -package tgbotapi - -import ( - "net/url" -) - -// NewMessage creates a new Message. -// -// chatID is where to send it, text is the message text. -func NewMessage(chatID int64, text string) MessageConfig { - return MessageConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - ReplyToMessageID: 0, - }, - Text: text, - DisableWebPagePreview: false, - } -} - -// NewDeleteMessage creates a request to delete a message. -func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { - return DeleteMessageConfig{ - ChatID: chatID, - MessageID: messageID, - } -} - -// NewMessageToChannel creates a new Message that is sent to a channel -// by username. -// -// username is the username of the channel, text is the message text, -// and the username should be in the form of `@username`. -func NewMessageToChannel(username string, text string) MessageConfig { - return MessageConfig{ - BaseChat: BaseChat{ - ChannelUsername: username, - }, - Text: text, - } -} - -// NewForward creates a new forward. -// -// chatID is where to send it, fromChatID is the source chat, -// and messageID is the ID of the original message. -func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig { - return ForwardConfig{ - BaseChat: BaseChat{ChatID: chatID}, - FromChatID: fromChatID, - MessageID: messageID, - } -} - -// NewCopyMessage creates a new copy message. -// -// chatID is where to send it, fromChatID is the source chat, -// and messageID is the ID of the original message. -func NewCopyMessage(chatID int64, fromChatID int64, messageID int) CopyMessageConfig { - return CopyMessageConfig{ - BaseChat: BaseChat{ChatID: chatID}, - FromChatID: fromChatID, - MessageID: messageID, - } -} - -// NewPhoto creates a new sendPhoto request. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -// -// Note that you must send animated GIFs as a document. -func NewPhoto(chatID int64, file RequestFileData) PhotoConfig { - return PhotoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - } -} - -// NewPhotoToChannel creates a new photo uploader to send a photo to a channel. -// -// Note that you must send animated GIFs as a document. -func NewPhotoToChannel(username string, file RequestFileData) PhotoConfig { - return PhotoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ - ChannelUsername: username, - }, - File: file, - }, - } -} - -// NewAudio creates a new sendAudio request. -func NewAudio(chatID int64, file RequestFileData) AudioConfig { - return AudioConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - } -} - -// NewDocument creates a new sendDocument request. -func NewDocument(chatID int64, file RequestFileData) DocumentConfig { - return DocumentConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - } -} - -// NewSticker creates a new sendSticker request. -func NewSticker(chatID int64, file RequestFileData) StickerConfig { - return StickerConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - } -} - -// NewVideo creates a new sendVideo request. -func NewVideo(chatID int64, file RequestFileData) VideoConfig { - return VideoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - } -} - -// NewAnimation creates a new sendAnimation request. -func NewAnimation(chatID int64, file RequestFileData) AnimationConfig { - return AnimationConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - } -} - -// NewVideoNote creates a new sendVideoNote request. -// -// chatID is where to send it, file is a string path to the file, -// FileReader, or FileBytes. -func NewVideoNote(chatID int64, length int, file RequestFileData) VideoNoteConfig { - return VideoNoteConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - Length: length, - } -} - -// NewVoice creates a new sendVoice request. -func NewVoice(chatID int64, file RequestFileData) VoiceConfig { - return VoiceConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, - File: file, - }, - } -} - -// NewMediaGroup creates a new media group. Files should be an array of -// two to ten InputMediaPhoto or InputMediaVideo. -func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { - return MediaGroupConfig{ - ChatID: chatID, - Media: files, - } -} - -// NewInputMediaPhoto creates a new InputMediaPhoto. -func NewInputMediaPhoto(media RequestFileData) InputMediaPhoto { - return InputMediaPhoto{ - BaseInputMedia{ - Type: "photo", - Media: media, - }, - } -} - -// NewInputMediaVideo creates a new InputMediaVideo. -func NewInputMediaVideo(media RequestFileData) InputMediaVideo { - return InputMediaVideo{ - BaseInputMedia: BaseInputMedia{ - Type: "video", - Media: media, - }, - } -} - -// NewInputMediaAnimation creates a new InputMediaAnimation. -func NewInputMediaAnimation(media RequestFileData) InputMediaAnimation { - return InputMediaAnimation{ - BaseInputMedia: BaseInputMedia{ - Type: "animation", - Media: media, - }, - } -} - -// NewInputMediaAudio creates a new InputMediaAudio. -func NewInputMediaAudio(media RequestFileData) InputMediaAudio { - return InputMediaAudio{ - BaseInputMedia: BaseInputMedia{ - Type: "audio", - Media: media, - }, - } -} - -// NewInputMediaDocument creates a new InputMediaDocument. -func NewInputMediaDocument(media RequestFileData) InputMediaDocument { - return InputMediaDocument{ - BaseInputMedia: BaseInputMedia{ - Type: "document", - Media: media, - }, - } -} - -// NewContact allows you to send a shared contact. -func NewContact(chatID int64, phoneNumber, firstName string) ContactConfig { - return ContactConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - PhoneNumber: phoneNumber, - FirstName: firstName, - } -} - -// NewLocation shares your location. -// -// chatID is where to send it, latitude and longitude are coordinates. -func NewLocation(chatID int64, latitude float64, longitude float64) LocationConfig { - return LocationConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - Latitude: latitude, - Longitude: longitude, - } -} - -// NewVenue allows you to send a venue and its location. -func NewVenue(chatID int64, title, address string, latitude, longitude float64) VenueConfig { - return VenueConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - Title: title, - Address: address, - Latitude: latitude, - Longitude: longitude, - } -} - -// NewChatAction sets a chat action. -// Actions last for 5 seconds, or until your next action. -// -// chatID is where to send it, action should be set via Chat constants. -func NewChatAction(chatID int64, action string) ChatActionConfig { - return ChatActionConfig{ - BaseChat: BaseChat{ChatID: chatID}, - Action: action, - } -} - -// NewUserProfilePhotos gets user profile photos. -// -// userID is the ID of the user you wish to get profile photos from. -func NewUserProfilePhotos(userID int64) UserProfilePhotosConfig { - return UserProfilePhotosConfig{ - UserID: userID, - Offset: 0, - Limit: 0, - } -} - -// NewUpdate gets updates since the last Offset. -// -// offset is the last Update ID to include. -// You likely want to set this to the last Update ID plus 1. -func NewUpdate(offset int) UpdateConfig { - return UpdateConfig{ - Offset: offset, - Limit: 0, - Timeout: 0, - } -} - -// NewWebhook creates a new webhook. -// -// link is the url parsable link you wish to get the updates. -func NewWebhook(link string) (WebhookConfig, error) { - u, err := url.Parse(link) - - if err != nil { - return WebhookConfig{}, err - } - - return WebhookConfig{ - URL: u, - }, nil -} - -// NewWebhookWithCert creates a new webhook with a certificate. -// -// link is the url you wish to get webhooks, -// file contains a string to a file, FileReader, or FileBytes. -func NewWebhookWithCert(link string, file RequestFileData) (WebhookConfig, error) { - u, err := url.Parse(link) - - if err != nil { - return WebhookConfig{}, err - } - - return WebhookConfig{ - URL: u, - Certificate: file, - }, nil -} - -// NewInlineQueryResultArticle creates a new inline query article. -func NewInlineQueryResultArticle(id, title, messageText string) InlineQueryResultArticle { - return InlineQueryResultArticle{ - Type: "article", - ID: id, - Title: title, - InputMessageContent: InputTextMessageContent{ - Text: messageText, - }, - } -} - -// NewInlineQueryResultArticleMarkdown creates a new inline query article with Markdown parsing. -func NewInlineQueryResultArticleMarkdown(id, title, messageText string) InlineQueryResultArticle { - return InlineQueryResultArticle{ - Type: "article", - ID: id, - Title: title, - InputMessageContent: InputTextMessageContent{ - Text: messageText, - ParseMode: "Markdown", - }, - } -} - -// NewInlineQueryResultArticleMarkdownV2 creates a new inline query article with MarkdownV2 parsing. -func NewInlineQueryResultArticleMarkdownV2(id, title, messageText string) InlineQueryResultArticle { - return InlineQueryResultArticle{ - Type: "article", - ID: id, - Title: title, - InputMessageContent: InputTextMessageContent{ - Text: messageText, - ParseMode: "MarkdownV2", - }, - } -} - -// NewInlineQueryResultArticleHTML creates a new inline query article with HTML parsing. -func NewInlineQueryResultArticleHTML(id, title, messageText string) InlineQueryResultArticle { - return InlineQueryResultArticle{ - Type: "article", - ID: id, - Title: title, - InputMessageContent: InputTextMessageContent{ - Text: messageText, - ParseMode: "HTML", - }, - } -} - -// NewInlineQueryResultGIF creates a new inline query GIF. -func NewInlineQueryResultGIF(id, url string) InlineQueryResultGIF { - return InlineQueryResultGIF{ - Type: "gif", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultCachedGIF create a new inline query with cached photo. -func NewInlineQueryResultCachedGIF(id, gifID string) InlineQueryResultCachedGIF { - return InlineQueryResultCachedGIF{ - Type: "gif", - ID: id, - GIFID: gifID, - } -} - -// NewInlineQueryResultMPEG4GIF creates a new inline query MPEG4 GIF. -func NewInlineQueryResultMPEG4GIF(id, url string) InlineQueryResultMPEG4GIF { - return InlineQueryResultMPEG4GIF{ - Type: "mpeg4_gif", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultCachedMPEG4GIF create a new inline query with cached MPEG4 GIF. -func NewInlineQueryResultCachedMPEG4GIF(id, MPEG4GIFID string) InlineQueryResultCachedMPEG4GIF { - return InlineQueryResultCachedMPEG4GIF{ - Type: "mpeg4_gif", - ID: id, - MPEG4FileID: MPEG4GIFID, - } -} - -// NewInlineQueryResultPhoto creates a new inline query photo. -func NewInlineQueryResultPhoto(id, url string) InlineQueryResultPhoto { - return InlineQueryResultPhoto{ - Type: "photo", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultPhotoWithThumb creates a new inline query photo. -func NewInlineQueryResultPhotoWithThumb(id, url, thumb string) InlineQueryResultPhoto { - return InlineQueryResultPhoto{ - Type: "photo", - ID: id, - URL: url, - ThumbURL: thumb, - } -} - -// NewInlineQueryResultCachedPhoto create a new inline query with cached photo. -func NewInlineQueryResultCachedPhoto(id, photoID string) InlineQueryResultCachedPhoto { - return InlineQueryResultCachedPhoto{ - Type: "photo", - ID: id, - PhotoID: photoID, - } -} - -// NewInlineQueryResultVideo creates a new inline query video. -func NewInlineQueryResultVideo(id, url string) InlineQueryResultVideo { - return InlineQueryResultVideo{ - Type: "video", - ID: id, - URL: url, - } -} - -// NewInlineQueryResultCachedVideo create a new inline query with cached video. -func NewInlineQueryResultCachedVideo(id, videoID, title string) InlineQueryResultCachedVideo { - return InlineQueryResultCachedVideo{ - Type: "video", - ID: id, - VideoID: videoID, - Title: title, - } -} - -// NewInlineQueryResultCachedSticker create a new inline query with cached sticker. -func NewInlineQueryResultCachedSticker(id, stickerID, title string) InlineQueryResultCachedSticker { - return InlineQueryResultCachedSticker{ - Type: "sticker", - ID: id, - StickerID: stickerID, - Title: title, - } -} - -// NewInlineQueryResultAudio creates a new inline query audio. -func NewInlineQueryResultAudio(id, url, title string) InlineQueryResultAudio { - return InlineQueryResultAudio{ - Type: "audio", - ID: id, - URL: url, - Title: title, - } -} - -// NewInlineQueryResultCachedAudio create a new inline query with cached photo. -func NewInlineQueryResultCachedAudio(id, audioID string) InlineQueryResultCachedAudio { - return InlineQueryResultCachedAudio{ - Type: "audio", - ID: id, - AudioID: audioID, - } -} - -// NewInlineQueryResultVoice creates a new inline query voice. -func NewInlineQueryResultVoice(id, url, title string) InlineQueryResultVoice { - return InlineQueryResultVoice{ - Type: "voice", - ID: id, - URL: url, - Title: title, - } -} - -// NewInlineQueryResultCachedVoice create a new inline query with cached photo. -func NewInlineQueryResultCachedVoice(id, voiceID, title string) InlineQueryResultCachedVoice { - return InlineQueryResultCachedVoice{ - Type: "voice", - ID: id, - VoiceID: voiceID, - Title: title, - } -} - -// NewInlineQueryResultDocument creates a new inline query document. -func NewInlineQueryResultDocument(id, url, title, mimeType string) InlineQueryResultDocument { - return InlineQueryResultDocument{ - Type: "document", - ID: id, - URL: url, - Title: title, - MimeType: mimeType, - } -} - -// NewInlineQueryResultCachedDocument create a new inline query with cached photo. -func NewInlineQueryResultCachedDocument(id, documentID, title string) InlineQueryResultCachedDocument { - return InlineQueryResultCachedDocument{ - Type: "document", - ID: id, - DocumentID: documentID, - Title: title, - } -} - -// NewInlineQueryResultLocation creates a new inline query location. -func NewInlineQueryResultLocation(id, title string, latitude, longitude float64) InlineQueryResultLocation { - return InlineQueryResultLocation{ - Type: "location", - ID: id, - Title: title, - Latitude: latitude, - Longitude: longitude, - } -} - -// NewInlineQueryResultVenue creates a new inline query venue. -func NewInlineQueryResultVenue(id, title, address string, latitude, longitude float64) InlineQueryResultVenue { - return InlineQueryResultVenue{ - Type: "venue", - ID: id, - Title: title, - Address: address, - Latitude: latitude, - Longitude: longitude, - } -} - -// NewEditMessageText allows you to edit the text of a message. -func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTextConfig { - return EditMessageTextConfig{ - BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, - }, - Text: text, - } -} - -// NewEditMessageTextAndMarkup allows you to edit the text and replymarkup of a message. -func NewEditMessageTextAndMarkup(chatID int64, messageID int, text string, replyMarkup InlineKeyboardMarkup) EditMessageTextConfig { - return EditMessageTextConfig{ - BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, - ReplyMarkup: &replyMarkup, - }, - Text: text, - } -} - -// NewEditMessageCaption allows you to edit the caption of a message. -func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMessageCaptionConfig { - return EditMessageCaptionConfig{ - BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, - }, - Caption: caption, - } -} - -// NewEditMessageReplyMarkup allows you to edit the inline -// keyboard markup. -func NewEditMessageReplyMarkup(chatID int64, messageID int, replyMarkup InlineKeyboardMarkup) EditMessageReplyMarkupConfig { - return EditMessageReplyMarkupConfig{ - BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, - ReplyMarkup: &replyMarkup, - }, - } -} - -// NewRemoveKeyboard hides the keyboard, with the option for being selective -// or hiding for everyone. -func NewRemoveKeyboard(selective bool) ReplyKeyboardRemove { - return ReplyKeyboardRemove{ - RemoveKeyboard: true, - Selective: selective, - } -} - -// NewKeyboardButton creates a regular keyboard button. -func NewKeyboardButton(text string) KeyboardButton { - return KeyboardButton{ - Text: text, - } -} - -// NewKeyboardButtonContact creates a keyboard button that requests -// user contact information upon click. -func NewKeyboardButtonContact(text string) KeyboardButton { - return KeyboardButton{ - Text: text, - RequestContact: true, - } -} - -// NewKeyboardButtonLocation creates a keyboard button that requests -// user location information upon click. -func NewKeyboardButtonLocation(text string) KeyboardButton { - return KeyboardButton{ - Text: text, - RequestLocation: true, - } -} - -// NewKeyboardButtonRow creates a row of keyboard buttons. -func NewKeyboardButtonRow(buttons ...KeyboardButton) []KeyboardButton { - var row []KeyboardButton - - row = append(row, buttons...) - - return row -} - -// NewReplyKeyboard creates a new regular keyboard with sane defaults. -func NewReplyKeyboard(rows ...[]KeyboardButton) ReplyKeyboardMarkup { - var keyboard [][]KeyboardButton - - keyboard = append(keyboard, rows...) - - return ReplyKeyboardMarkup{ - ResizeKeyboard: true, - Keyboard: keyboard, - } -} - -// NewOneTimeReplyKeyboard creates a new one time keyboard. -func NewOneTimeReplyKeyboard(rows ...[]KeyboardButton) ReplyKeyboardMarkup { - markup := NewReplyKeyboard(rows...) - markup.OneTimeKeyboard = true - return markup -} - -// NewInlineKeyboardButtonData creates an inline keyboard button with text -// and data for a callback. -func NewInlineKeyboardButtonData(text, data string) InlineKeyboardButton { - return InlineKeyboardButton{ - Text: text, - CallbackData: &data, - } -} - -// NewInlineKeyboardButtonLoginURL creates an inline keyboard button with text -// which goes to a LoginURL. -func NewInlineKeyboardButtonLoginURL(text string, loginURL LoginURL) InlineKeyboardButton { - return InlineKeyboardButton{ - Text: text, - LoginURL: &loginURL, - } -} - -// NewInlineKeyboardButtonURL creates an inline keyboard button with text -// which goes to a URL. -func NewInlineKeyboardButtonURL(text, url string) InlineKeyboardButton { - return InlineKeyboardButton{ - Text: text, - URL: &url, - } -} - -// NewInlineKeyboardButtonSwitch creates an inline keyboard button with -// text which allows the user to switch to a chat or return to a chat. -func NewInlineKeyboardButtonSwitch(text, sw string) InlineKeyboardButton { - return InlineKeyboardButton{ - Text: text, - SwitchInlineQuery: &sw, - } -} - -// NewInlineKeyboardRow creates an inline keyboard row with buttons. -func NewInlineKeyboardRow(buttons ...InlineKeyboardButton) []InlineKeyboardButton { - var row []InlineKeyboardButton - - row = append(row, buttons...) - - return row -} - -// NewInlineKeyboardMarkup creates a new inline keyboard. -func NewInlineKeyboardMarkup(rows ...[]InlineKeyboardButton) InlineKeyboardMarkup { - var keyboard [][]InlineKeyboardButton - - keyboard = append(keyboard, rows...) - - return InlineKeyboardMarkup{ - InlineKeyboard: keyboard, - } -} - -// NewCallback creates a new callback message. -func NewCallback(id, text string) CallbackConfig { - return CallbackConfig{ - CallbackQueryID: id, - Text: text, - ShowAlert: false, - } -} - -// NewCallbackWithAlert creates a new callback message that alerts -// the user. -func NewCallbackWithAlert(id, text string) CallbackConfig { - return CallbackConfig{ - CallbackQueryID: id, - Text: text, - ShowAlert: true, - } -} - -// NewInvoice creates a new Invoice request to the user. -func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices []LabeledPrice) InvoiceConfig { - return InvoiceConfig{ - BaseChat: BaseChat{ChatID: chatID}, - Title: title, - Description: description, - Payload: payload, - ProviderToken: providerToken, - StartParameter: startParameter, - Currency: currency, - Prices: prices} -} - -// NewChatTitle allows you to update the title of a chat. -func NewChatTitle(chatID int64, title string) SetChatTitleConfig { - return SetChatTitleConfig{ - ChatID: chatID, - Title: title, - } -} - -// NewChatDescription allows you to update the description of a chat. -func NewChatDescription(chatID int64, description string) SetChatDescriptionConfig { - return SetChatDescriptionConfig{ - ChatID: chatID, - Description: description, - } -} - -// NewChatPhoto allows you to update the photo for a chat. -func NewChatPhoto(chatID int64, photo RequestFileData) SetChatPhotoConfig { - return SetChatPhotoConfig{ - BaseFile: BaseFile{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - File: photo, - }, - } -} - -// NewDeleteChatPhoto allows you to delete the photo for a chat. -func NewDeleteChatPhoto(chatID int64) DeleteChatPhotoConfig { - return DeleteChatPhotoConfig{ - ChatID: chatID, - } -} - -// NewPoll allows you to create a new poll. -func NewPoll(chatID int64, question string, options ...string) SendPollConfig { - return SendPollConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - Question: question, - Options: options, - IsAnonymous: true, // This is Telegram's default. - } -} - -// NewStopPoll allows you to stop a poll. -func NewStopPoll(chatID int64, messageID int) StopPollConfig { - return StopPollConfig{ - BaseEdit{ - ChatID: chatID, - MessageID: messageID, - }, - } -} - -// NewDice allows you to send a random dice roll. -func NewDice(chatID int64) DiceConfig { - return DiceConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - } -} - -// NewDiceWithEmoji allows you to send a random roll of one of many types. -// -// Emoji may be 🎲 (1-6), 🎯 (1-6), or 🏀 (1-5). -func NewDiceWithEmoji(chatID int64, emoji string) DiceConfig { - return DiceConfig{ - BaseChat: BaseChat{ - ChatID: chatID, - }, - Emoji: emoji, - } -} - -// NewBotCommandScopeDefault represents the default scope of bot commands. -func NewBotCommandScopeDefault() BotCommandScope { - return BotCommandScope{Type: "default"} -} - -// NewBotCommandScopeAllPrivateChats represents the scope of bot commands, -// covering all private chats. -func NewBotCommandScopeAllPrivateChats() BotCommandScope { - return BotCommandScope{Type: "all_private_chats"} -} - -// NewBotCommandScopeAllGroupChats represents the scope of bot commands, -// covering all group and supergroup chats. -func NewBotCommandScopeAllGroupChats() BotCommandScope { - return BotCommandScope{Type: "all_group_chats"} -} - -// NewBotCommandScopeAllChatAdministrators represents the scope of bot commands, -// covering all group and supergroup chat administrators. -func NewBotCommandScopeAllChatAdministrators() BotCommandScope { - return BotCommandScope{Type: "all_chat_administrators"} -} - -// NewBotCommandScopeChat represents the scope of bot commands, covering a -// specific chat. -func NewBotCommandScopeChat(chatID int64) BotCommandScope { - return BotCommandScope{ - Type: "chat", - ChatID: chatID, - } -} - -// NewBotCommandScopeChatAdministrators represents the scope of bot commands, -// covering all administrators of a specific group or supergroup chat. -func NewBotCommandScopeChatAdministrators(chatID int64) BotCommandScope { - return BotCommandScope{ - Type: "chat_administrators", - ChatID: chatID, - } -} - -// NewBotCommandScopeChatMember represents the scope of bot commands, covering a -// specific member of a group or supergroup chat. -func NewBotCommandScopeChatMember(chatID, userID int64) BotCommandScope { - return BotCommandScope{ - Type: "chat_member", - ChatID: chatID, - UserID: userID, - } -} - -// NewGetMyCommandsWithScope allows you to set the registered commands for a -// given scope. -func NewGetMyCommandsWithScope(scope BotCommandScope) GetMyCommandsConfig { - return GetMyCommandsConfig{Scope: &scope} -} - -// NewGetMyCommandsWithScopeAndLanguage allows you to set the registered -// commands for a given scope and language code. -func NewGetMyCommandsWithScopeAndLanguage(scope BotCommandScope, languageCode string) GetMyCommandsConfig { - return GetMyCommandsConfig{Scope: &scope, LanguageCode: languageCode} -} - -// NewSetMyCommands allows you to set the registered commands. -func NewSetMyCommands(commands ...BotCommand) SetMyCommandsConfig { - return SetMyCommandsConfig{Commands: commands} -} - -// NewSetMyCommandsWithScope allows you to set the registered commands for a given scope. -func NewSetMyCommandsWithScope(scope BotCommandScope, commands ...BotCommand) SetMyCommandsConfig { - return SetMyCommandsConfig{Commands: commands, Scope: &scope} -} - -// NewSetMyCommandsWithScopeAndLanguage allows you to set the registered commands for a given scope -// and language code. -func NewSetMyCommandsWithScopeAndLanguage(scope BotCommandScope, languageCode string, commands ...BotCommand) SetMyCommandsConfig { - return SetMyCommandsConfig{Commands: commands, Scope: &scope, LanguageCode: languageCode} -} - -// NewDeleteMyCommands allows you to delete the registered commands. -func NewDeleteMyCommands() DeleteMyCommandsConfig { - return DeleteMyCommandsConfig{} -} - -// NewDeleteMyCommandsWithScope allows you to delete the registered commands for a given -// scope. -func NewDeleteMyCommandsWithScope(scope BotCommandScope) DeleteMyCommandsConfig { - return DeleteMyCommandsConfig{Scope: &scope} -} - -// NewDeleteMyCommandsWithScopeAndLanguage allows you to delete the registered commands for a given -// scope and language code. -func NewDeleteMyCommandsWithScopeAndLanguage(scope BotCommandScope, languageCode string) DeleteMyCommandsConfig { - return DeleteMyCommandsConfig{Scope: &scope, LanguageCode: languageCode} -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/log.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/log.go deleted file mode 100644 index 18725514..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/log.go +++ /dev/null @@ -1,27 +0,0 @@ -package tgbotapi - -import ( - "errors" - stdlog "log" - "os" -) - -// BotLogger is an interface that represents the required methods to log data. -// -// Instead of requiring the standard logger, we can just specify the methods we -// use and allow users to pass anything that implements these. -type BotLogger interface { - Println(v ...interface{}) - Printf(format string, v ...interface{}) -} - -var log BotLogger = stdlog.New(os.Stderr, "", stdlog.LstdFlags) - -// SetLogger specifies the logger that the package should use. -func SetLogger(logger BotLogger) error { - if logger == nil { - return errors.New("logger is nil") - } - log = logger - return nil -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/params.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/params.go deleted file mode 100644 index 134f85e4..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/params.go +++ /dev/null @@ -1,97 +0,0 @@ -package tgbotapi - -import ( - "encoding/json" - "reflect" - "strconv" -) - -// Params represents a set of parameters that gets passed to a request. -type Params map[string]string - -// AddNonEmpty adds a value if it not an empty string. -func (p Params) AddNonEmpty(key, value string) { - if value != "" { - p[key] = value - } -} - -// AddNonZero adds a value if it is not zero. -func (p Params) AddNonZero(key string, value int) { - if value != 0 { - p[key] = strconv.Itoa(value) - } -} - -// AddNonZero64 is the same as AddNonZero except uses an int64. -func (p Params) AddNonZero64(key string, value int64) { - if value != 0 { - p[key] = strconv.FormatInt(value, 10) - } -} - -// AddBool adds a value of a bool if it is true. -func (p Params) AddBool(key string, value bool) { - if value { - p[key] = strconv.FormatBool(value) - } -} - -// AddNonZeroFloat adds a floating point value that is not zero. -func (p Params) AddNonZeroFloat(key string, value float64) { - if value != 0 { - p[key] = strconv.FormatFloat(value, 'f', 6, 64) - } -} - -// AddInterface adds an interface if it is not nil and can be JSON marshalled. -func (p Params) AddInterface(key string, value interface{}) error { - if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) { - return nil - } - - b, err := json.Marshal(value) - if err != nil { - return err - } - - p[key] = string(b) - - return nil -} - -// AddFirstValid attempts to add the first item that is not a default value. -// -// For example, AddFirstValid(0, "", "test") would add "test". -func (p Params) AddFirstValid(key string, args ...interface{}) error { - for _, arg := range args { - switch v := arg.(type) { - case int: - if v != 0 { - p[key] = strconv.Itoa(v) - return nil - } - case int64: - if v != 0 { - p[key] = strconv.FormatInt(v, 10) - return nil - } - case string: - if v != "" { - p[key] = v - return nil - } - case nil: - default: - b, err := json.Marshal(arg) - if err != nil { - return err - } - - p[key] = string(b) - return nil - } - } - - return nil -} diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/passport.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/passport.go deleted file mode 100644 index 4fedb965..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/passport.go +++ /dev/null @@ -1,317 +0,0 @@ -package tgbotapi - -// PassportRequestInfoConfig allows you to request passport info -type PassportRequestInfoConfig struct { - BotID int `json:"bot_id"` - Scope *PassportScope `json:"scope"` - Nonce string `json:"nonce"` - PublicKey string `json:"public_key"` -} - -// PassportScopeElement supports using one or one of several elements. -type PassportScopeElement interface { - ScopeType() string -} - -// PassportScope is the requested scopes of data. -type PassportScope struct { - V int `json:"v"` - Data []PassportScopeElement `json:"data"` -} - -// PassportScopeElementOneOfSeveral allows you to request any one of the -// requested documents. -type PassportScopeElementOneOfSeveral struct { -} - -// ScopeType is the scope type. -func (eo *PassportScopeElementOneOfSeveral) ScopeType() string { - return "one_of" -} - -// PassportScopeElementOne requires the specified element be provided. -type PassportScopeElementOne struct { - Type string `json:"type"` // One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email” - Selfie bool `json:"selfie"` - Translation bool `json:"translation"` - NativeNames bool `json:"native_name"` -} - -// ScopeType is the scope type. -func (eo *PassportScopeElementOne) ScopeType() string { - return "one" -} - -type ( - // PassportData contains information about Telegram Passport data shared with - // the bot by the user. - PassportData struct { - // Array with information about documents and other Telegram Passport - // elements that was shared with the bot - Data []EncryptedPassportElement `json:"data"` - - // Encrypted credentials required to decrypt the data - Credentials *EncryptedCredentials `json:"credentials"` - } - - // PassportFile represents a file uploaded to Telegram Passport. Currently, all - // Telegram Passport files are in JPEG format when decrypted and don't exceed - // 10MB. - PassportFile struct { - // Unique identifier for this file - FileID string `json:"file_id"` - - FileUniqueID string `json:"file_unique_id"` - - // File size - FileSize int `json:"file_size"` - - // Unix time when the file was uploaded - FileDate int64 `json:"file_date"` - } - - // EncryptedPassportElement contains information about documents or other - // Telegram Passport elements shared with the bot by the user. - EncryptedPassportElement struct { - // Element type. - Type string `json:"type"` - - // Base64-encoded encrypted Telegram Passport element data provided by - // the user, available for "personal_details", "passport", - // "driver_license", "identity_card", "identity_passport" and "address" - // types. Can be decrypted and verified using the accompanying - // EncryptedCredentials. - Data string `json:"data,omitempty"` - - // User's verified phone number, available only for "phone_number" type - PhoneNumber string `json:"phone_number,omitempty"` - - // User's verified email address, available only for "email" type - Email string `json:"email,omitempty"` - - // Array of encrypted files with documents provided by the user, - // available for "utility_bill", "bank_statement", "rental_agreement", - // "passport_registration" and "temporary_registration" types. Files can - // be decrypted and verified using the accompanying EncryptedCredentials. - Files []PassportFile `json:"files,omitempty"` - - // Encrypted file with the front side of the document, provided by the - // user. Available for "passport", "driver_license", "identity_card" and - // "internal_passport". The file can be decrypted and verified using the - // accompanying EncryptedCredentials. - FrontSide *PassportFile `json:"front_side,omitempty"` - - // Encrypted file with the reverse side of the document, provided by the - // user. Available for "driver_license" and "identity_card". The file can - // be decrypted and verified using the accompanying EncryptedCredentials. - ReverseSide *PassportFile `json:"reverse_side,omitempty"` - - // Encrypted file with the selfie of the user holding a document, - // provided by the user; available for "passport", "driver_license", - // "identity_card" and "internal_passport". The file can be decrypted - // and verified using the accompanying EncryptedCredentials. - Selfie *PassportFile `json:"selfie,omitempty"` - } - - // EncryptedCredentials contains data required for decrypting and - // authenticating EncryptedPassportElement. See the Telegram Passport - // Documentation for a complete description of the data decryption and - // authentication processes. - EncryptedCredentials struct { - // Base64-encoded encrypted JSON-serialized data with unique user's - // payload, data hashes and secrets required for EncryptedPassportElement - // decryption and authentication - Data string `json:"data"` - - // Base64-encoded data hash for data authentication - Hash string `json:"hash"` - - // Base64-encoded secret, encrypted with the bot's public RSA key, - // required for data decryption - Secret string `json:"secret"` - } - - // PassportElementError represents an error in the Telegram Passport element - // which was submitted that should be resolved by the user. - PassportElementError interface{} - - // PassportElementErrorDataField represents an issue in one of the data - // fields that was provided by the user. The error is considered resolved - // when the field's value changes. - PassportElementErrorDataField struct { - // Error source, must be data - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the error, one - // of "personal_details", "passport", "driver_license", "identity_card", - // "internal_passport", "address" - Type string `json:"type"` - - // Name of the data field which has the error - FieldName string `json:"field_name"` - - // Base64-encoded data hash - DataHash string `json:"data_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorFrontSide represents an issue with the front side of - // a document. The error is considered resolved when the file with the front - // side of the document changes. - PassportElementErrorFrontSide struct { - // Error source, must be front_side - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "passport", "driver_license", "identity_card", "internal_passport" - Type string `json:"type"` - - // Base64-encoded hash of the file with the front side of the document - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorReverseSide represents an issue with the reverse side - // of a document. The error is considered resolved when the file with reverse - // side of the document changes. - PassportElementErrorReverseSide struct { - // Error source, must be reverse_side - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "driver_license", "identity_card" - Type string `json:"type"` - - // Base64-encoded hash of the file with the reverse side of the document - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorSelfie represents an issue with the selfie with a - // document. The error is considered resolved when the file with the selfie - // changes. - PassportElementErrorSelfie struct { - // Error source, must be selfie - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "passport", "driver_license", "identity_card", "internal_passport" - Type string `json:"type"` - - // Base64-encoded hash of the file with the selfie - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorFile represents an issue with a document scan. The - // error is considered resolved when the file with the document scan changes. - PassportElementErrorFile struct { - // Error source, must be a file - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "utility_bill", "bank_statement", "rental_agreement", - // "passport_registration", "temporary_registration" - Type string `json:"type"` - - // Base64-encoded file hash - FileHash string `json:"file_hash"` - - // Error message - Message string `json:"message"` - } - - // PassportElementErrorFiles represents an issue with a list of scans. The - // error is considered resolved when the list of files containing the scans - // changes. - PassportElementErrorFiles struct { - // Error source, must be files - Source string `json:"source"` - - // The section of the user's Telegram Passport which has the issue, one - // of "utility_bill", "bank_statement", "rental_agreement", - // "passport_registration", "temporary_registration" - Type string `json:"type"` - - // List of base64-encoded file hashes - FileHashes []string `json:"file_hashes"` - - // Error message - Message string `json:"message"` - } - - // Credentials contains encrypted data. - Credentials struct { - Data SecureData `json:"secure_data"` - // Nonce the same nonce given in the request - Nonce string `json:"nonce"` - } - - // SecureData is a map of the fields and their encrypted values. - SecureData map[string]*SecureValue - // PersonalDetails *SecureValue `json:"personal_details"` - // Passport *SecureValue `json:"passport"` - // InternalPassport *SecureValue `json:"internal_passport"` - // DriverLicense *SecureValue `json:"driver_license"` - // IdentityCard *SecureValue `json:"identity_card"` - // Address *SecureValue `json:"address"` - // UtilityBill *SecureValue `json:"utility_bill"` - // BankStatement *SecureValue `json:"bank_statement"` - // RentalAgreement *SecureValue `json:"rental_agreement"` - // PassportRegistration *SecureValue `json:"passport_registration"` - // TemporaryRegistration *SecureValue `json:"temporary_registration"` - - // SecureValue contains encrypted values for a SecureData item. - SecureValue struct { - Data *DataCredentials `json:"data"` - FrontSide *FileCredentials `json:"front_side"` - ReverseSide *FileCredentials `json:"reverse_side"` - Selfie *FileCredentials `json:"selfie"` - Translation []*FileCredentials `json:"translation"` - Files []*FileCredentials `json:"files"` - } - - // DataCredentials contains information required to decrypt data. - DataCredentials struct { - // DataHash checksum of encrypted data - DataHash string `json:"data_hash"` - // Secret of encrypted data - Secret string `json:"secret"` - } - - // FileCredentials contains information required to decrypt files. - FileCredentials struct { - // FileHash checksum of encrypted data - FileHash string `json:"file_hash"` - // Secret of encrypted data - Secret string `json:"secret"` - } - - // PersonalDetails https://core.telegram.org/passport#personaldetails - PersonalDetails struct { - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - MiddleName string `json:"middle_name"` - BirthDate string `json:"birth_date"` - Gender string `json:"gender"` - CountryCode string `json:"country_code"` - ResidenceCountryCode string `json:"residence_country_code"` - FirstNameNative string `json:"first_name_native"` - LastNameNative string `json:"last_name_native"` - MiddleNameNative string `json:"middle_name_native"` - } - - // IDDocumentData https://core.telegram.org/passport#iddocumentdata - IDDocumentData struct { - DocumentNumber string `json:"document_no"` - ExpiryDate string `json:"expiry_date"` - } -) diff --git a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/types.go b/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/types.go deleted file mode 100644 index 847f1b14..00000000 --- a/vendor/github.com/go-telegram-bot-api/telegram-bot-api/v5/types.go +++ /dev/null @@ -1,3225 +0,0 @@ -package tgbotapi - -import ( - "encoding/json" - "errors" - "fmt" - "net/url" - "strings" - "time" -) - -// APIResponse is a response from the Telegram API with the result -// stored raw. -type APIResponse struct { - Ok bool `json:"ok"` - Result json.RawMessage `json:"result,omitempty"` - ErrorCode int `json:"error_code,omitempty"` - Description string `json:"description,omitempty"` - Parameters *ResponseParameters `json:"parameters,omitempty"` -} - -// Error is an error containing extra information returned by the Telegram API. -type Error struct { - Code int - Message string - ResponseParameters -} - -// Error message string. -func (e Error) Error() string { - return e.Message -} - -// Update is an update response, from GetUpdates. -type Update struct { - // UpdateID is the update's unique identifier. - // Update identifiers start from a certain positive number and increase - // sequentially. - // This ID becomes especially handy if you're using Webhooks, - // since it allows you to ignore repeated updates or to restore - // the correct update sequence, should they get out of order. - // If there are no new updates for at least a week, then identifier - // of the next update will be chosen randomly instead of sequentially. - UpdateID int `json:"update_id"` - // Message new incoming message of any kind — text, photo, sticker, etc. - // - // optional - Message *Message `json:"message,omitempty"` - // EditedMessage new version of a message that is known to the bot and was - // edited - // - // optional - EditedMessage *Message `json:"edited_message,omitempty"` - // ChannelPost new version of a message that is known to the bot and was - // edited - // - // optional - ChannelPost *Message `json:"channel_post,omitempty"` - // EditedChannelPost new incoming channel post of any kind — text, photo, - // sticker, etc. - // - // optional - EditedChannelPost *Message `json:"edited_channel_post,omitempty"` - // InlineQuery new incoming inline query - // - // optional - InlineQuery *InlineQuery `json:"inline_query,omitempty"` - // ChosenInlineResult is the result of an inline query - // that was chosen by a user and sent to their chat partner. - // Please see our documentation on the feedback collecting - // for details on how to enable these updates for your bot. - // - // optional - ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result,omitempty"` - // CallbackQuery new incoming callback query - // - // optional - CallbackQuery *CallbackQuery `json:"callback_query,omitempty"` - // ShippingQuery new incoming shipping query. Only for invoices with - // flexible price - // - // optional - ShippingQuery *ShippingQuery `json:"shipping_query,omitempty"` - // PreCheckoutQuery new incoming pre-checkout query. Contains full - // information about checkout - // - // optional - PreCheckoutQuery *PreCheckoutQuery `json:"pre_checkout_query,omitempty"` - // Pool new poll state. Bots receive only updates about stopped polls and - // polls, which are sent by the bot - // - // optional - Poll *Poll `json:"poll,omitempty"` - // PollAnswer user changed their answer in a non-anonymous poll. Bots - // receive new votes only in polls that were sent by the bot itself. - // - // optional - PollAnswer *PollAnswer `json:"poll_answer,omitempty"` - // MyChatMember is the bot's chat member status was updated in a chat. For - // private chats, this update is received only when the bot is blocked or - // unblocked by the user. - // - // optional - MyChatMember *ChatMemberUpdated `json:"my_chat_member"` - // ChatMember is a chat member's status was updated in a chat. The bot must - // be an administrator in the chat and must explicitly specify "chat_member" - // in the list of allowed_updates to receive these updates. - // - // optional - ChatMember *ChatMemberUpdated `json:"chat_member"` - // ChatJoinRequest is a request to join the chat has been sent. The bot must - // have the can_invite_users administrator right in the chat to receive - // these updates. - // - // optional - ChatJoinRequest *ChatJoinRequest `json:"chat_join_request"` -} - -// SentFrom returns the user who sent an update. Can be nil, if Telegram did not provide information -// about the user in the update object. -func (u *Update) SentFrom() *User { - switch { - case u.Message != nil: - return u.Message.From - case u.EditedMessage != nil: - return u.EditedMessage.From - case u.InlineQuery != nil: - return u.InlineQuery.From - case u.ChosenInlineResult != nil: - return u.ChosenInlineResult.From - case u.CallbackQuery != nil: - return u.CallbackQuery.From - case u.ShippingQuery != nil: - return u.ShippingQuery.From - case u.PreCheckoutQuery != nil: - return u.PreCheckoutQuery.From - default: - return nil - } -} - -// CallbackData returns the callback query data, if it exists. -func (u *Update) CallbackData() string { - if u.CallbackQuery != nil { - return u.CallbackQuery.Data - } - return "" -} - -// FromChat returns the chat where an update occurred. -func (u *Update) FromChat() *Chat { - switch { - case u.Message != nil: - return u.Message.Chat - case u.EditedMessage != nil: - return u.EditedMessage.Chat - case u.ChannelPost != nil: - return u.ChannelPost.Chat - case u.EditedChannelPost != nil: - return u.EditedChannelPost.Chat - case u.CallbackQuery != nil: - return u.CallbackQuery.Message.Chat - default: - return nil - } -} - -// UpdatesChannel is the channel for getting updates. -type UpdatesChannel <-chan Update - -// Clear discards all unprocessed incoming updates. -func (ch UpdatesChannel) Clear() { - for len(ch) != 0 { - <-ch - } -} - -// User represents a Telegram user or bot. -type User struct { - // ID is a unique identifier for this user or bot - ID int64 `json:"id"` - // IsBot true, if this user is a bot - // - // optional - IsBot bool `json:"is_bot,omitempty"` - // FirstName user's or bot's first name - FirstName string `json:"first_name"` - // LastName user's or bot's last name - // - // optional - LastName string `json:"last_name,omitempty"` - // UserName user's or bot's username - // - // optional - UserName string `json:"username,omitempty"` - // LanguageCode IETF language tag of the user's language - // more info: https://en.wikipedia.org/wiki/IETF_language_tag - // - // optional - LanguageCode string `json:"language_code,omitempty"` - // CanJoinGroups is true, if the bot can be invited to groups. - // Returned only in getMe. - // - // optional - CanJoinGroups bool `json:"can_join_groups,omitempty"` - // CanReadAllGroupMessages is true, if privacy mode is disabled for the bot. - // Returned only in getMe. - // - // optional - CanReadAllGroupMessages bool `json:"can_read_all_group_messages,omitempty"` - // SupportsInlineQueries is true, if the bot supports inline queries. - // Returned only in getMe. - // - // optional - SupportsInlineQueries bool `json:"supports_inline_queries,omitempty"` -} - -// String displays a simple text version of a user. -// -// It is normally a user's username, but falls back to a first/last -// name as available. -func (u *User) String() string { - if u == nil { - return "" - } - if u.UserName != "" { - return u.UserName - } - - name := u.FirstName - if u.LastName != "" { - name += " " + u.LastName - } - - return name -} - -// Chat represents a chat. -type Chat struct { - // ID is a unique identifier for this chat - ID int64 `json:"id"` - // Type of chat, can be either “private”, “group”, “supergroup” or “channel” - Type string `json:"type"` - // Title for supergroups, channels and group chats - // - // optional - Title string `json:"title,omitempty"` - // UserName for private chats, supergroups and channels if available - // - // optional - UserName string `json:"username,omitempty"` - // FirstName of the other party in a private chat - // - // optional - FirstName string `json:"first_name,omitempty"` - // LastName of the other party in a private chat - // - // optional - LastName string `json:"last_name,omitempty"` - // Photo is a chat photo - Photo *ChatPhoto `json:"photo"` - // Bio is the bio of the other party in a private chat. Returned only in - // getChat - // - // optional - Bio string `json:"bio,omitempty"` - // HasPrivateForwards is true if privacy settings of the other party in the - // private chat allows to use tg://user?id= links only in chats - // with the user. Returned only in getChat. - // - // optional - HasPrivateForwards bool `json:"has_private_forwards,omitempty"` - // Description for groups, supergroups and channel chats - // - // optional - Description string `json:"description,omitempty"` - // InviteLink is a chat invite link, for groups, supergroups and channel chats. - // Each administrator in a chat generates their own invite links, - // so the bot must first generate the link using exportChatInviteLink - // - // optional - InviteLink string `json:"invite_link,omitempty"` - // PinnedMessage is the pinned message, for groups, supergroups and channels - // - // optional - PinnedMessage *Message `json:"pinned_message,omitempty"` - // Permissions are default chat member permissions, for groups and - // supergroups. Returned only in getChat. - // - // optional - Permissions *ChatPermissions `json:"permissions,omitempty"` - // SlowModeDelay is for supergroups, the minimum allowed delay between - // consecutive messages sent by each unpriviledged user. Returned only in - // getChat. - // - // optional - SlowModeDelay int `json:"slow_mode_delay,omitempty"` - // MessageAutoDeleteTime is the time after which all messages sent to the - // chat will be automatically deleted; in seconds. Returned only in getChat. - // - // optional - MessageAutoDeleteTime int `json:"message_auto_delete_time,omitempty"` - // HasProtectedContent is true if messages from the chat can't be forwarded - // to other chats. Returned only in getChat. - // - // optional - HasProtectedContent bool `json:"has_protected_content,omitempty"` - // StickerSetName is for supergroups, name of group sticker set.Returned - // only in getChat. - // - // optional - StickerSetName string `json:"sticker_set_name,omitempty"` - // CanSetStickerSet is true, if the bot can change the group sticker set. - // Returned only in getChat. - // - // optional - CanSetStickerSet bool `json:"can_set_sticker_set,omitempty"` - // LinkedChatID is a unique identifier for the linked chat, i.e. the - // discussion group identifier for a channel and vice versa; for supergroups - // and channel chats. - // - // optional - LinkedChatID int64 `json:"linked_chat_id,omitempty"` - // Location is for supergroups, the location to which the supergroup is - // connected. Returned only in getChat. - // - // optional - Location *ChatLocation `json:"location"` -} - -// IsPrivate returns if the Chat is a private conversation. -func (c Chat) IsPrivate() bool { - return c.Type == "private" -} - -// IsGroup returns if the Chat is a group. -func (c Chat) IsGroup() bool { - return c.Type == "group" -} - -// IsSuperGroup returns if the Chat is a supergroup. -func (c Chat) IsSuperGroup() bool { - return c.Type == "supergroup" -} - -// IsChannel returns if the Chat is a channel. -func (c Chat) IsChannel() bool { - return c.Type == "channel" -} - -// ChatConfig returns a ChatConfig struct for chat related methods. -func (c Chat) ChatConfig() ChatConfig { - return ChatConfig{ChatID: c.ID} -} - -// Message represents a message. -type Message struct { - // MessageID is a unique message identifier inside this chat - MessageID int `json:"message_id"` - // From is a sender, empty for messages sent to channels; - // - // optional - From *User `json:"from,omitempty"` - // SenderChat is the sender of the message, sent on behalf of a chat. The - // channel itself for channel messages. The supergroup itself for messages - // from anonymous group administrators. The linked channel for messages - // automatically forwarded to the discussion group - // - // optional - SenderChat *Chat `json:"sender_chat,omitempty"` - // Date of the message was sent in Unix time - Date int `json:"date"` - // Chat is the conversation the message belongs to - Chat *Chat `json:"chat"` - // ForwardFrom for forwarded messages, sender of the original message; - // - // optional - ForwardFrom *User `json:"forward_from,omitempty"` - // ForwardFromChat for messages forwarded from channels, - // information about the original channel; - // - // optional - ForwardFromChat *Chat `json:"forward_from_chat,omitempty"` - // ForwardFromMessageID for messages forwarded from channels, - // identifier of the original message in the channel; - // - // optional - ForwardFromMessageID int `json:"forward_from_message_id,omitempty"` - // ForwardSignature for messages forwarded from channels, signature of the - // post author if present - // - // optional - ForwardSignature string `json:"forward_signature,omitempty"` - // ForwardSenderName is the sender's name for messages forwarded from users - // who disallow adding a link to their account in forwarded messages - // - // optional - ForwardSenderName string `json:"forward_sender_name,omitempty"` - // ForwardDate for forwarded messages, date the original message was sent in Unix time; - // - // optional - ForwardDate int `json:"forward_date,omitempty"` - // IsAutomaticForward is true if the message is a channel post that was - // automatically forwarded to the connected discussion group. - // - // optional - IsAutomaticForward bool `json:"is_automatic_forward,omitempty"` - // ReplyToMessage for replies, the original message. - // Note that the Message object in this field will not contain further ReplyToMessage fields - // even if it itself is a reply; - // - // optional - ReplyToMessage *Message `json:"reply_to_message,omitempty"` - // ViaBot through which the message was sent; - // - // optional - ViaBot *User `json:"via_bot,omitempty"` - // EditDate of the message was last edited in Unix time; - // - // optional - EditDate int `json:"edit_date,omitempty"` - // HasProtectedContent is true if the message can't be forwarded. - // - // optional - HasProtectedContent bool `json:"has_protected_content,omitempty"` - // MediaGroupID is the unique identifier of a media message group this message belongs to; - // - // optional - MediaGroupID string `json:"media_group_id,omitempty"` - // AuthorSignature is the signature of the post author for messages in channels; - // - // optional - AuthorSignature string `json:"author_signature,omitempty"` - // Text is for text messages, the actual UTF-8 text of the message, 0-4096 characters; - // - // optional - Text string `json:"text,omitempty"` - // Entities are for text messages, special entities like usernames, - // URLs, bot commands, etc. that appear in the text; - // - // optional - Entities []MessageEntity `json:"entities,omitempty"` - // Animation message is an animation, information about the animation. - // For backward compatibility, when this field is set, the document field will also be set; - // - // optional - Animation *Animation `json:"animation,omitempty"` - // Audio message is an audio file, information about the file; - // - // optional - Audio *Audio `json:"audio,omitempty"` - // Document message is a general file, information about the file; - // - // optional - Document *Document `json:"document,omitempty"` - // Photo message is a photo, available sizes of the photo; - // - // optional - Photo []PhotoSize `json:"photo,omitempty"` - // Sticker message is a sticker, information about the sticker; - // - // optional - Sticker *Sticker `json:"sticker,omitempty"` - // Video message is a video, information about the video; - // - // optional - Video *Video `json:"video,omitempty"` - // VideoNote message is a video note, information about the video message; - // - // optional - VideoNote *VideoNote `json:"video_note,omitempty"` - // Voice message is a voice message, information about the file; - // - // optional - Voice *Voice `json:"voice,omitempty"` - // Caption for the animation, audio, document, photo, video or voice, 0-1024 characters; - // - // optional - Caption string `json:"caption,omitempty"` - // CaptionEntities; - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // Contact message is a shared contact, information about the contact; - // - // optional - Contact *Contact `json:"contact,omitempty"` - // Dice is a dice with random value; - // - // optional - Dice *Dice `json:"dice,omitempty"` - // Game message is a game, information about the game; - // - // optional - Game *Game `json:"game,omitempty"` - // Poll is a native poll, information about the poll; - // - // optional - Poll *Poll `json:"poll,omitempty"` - // Venue message is a venue, information about the venue. - // For backward compatibility, when this field is set, the location field - // will also be set; - // - // optional - Venue *Venue `json:"venue,omitempty"` - // Location message is a shared location, information about the location; - // - // optional - Location *Location `json:"location,omitempty"` - // NewChatMembers that were added to the group or supergroup - // and information about them (the bot itself may be one of these members); - // - // optional - NewChatMembers []User `json:"new_chat_members,omitempty"` - // LeftChatMember is a member was removed from the group, - // information about them (this member may be the bot itself); - // - // optional - LeftChatMember *User `json:"left_chat_member,omitempty"` - // NewChatTitle is a chat title was changed to this value; - // - // optional - NewChatTitle string `json:"new_chat_title,omitempty"` - // NewChatPhoto is a chat photo was change to this value; - // - // optional - NewChatPhoto []PhotoSize `json:"new_chat_photo,omitempty"` - // DeleteChatPhoto is a service message: the chat photo was deleted; - // - // optional - DeleteChatPhoto bool `json:"delete_chat_photo,omitempty"` - // GroupChatCreated is a service message: the group has been created; - // - // optional - GroupChatCreated bool `json:"group_chat_created,omitempty"` - // SuperGroupChatCreated is a service message: the supergroup has been created. - // This field can't be received in a message coming through updates, - // because bot can't be a member of a supergroup when it is created. - // It can only be found in ReplyToMessage if someone replies to a very first message - // in a directly created supergroup; - // - // optional - SuperGroupChatCreated bool `json:"supergroup_chat_created,omitempty"` - // ChannelChatCreated is a service message: the channel has been created. - // This field can't be received in a message coming through updates, - // because bot can't be a member of a channel when it is created. - // It can only be found in ReplyToMessage - // if someone replies to a very first message in a channel; - // - // optional - ChannelChatCreated bool `json:"channel_chat_created,omitempty"` - // MessageAutoDeleteTimerChanged is a service message: auto-delete timer - // settings changed in the chat. - // - // optional - MessageAutoDeleteTimerChanged *MessageAutoDeleteTimerChanged `json:"message_auto_delete_timer_changed"` - // MigrateToChatID is the group has been migrated to a supergroup with the specified identifier. - // This number may be greater than 32 bits and some programming languages - // may have difficulty/silent defects in interpreting it. - // But it is smaller than 52 bits, so a signed 64-bit integer - // or double-precision float type are safe for storing this identifier; - // - // optional - MigrateToChatID int64 `json:"migrate_to_chat_id,omitempty"` - // MigrateFromChatID is the supergroup has been migrated from a group with the specified identifier. - // This number may be greater than 32 bits and some programming languages - // may have difficulty/silent defects in interpreting it. - // But it is smaller than 52 bits, so a signed 64-bit integer - // or double-precision float type are safe for storing this identifier; - // - // optional - MigrateFromChatID int64 `json:"migrate_from_chat_id,omitempty"` - // PinnedMessage is a specified message was pinned. - // Note that the Message object in this field will not contain further ReplyToMessage - // fields even if it is itself a reply; - // - // optional - PinnedMessage *Message `json:"pinned_message,omitempty"` - // Invoice message is an invoice for a payment; - // - // optional - Invoice *Invoice `json:"invoice,omitempty"` - // SuccessfulPayment message is a service message about a successful payment, - // information about the payment; - // - // optional - SuccessfulPayment *SuccessfulPayment `json:"successful_payment,omitempty"` - // ConnectedWebsite is the domain name of the website on which the user has - // logged in; - // - // optional - ConnectedWebsite string `json:"connected_website,omitempty"` - // PassportData is a Telegram Passport data; - // - // optional - PassportData *PassportData `json:"passport_data,omitempty"` - // ProximityAlertTriggered is a service message. A user in the chat - // triggered another user's proximity alert while sharing Live Location - // - // optional - ProximityAlertTriggered *ProximityAlertTriggered `json:"proximity_alert_triggered"` - // VoiceChatScheduled is a service message: voice chat scheduled. - // - // optional - VoiceChatScheduled *VoiceChatScheduled `json:"voice_chat_scheduled"` - // VoiceChatStarted is a service message: voice chat started. - // - // optional - VoiceChatStarted *VoiceChatStarted `json:"voice_chat_started"` - // VoiceChatEnded is a service message: voice chat ended. - // - // optional - VoiceChatEnded *VoiceChatEnded `json:"voice_chat_ended"` - // VoiceChatParticipantsInvited is a service message: new participants - // invited to a voice chat. - // - // optional - VoiceChatParticipantsInvited *VoiceChatParticipantsInvited `json:"voice_chat_participants_invited"` - // ReplyMarkup is the Inline keyboard attached to the message. - // login_url buttons are represented as ordinary url buttons. - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` -} - -// Time converts the message timestamp into a Time. -func (m *Message) Time() time.Time { - return time.Unix(int64(m.Date), 0) -} - -// IsCommand returns true if message starts with a "bot_command" entity. -func (m *Message) IsCommand() bool { - if m.Entities == nil || len(m.Entities) == 0 { - return false - } - - entity := m.Entities[0] - return entity.Offset == 0 && entity.IsCommand() -} - -// Command checks if the message was a command and if it was, returns the -// command. If the Message was not a command, it returns an empty string. -// -// If the command contains the at name syntax, it is removed. Use -// CommandWithAt() if you do not want that. -func (m *Message) Command() string { - command := m.CommandWithAt() - - if i := strings.Index(command, "@"); i != -1 { - command = command[:i] - } - - return command -} - -// CommandWithAt checks if the message was a command and if it was, returns the -// command. If the Message was not a command, it returns an empty string. -// -// If the command contains the at name syntax, it is not removed. Use Command() -// if you want that. -func (m *Message) CommandWithAt() string { - if !m.IsCommand() { - return "" - } - - // IsCommand() checks that the message begins with a bot_command entity - entity := m.Entities[0] - return m.Text[1:entity.Length] -} - -// CommandArguments checks if the message was a command and if it was, -// returns all text after the command name. If the Message was not a -// command, it returns an empty string. -// -// Note: The first character after the command name is omitted: -// - "/foo bar baz" yields "bar baz", not " bar baz" -// - "/foo-bar baz" yields "bar baz", too -// Even though the latter is not a command conforming to the spec, the API -// marks "/foo" as command entity. -func (m *Message) CommandArguments() string { - if !m.IsCommand() { - return "" - } - - // IsCommand() checks that the message begins with a bot_command entity - entity := m.Entities[0] - - if len(m.Text) == entity.Length { - return "" // The command makes up the whole message - } - - return m.Text[entity.Length+1:] -} - -// MessageID represents a unique message identifier. -type MessageID struct { - MessageID int `json:"message_id"` -} - -// MessageEntity represents one special entity in a text message. -type MessageEntity struct { - // Type of the entity. - // Can be: - // “mention” (@username), - // “hashtag” (#hashtag), - // “cashtag” ($USD), - // “bot_command” (/start@jobs_bot), - // “url” (https://telegram.org), - // “email” (do-not-reply@telegram.org), - // “phone_number” (+1-212-555-0123), - // “bold” (bold text), - // “italic” (italic text), - // “underline” (underlined text), - // “strikethrough” (strikethrough text), - // “code” (monowidth string), - // “pre” (monowidth block), - // “text_link” (for clickable text URLs), - // “text_mention” (for users without usernames) - Type string `json:"type"` - // Offset in UTF-16 code units to the start of the entity - Offset int `json:"offset"` - // Length - Length int `json:"length"` - // URL for “text_link” only, url that will be opened after user taps on the text - // - // optional - URL string `json:"url,omitempty"` - // User for “text_mention” only, the mentioned user - // - // optional - User *User `json:"user,omitempty"` - // Language for “pre” only, the programming language of the entity text - // - // optional - Language string `json:"language,omitempty"` -} - -// ParseURL attempts to parse a URL contained within a MessageEntity. -func (e MessageEntity) ParseURL() (*url.URL, error) { - if e.URL == "" { - return nil, errors.New(ErrBadURL) - } - - return url.Parse(e.URL) -} - -// IsMention returns true if the type of the message entity is "mention" (@username). -func (e MessageEntity) IsMention() bool { - return e.Type == "mention" -} - -// IsHashtag returns true if the type of the message entity is "hashtag". -func (e MessageEntity) IsHashtag() bool { - return e.Type == "hashtag" -} - -// IsCommand returns true if the type of the message entity is "bot_command". -func (e MessageEntity) IsCommand() bool { - return e.Type == "bot_command" -} - -// IsURL returns true if the type of the message entity is "url". -func (e MessageEntity) IsURL() bool { - return e.Type == "url" -} - -// IsEmail returns true if the type of the message entity is "email". -func (e MessageEntity) IsEmail() bool { - return e.Type == "email" -} - -// IsBold returns true if the type of the message entity is "bold" (bold text). -func (e MessageEntity) IsBold() bool { - return e.Type == "bold" -} - -// IsItalic returns true if the type of the message entity is "italic" (italic text). -func (e MessageEntity) IsItalic() bool { - return e.Type == "italic" -} - -// IsCode returns true if the type of the message entity is "code" (monowidth string). -func (e MessageEntity) IsCode() bool { - return e.Type == "code" -} - -// IsPre returns true if the type of the message entity is "pre" (monowidth block). -func (e MessageEntity) IsPre() bool { - return e.Type == "pre" -} - -// IsTextLink returns true if the type of the message entity is "text_link" (clickable text URL). -func (e MessageEntity) IsTextLink() bool { - return e.Type == "text_link" -} - -// PhotoSize represents one size of a photo or a file / sticker thumbnail. -type PhotoSize struct { - // FileID identifier for this file, which can be used to download or reuse - // the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Width photo width - Width int `json:"width"` - // Height photo height - Height int `json:"height"` - // FileSize file size - // - // optional - FileSize int `json:"file_size,omitempty"` -} - -// Animation represents an animation file. -type Animation struct { - // FileID is the identifier for this file, which can be used to download or reuse - // the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Width video width as defined by sender - Width int `json:"width"` - // Height video height as defined by sender - Height int `json:"height"` - // Duration of the video in seconds as defined by sender - Duration int `json:"duration"` - // Thumbnail animation thumbnail as defined by sender - // - // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` - // FileName original animation filename as defined by sender - // - // optional - FileName string `json:"file_name,omitempty"` - // MimeType of the file as defined by sender - // - // optional - MimeType string `json:"mime_type,omitempty"` - // FileSize file size - // - // optional - FileSize int `json:"file_size,omitempty"` -} - -// Audio represents an audio file to be treated as music by the Telegram clients. -type Audio struct { - // FileID is an identifier for this file, which can be used to download or - // reuse the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Duration of the audio in seconds as defined by sender - Duration int `json:"duration"` - // Performer of the audio as defined by sender or by audio tags - // - // optional - Performer string `json:"performer,omitempty"` - // Title of the audio as defined by sender or by audio tags - // - // optional - Title string `json:"title,omitempty"` - // FileName is the original filename as defined by sender - // - // optional - FileName string `json:"file_name,omitempty"` - // MimeType of the file as defined by sender - // - // optional - MimeType string `json:"mime_type,omitempty"` - // FileSize file size - // - // optional - FileSize int `json:"file_size,omitempty"` - // Thumbnail is the album cover to which the music file belongs - // - // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` -} - -// Document represents a general file. -type Document struct { - // FileID is an identifier for this file, which can be used to download or - // reuse the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Thumbnail document thumbnail as defined by sender - // - // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` - // FileName original filename as defined by sender - // - // optional - FileName string `json:"file_name,omitempty"` - // MimeType of the file as defined by sender - // - // optional - MimeType string `json:"mime_type,omitempty"` - // FileSize file size - // - // optional - FileSize int `json:"file_size,omitempty"` -} - -// Video represents a video file. -type Video struct { - // FileID identifier for this file, which can be used to download or reuse - // the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Width video width as defined by sender - Width int `json:"width"` - // Height video height as defined by sender - Height int `json:"height"` - // Duration of the video in seconds as defined by sender - Duration int `json:"duration"` - // Thumbnail video thumbnail - // - // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` - // FileName is the original filename as defined by sender - // - // optional - FileName string `json:"file_name,omitempty"` - // MimeType of a file as defined by sender - // - // optional - MimeType string `json:"mime_type,omitempty"` - // FileSize file size - // - // optional - FileSize int `json:"file_size,omitempty"` -} - -// VideoNote object represents a video message. -type VideoNote struct { - // FileID identifier for this file, which can be used to download or reuse the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Length video width and height (diameter of the video message) as defined by sender - Length int `json:"length"` - // Duration of the video in seconds as defined by sender - Duration int `json:"duration"` - // Thumbnail video thumbnail - // - // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` - // FileSize file size - // - // optional - FileSize int `json:"file_size,omitempty"` -} - -// Voice represents a voice note. -type Voice struct { - // FileID identifier for this file, which can be used to download or reuse the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Duration of the audio in seconds as defined by sender - Duration int `json:"duration"` - // MimeType of the file as defined by sender - // - // optional - MimeType string `json:"mime_type,omitempty"` - // FileSize file size - // - // optional - FileSize int `json:"file_size,omitempty"` -} - -// Contact represents a phone contact. -// -// Note that LastName and UserID may be empty. -type Contact struct { - // PhoneNumber contact's phone number - PhoneNumber string `json:"phone_number"` - // FirstName contact's first name - FirstName string `json:"first_name"` - // LastName contact's last name - // - // optional - LastName string `json:"last_name,omitempty"` - // UserID contact's user identifier in Telegram - // - // optional - UserID int64 `json:"user_id,omitempty"` - // VCard is additional data about the contact in the form of a vCard. - // - // optional - VCard string `json:"vcard,omitempty"` -} - -// Dice represents an animated emoji that displays a random value. -type Dice struct { - // Emoji on which the dice throw animation is based - Emoji string `json:"emoji"` - // Value of the dice - Value int `json:"value"` -} - -// PollOption contains information about one answer option in a poll. -type PollOption struct { - // Text is the option text, 1-100 characters - Text string `json:"text"` - // VoterCount is the number of users that voted for this option - VoterCount int `json:"voter_count"` -} - -// PollAnswer represents an answer of a user in a non-anonymous poll. -type PollAnswer struct { - // PollID is the unique poll identifier - PollID string `json:"poll_id"` - // User who changed the answer to the poll - User User `json:"user"` - // OptionIDs is the 0-based identifiers of poll options chosen by the user. - // May be empty if user retracted vote. - OptionIDs []int `json:"option_ids"` -} - -// Poll contains information about a poll. -type Poll struct { - // ID is the unique poll identifier - ID string `json:"id"` - // Question is the poll question, 1-255 characters - Question string `json:"question"` - // Options is the list of poll options - Options []PollOption `json:"options"` - // TotalVoterCount is the total numbers of users who voted in the poll - TotalVoterCount int `json:"total_voter_count"` - // IsClosed is if the poll is closed - IsClosed bool `json:"is_closed"` - // IsAnonymous is if the poll is anonymous - IsAnonymous bool `json:"is_anonymous"` - // Type is the poll type, currently can be "regular" or "quiz" - Type string `json:"type"` - // AllowsMultipleAnswers is true, if the poll allows multiple answers - AllowsMultipleAnswers bool `json:"allows_multiple_answers"` - // CorrectOptionID is the 0-based identifier of the correct answer option. - // Available only for polls in quiz mode, which are closed, or was sent (not - // forwarded) by the bot or to the private chat with the bot. - // - // optional - CorrectOptionID int `json:"correct_option_id,omitempty"` - // Explanation is text that is shown when a user chooses an incorrect answer - // or taps on the lamp icon in a quiz-style poll, 0-200 characters - // - // optional - Explanation string `json:"explanation,omitempty"` - // ExplanationEntities are special entities like usernames, URLs, bot - // commands, etc. that appear in the explanation - // - // optional - ExplanationEntities []MessageEntity `json:"explanation_entities,omitempty"` - // OpenPeriod is the amount of time in seconds the poll will be active - // after creation - // - // optional - OpenPeriod int `json:"open_period,omitempty"` - // CloseDate is the point in time (unix timestamp) when the poll will be - // automatically closed - // - // optional - CloseDate int `json:"close_date,omitempty"` -} - -// Location represents a point on the map. -type Location struct { - // Longitude as defined by sender - Longitude float64 `json:"longitude"` - // Latitude as defined by sender - Latitude float64 `json:"latitude"` - // HorizontalAccuracy is the radius of uncertainty for the location, - // measured in meters; 0-1500 - // - // optional - HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"` - // LivePeriod is time relative to the message sending date, during which the - // location can be updated, in seconds. For active live locations only. - // - // optional - LivePeriod int `json:"live_period,omitempty"` - // Heading is the direction in which user is moving, in degrees; 1-360. For - // active live locations only. - // - // optional - Heading int `json:"heading,omitempty"` - // ProximityAlertRadius is the maximum distance for proximity alerts about - // approaching another chat member, in meters. For sent live locations only. - // - // optional - ProximityAlertRadius int `json:"proximity_alert_radius,omitempty"` -} - -// Venue represents a venue. -type Venue struct { - // Location is the venue location - Location Location `json:"location"` - // Title is the name of the venue - Title string `json:"title"` - // Address of the venue - Address string `json:"address"` - // FoursquareID is the foursquare identifier of the venue - // - // optional - FoursquareID string `json:"foursquare_id,omitempty"` - // FoursquareType is the foursquare type of the venue - // - // optional - FoursquareType string `json:"foursquare_type,omitempty"` - // GooglePlaceID is the Google Places identifier of the venue - // - // optional - GooglePlaceID string `json:"google_place_id,omitempty"` - // GooglePlaceType is the Google Places type of the venue - // - // optional - GooglePlaceType string `json:"google_place_type,omitempty"` -} - -// ProximityAlertTriggered represents a service message sent when a user in the -// chat triggers a proximity alert sent by another user. -type ProximityAlertTriggered struct { - // Traveler is the user that triggered the alert - Traveler User `json:"traveler"` - // Watcher is the user that set the alert - Watcher User `json:"watcher"` - // Distance is the distance between the users - Distance int `json:"distance"` -} - -// MessageAutoDeleteTimerChanged represents a service message about a change in -// auto-delete timer settings. -type MessageAutoDeleteTimerChanged struct { - // New auto-delete time for messages in the chat. - MessageAutoDeleteTime int `json:"message_auto_delete_time"` -} - -// VoiceChatScheduled represents a service message about a voice chat scheduled -// in the chat. -type VoiceChatScheduled struct { - // Point in time (Unix timestamp) when the voice chat is supposed to be - // started by a chat administrator - StartDate int `json:"start_date"` -} - -// Time converts the scheduled start date into a Time. -func (m *VoiceChatScheduled) Time() time.Time { - return time.Unix(int64(m.StartDate), 0) -} - -// VoiceChatStarted represents a service message about a voice chat started in -// the chat. -type VoiceChatStarted struct{} - -// VoiceChatEnded represents a service message about a voice chat ended in the -// chat. -type VoiceChatEnded struct { - // Voice chat duration; in seconds. - Duration int `json:"duration"` -} - -// VoiceChatParticipantsInvited represents a service message about new members -// invited to a voice chat. -type VoiceChatParticipantsInvited struct { - // New members that were invited to the voice chat. - // - // optional - Users []User `json:"users"` -} - -// UserProfilePhotos contains a set of user profile photos. -type UserProfilePhotos struct { - // TotalCount total number of profile pictures the target user has - TotalCount int `json:"total_count"` - // Photos requested profile pictures (in up to 4 sizes each) - Photos [][]PhotoSize `json:"photos"` -} - -// File contains information about a file to download from Telegram. -type File struct { - // FileID identifier for this file, which can be used to download or reuse - // the file - FileID string `json:"file_id"` - // FileUniqueID is the unique identifier for this file, which is supposed to - // be the same over time and for different bots. Can't be used to download - // or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // FileSize file size, if known - // - // optional - FileSize int `json:"file_size,omitempty"` - // FilePath file path - // - // optional - FilePath string `json:"file_path,omitempty"` -} - -// Link returns a full path to the download URL for a File. -// -// It requires the Bot token to create the link. -func (f *File) Link(token string) string { - return fmt.Sprintf(FileEndpoint, token, f.FilePath) -} - -// ReplyKeyboardMarkup represents a custom keyboard with reply options. -type ReplyKeyboardMarkup struct { - // Keyboard is an array of button rows, each represented by an Array of KeyboardButton objects - Keyboard [][]KeyboardButton `json:"keyboard"` - // ResizeKeyboard requests clients to resize the keyboard vertically for optimal fit - // (e.g., make the keyboard smaller if there are just two rows of buttons). - // Defaults to false, in which case the custom keyboard - // is always of the same height as the app's standard keyboard. - // - // optional - ResizeKeyboard bool `json:"resize_keyboard,omitempty"` - // OneTimeKeyboard requests clients to hide the keyboard as soon as it's been used. - // The keyboard will still be available, but clients will automatically display - // the usual letter-keyboard in the chat – the user can press a special button - // in the input field to see the custom keyboard again. - // Defaults to false. - // - // optional - OneTimeKeyboard bool `json:"one_time_keyboard,omitempty"` - // InputFieldPlaceholder is the placeholder to be shown in the input field when - // the keyboard is active; 1-64 characters. - // - // optional - InputFieldPlaceholder string `json:"input_field_placeholder,omitempty"` - // Selective use this parameter if you want to show the keyboard to specific users only. - // Targets: - // 1) users that are @mentioned in the text of the Message object; - // 2) if the bot's message is a reply (has Message.ReplyToMessage not nil), sender of the original message. - // - // Example: A user requests to change the bot's language, - // bot replies to the request with a keyboard to select the new language. - // Other users in the group don't see the keyboard. - // - // optional - Selective bool `json:"selective,omitempty"` -} - -// KeyboardButton represents one button of the reply keyboard. For simple text -// buttons String can be used instead of this object to specify text of the -// button. Optional fields request_contact, request_location, and request_poll -// are mutually exclusive. -type KeyboardButton struct { - // Text of the button. If none of the optional fields are used, - // it will be sent as a message when the button is pressed. - Text string `json:"text"` - // RequestContact if True, the user's phone number will be sent - // as a contact when the button is pressed. - // Available in private chats only. - // - // optional - RequestContact bool `json:"request_contact,omitempty"` - // RequestLocation if True, the user's current location will be sent when - // the button is pressed. - // Available in private chats only. - // - // optional - RequestLocation bool `json:"request_location,omitempty"` - // RequestPoll if True, the user will be asked to create a poll and send it - // to the bot when the button is pressed. Available in private chats only - // - // optional - RequestPoll *KeyboardButtonPollType `json:"request_poll,omitempty"` -} - -// KeyboardButtonPollType represents type of poll, which is allowed to -// be created and sent when the corresponding button is pressed. -type KeyboardButtonPollType struct { - // Type is if quiz is passed, the user will be allowed to create only polls - // in the quiz mode. If regular is passed, only regular polls will be - // allowed. Otherwise, the user will be allowed to create a poll of any type. - Type string `json:"type"` -} - -// ReplyKeyboardRemove Upon receiving a message with this object, Telegram -// clients will remove the current custom keyboard and display the default -// letter-keyboard. By default, custom keyboards are displayed until a new -// keyboard is sent by a bot. An exception is made for one-time keyboards -// that are hidden immediately after the user presses a button. -type ReplyKeyboardRemove struct { - // RemoveKeyboard requests clients to remove the custom keyboard - // (user will not be able to summon this keyboard; - // if you want to hide the keyboard from sight but keep it accessible, - // use one_time_keyboard in ReplyKeyboardMarkup). - RemoveKeyboard bool `json:"remove_keyboard"` - // Selective use this parameter if you want to remove the keyboard for specific users only. - // Targets: - // 1) users that are @mentioned in the text of the Message object; - // 2) if the bot's message is a reply (has Message.ReplyToMessage not nil), sender of the original message. - // - // Example: A user votes in a poll, bot returns confirmation message - // in reply to the vote and removes the keyboard for that user, - // while still showing the keyboard with poll options to users who haven't voted yet. - // - // optional - Selective bool `json:"selective,omitempty"` -} - -// InlineKeyboardMarkup represents an inline keyboard that appears right next to -// the message it belongs to. -type InlineKeyboardMarkup struct { - // InlineKeyboard array of button rows, each represented by an Array of - // InlineKeyboardButton objects - InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"` -} - -// InlineKeyboardButton represents one button of an inline keyboard. You must -// use exactly one of the optional fields. -// -// Note that some values are references as even an empty string -// will change behavior. -// -// CallbackGame, if set, MUST be first button in first row. -type InlineKeyboardButton struct { - // Text label text on the button - Text string `json:"text"` - // URL HTTP or tg:// url to be opened when button is pressed. - // - // optional - URL *string `json:"url,omitempty"` - // LoginURL is an HTTP URL used to automatically authorize the user. Can be - // used as a replacement for the Telegram Login Widget - // - // optional - LoginURL *LoginURL `json:"login_url,omitempty"` - // CallbackData data to be sent in a callback query to the bot when button is pressed, 1-64 bytes. - // - // optional - CallbackData *string `json:"callback_data,omitempty"` - // SwitchInlineQuery if set, pressing the button will prompt the user to select one of their chats, - // open that chat and insert the bot's username and the specified inline query in the input field. - // Can be empty, in which case just the bot's username will be inserted. - // - // This offers an easy way for users to start using your bot - // in inline mode when they are currently in a private chat with it. - // Especially useful when combined with switch_pm… actions – in this case - // the user will be automatically returned to the chat they switched from, - // skipping the chat selection screen. - // - // optional - SwitchInlineQuery *string `json:"switch_inline_query,omitempty"` - // SwitchInlineQueryCurrentChat if set, pressing the button will insert the bot's username - // and the specified inline query in the current chat's input field. - // Can be empty, in which case only the bot's username will be inserted. - // - // This offers a quick way for the user to open your bot in inline mode - // in the same chat – good for selecting something from multiple options. - // - // optional - SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` - // CallbackGame description of the game that will be launched when the user presses the button. - // - // optional - CallbackGame *CallbackGame `json:"callback_game,omitempty"` - // Pay specify True, to send a Pay button. - // - // NOTE: This type of button must always be the first button in the first row. - // - // optional - Pay bool `json:"pay,omitempty"` -} - -// LoginURL represents a parameter of the inline keyboard button used to -// automatically authorize a user. Serves as a great replacement for the -// Telegram Login Widget when the user is coming from Telegram. All the user -// needs to do is tap/click a button and confirm that they want to log in. -type LoginURL struct { - // URL is an HTTP URL to be opened with user authorization data added to the - // query string when the button is pressed. If the user refuses to provide - // authorization data, the original URL without information about the user - // will be opened. The data added is the same as described in Receiving - // authorization data. - // - // NOTE: You must always check the hash of the received data to verify the - // authentication and the integrity of the data as described in Checking - // authorization. - URL string `json:"url"` - // ForwardText is the new text of the button in forwarded messages - // - // optional - ForwardText string `json:"forward_text,omitempty"` - // BotUsername is the username of a bot, which will be used for user - // authorization. See Setting up a bot for more details. If not specified, - // the current bot's username will be assumed. The url's domain must be the - // same as the domain linked with the bot. See Linking your domain to the - // bot for more details. - // - // optional - BotUsername string `json:"bot_username,omitempty"` - // RequestWriteAccess if true requests permission for your bot to send - // messages to the user - // - // optional - RequestWriteAccess bool `json:"request_write_access,omitempty"` -} - -// CallbackQuery represents an incoming callback query from a callback button in -// an inline keyboard. If the button that originated the query was attached to a -// message sent by the bot, the field message will be present. If the button was -// attached to a message sent via the bot (in inline mode), the field -// inline_message_id will be present. Exactly one of the fields data or -// game_short_name will be present. -type CallbackQuery struct { - // ID unique identifier for this query - ID string `json:"id"` - // From sender - From *User `json:"from"` - // Message with the callback button that originated the query. - // Note that message content and message date will not be available if the - // message is too old. - // - // optional - Message *Message `json:"message,omitempty"` - // InlineMessageID identifier of the message sent via the bot in inline - // mode, that originated the query. - // - // optional - InlineMessageID string `json:"inline_message_id,omitempty"` - // ChatInstance global identifier, uniquely corresponding to the chat to - // which the message with the callback button was sent. Useful for high - // scores in games. - ChatInstance string `json:"chat_instance"` - // Data associated with the callback button. Be aware that - // a bad client can send arbitrary data in this field. - // - // optional - Data string `json:"data,omitempty"` - // GameShortName short name of a Game to be returned, serves as the unique identifier for the game. - // - // optional - GameShortName string `json:"game_short_name,omitempty"` -} - -// ForceReply when receiving a message with this object, Telegram clients will -// display a reply interface to the user (act as if the user has selected the -// bot's message and tapped 'Reply'). This can be extremely useful if you want -// to create user-friendly step-by-step interfaces without having to sacrifice -// privacy mode. -type ForceReply struct { - // ForceReply shows reply interface to the user, - // as if they manually selected the bot's message and tapped 'Reply'. - ForceReply bool `json:"force_reply"` - // InputFieldPlaceholder is the placeholder to be shown in the input field when - // the reply is active; 1-64 characters. - // - // optional - InputFieldPlaceholder string `json:"input_field_placeholder,omitempty"` - // Selective use this parameter if you want to force reply from specific users only. - // Targets: - // 1) users that are @mentioned in the text of the Message object; - // 2) if the bot's message is a reply (has Message.ReplyToMessage not nil), sender of the original message. - // - // optional - Selective bool `json:"selective,omitempty"` -} - -// ChatPhoto represents a chat photo. -type ChatPhoto struct { - // SmallFileID is a file identifier of small (160x160) chat photo. - // This file_id can be used only for photo download and - // only for as long as the photo is not changed. - SmallFileID string `json:"small_file_id"` - // SmallFileUniqueID is a unique file identifier of small (160x160) chat - // photo, which is supposed to be the same over time and for different bots. - // Can't be used to download or reuse the file. - SmallFileUniqueID string `json:"small_file_unique_id"` - // BigFileID is a file identifier of big (640x640) chat photo. - // This file_id can be used only for photo download and - // only for as long as the photo is not changed. - BigFileID string `json:"big_file_id"` - // BigFileUniqueID is a file identifier of big (640x640) chat photo, which - // is supposed to be the same over time and for different bots. Can't be - // used to download or reuse the file. - BigFileUniqueID string `json:"big_file_unique_id"` -} - -// ChatInviteLink represents an invite link for a chat. -type ChatInviteLink struct { - // InviteLink is the invite link. If the link was created by another chat - // administrator, then the second part of the link will be replaced with “…”. - InviteLink string `json:"invite_link"` - // Creator of the link. - Creator User `json:"creator"` - // CreatesJoinRequest is true if users joining the chat via the link need to - // be approved by chat administrators. - // - // optional - CreatesJoinRequest bool `json:"creates_join_request"` - // IsPrimary is true, if the link is primary. - IsPrimary bool `json:"is_primary"` - // IsRevoked is true, if the link is revoked. - IsRevoked bool `json:"is_revoked"` - // Name is the name of the invite link. - // - // optional - Name string `json:"name"` - // ExpireDate is the point in time (Unix timestamp) when the link will - // expire or has been expired. - // - // optional - ExpireDate int `json:"expire_date"` - // MemberLimit is the maximum number of users that can be members of the - // chat simultaneously after joining the chat via this invite link; 1-99999. - // - // optional - MemberLimit int `json:"member_limit"` - // PendingJoinRequestCount is the number of pending join requests created - // using this link. - // - // optional - PendingJoinRequestCount int `json:"pending_join_request_count"` -} - -// ChatMember contains information about one member of a chat. -type ChatMember struct { - // User information about the user - User *User `json:"user"` - // Status the member's status in the chat. - // Can be - // “creator”, - // “administrator”, - // “member”, - // “restricted”, - // “left” or - // “kicked” - Status string `json:"status"` - // CustomTitle owner and administrators only. Custom title for this user - // - // optional - CustomTitle string `json:"custom_title,omitempty"` - // IsAnonymous owner and administrators only. True, if the user's presence - // in the chat is hidden - // - // optional - IsAnonymous bool `json:"is_anonymous"` - // UntilDate restricted and kicked only. - // Date when restrictions will be lifted for this user; - // unix time. - // - // optional - UntilDate int64 `json:"until_date,omitempty"` - // CanBeEdited administrators only. - // True, if the bot is allowed to edit administrator privileges of that user. - // - // optional - CanBeEdited bool `json:"can_be_edited,omitempty"` - // CanManageChat administrators only. - // True, if the administrator can access the chat event log, chat - // statistics, message statistics in channels, see channel members, see - // anonymous administrators in supergroups and ignore slow mode. Implied by - // any other administrator privilege. - // - // optional - CanManageChat bool `json:"can_manage_chat"` - // CanPostMessages administrators only. - // True, if the administrator can post in the channel; - // channels only. - // - // optional - CanPostMessages bool `json:"can_post_messages,omitempty"` - // CanEditMessages administrators only. - // True, if the administrator can edit messages of other users and can pin messages; - // channels only. - // - // optional - CanEditMessages bool `json:"can_edit_messages,omitempty"` - // CanDeleteMessages administrators only. - // True, if the administrator can delete messages of other users. - // - // optional - CanDeleteMessages bool `json:"can_delete_messages,omitempty"` - // CanManageVoiceChats administrators only. - // True, if the administrator can manage voice chats. - // - // optional - CanManageVoiceChats bool `json:"can_manage_voice_chats"` - // CanRestrictMembers administrators only. - // True, if the administrator can restrict, ban or unban chat members. - // - // optional - CanRestrictMembers bool `json:"can_restrict_members,omitempty"` - // CanPromoteMembers administrators only. - // True, if the administrator can add new administrators - // with a subset of their own privileges or demote administrators that he has promoted, - // directly or indirectly (promoted by administrators that were appointed by the user). - // - // optional - CanPromoteMembers bool `json:"can_promote_members,omitempty"` - // CanChangeInfo administrators and restricted only. - // True, if the user is allowed to change the chat title, photo and other settings. - // - // optional - CanChangeInfo bool `json:"can_change_info,omitempty"` - // CanInviteUsers administrators and restricted only. - // True, if the user is allowed to invite new users to the chat. - // - // optional - CanInviteUsers bool `json:"can_invite_users,omitempty"` - // CanPinMessages administrators and restricted only. - // True, if the user is allowed to pin messages; groups and supergroups only - // - // optional - CanPinMessages bool `json:"can_pin_messages,omitempty"` - // IsMember is true, if the user is a member of the chat at the moment of - // the request - IsMember bool `json:"is_member"` - // CanSendMessages - // - // optional - CanSendMessages bool `json:"can_send_messages,omitempty"` - // CanSendMediaMessages restricted only. - // True, if the user is allowed to send text messages, contacts, locations and venues - // - // optional - CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` - // CanSendPolls restricted only. - // True, if the user is allowed to send polls - // - // optional - CanSendPolls bool `json:"can_send_polls,omitempty"` - // CanSendOtherMessages restricted only. - // True, if the user is allowed to send audios, documents, - // photos, videos, video notes and voice notes. - // - // optional - CanSendOtherMessages bool `json:"can_send_other_messages,omitempty"` - // CanAddWebPagePreviews restricted only. - // True, if the user is allowed to add web page previews to their messages. - // - // optional - CanAddWebPagePreviews bool `json:"can_add_web_page_previews,omitempty"` -} - -// IsCreator returns if the ChatMember was the creator of the chat. -func (chat ChatMember) IsCreator() bool { return chat.Status == "creator" } - -// IsAdministrator returns if the ChatMember is a chat administrator. -func (chat ChatMember) IsAdministrator() bool { return chat.Status == "administrator" } - -// HasLeft returns if the ChatMember left the chat. -func (chat ChatMember) HasLeft() bool { return chat.Status == "left" } - -// WasKicked returns if the ChatMember was kicked from the chat. -func (chat ChatMember) WasKicked() bool { return chat.Status == "kicked" } - -// ChatMemberUpdated represents changes in the status of a chat member. -type ChatMemberUpdated struct { - // Chat the user belongs to. - Chat Chat `json:"chat"` - // From is the performer of the action, which resulted in the change. - From User `json:"from"` - // Date the change was done in Unix time. - Date int `json:"date"` - // Previous information about the chat member. - OldChatMember ChatMember `json:"old_chat_member"` - // New information about the chat member. - NewChatMember ChatMember `json:"new_chat_member"` - // InviteLink is the link which was used by the user to join the chat; - // for joining by invite link events only. - // - // optional - InviteLink *ChatInviteLink `json:"invite_link"` -} - -// ChatJoinRequest represents a join request sent to a chat. -type ChatJoinRequest struct { - // Chat to which the request was sent. - Chat Chat `json:"chat"` - // User that sent the join request. - From User `json:"from"` - // Date the request was sent in Unix time. - Date int `json:"date"` - // Bio of the user. - // - // optional - Bio string `json:"bio"` - // InviteLink is the link that was used by the user to send the join request. - // - // optional - InviteLink *ChatInviteLink `json:"invite_link"` -} - -// ChatPermissions describes actions that a non-administrator user is -// allowed to take in a chat. All fields are optional. -type ChatPermissions struct { - // CanSendMessages is true, if the user is allowed to send text messages, - // contacts, locations and venues - // - // optional - CanSendMessages bool `json:"can_send_messages,omitempty"` - // CanSendMediaMessages is true, if the user is allowed to send audios, - // documents, photos, videos, video notes and voice notes, implies - // can_send_messages - // - // optional - CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` - // CanSendPolls is true, if the user is allowed to send polls, implies - // can_send_messages - // - // optional - CanSendPolls bool `json:"can_send_polls,omitempty"` - // CanSendOtherMessages is true, if the user is allowed to send animations, - // games, stickers and use inline bots, implies can_send_media_messages - // - // optional - CanSendOtherMessages bool `json:"can_send_other_messages,omitempty"` - // CanAddWebPagePreviews is true, if the user is allowed to add web page - // previews to their messages, implies can_send_media_messages - // - // optional - CanAddWebPagePreviews bool `json:"can_add_web_page_previews,omitempty"` - // CanChangeInfo is true, if the user is allowed to change the chat title, - // photo and other settings. Ignored in public supergroups - // - // optional - CanChangeInfo bool `json:"can_change_info,omitempty"` - // CanInviteUsers is true, if the user is allowed to invite new users to the - // chat - // - // optional - CanInviteUsers bool `json:"can_invite_users,omitempty"` - // CanPinMessages is true, if the user is allowed to pin messages. Ignored - // in public supergroups - // - // optional - CanPinMessages bool `json:"can_pin_messages,omitempty"` -} - -// ChatLocation represents a location to which a chat is connected. -type ChatLocation struct { - // Location is the location to which the supergroup is connected. Can't be a - // live location. - Location Location `json:"location"` - // Address is the location address; 1-64 characters, as defined by the chat - // owner - Address string `json:"address"` -} - -// BotCommand represents a bot command. -type BotCommand struct { - // Command text of the command, 1-32 characters. - // Can contain only lowercase English letters, digits and underscores. - Command string `json:"command"` - // Description of the command, 3-256 characters. - Description string `json:"description"` -} - -// BotCommandScope represents the scope to which bot commands are applied. -// -// It contains the fields for all types of scopes, different types only support -// specific (or no) fields. -type BotCommandScope struct { - Type string `json:"type"` - ChatID int64 `json:"chat_id,omitempty"` - UserID int64 `json:"user_id,omitempty"` -} - -// ResponseParameters are various errors that can be returned in APIResponse. -type ResponseParameters struct { - // The group has been migrated to a supergroup with the specified identifier. - // - // optional - MigrateToChatID int64 `json:"migrate_to_chat_id,omitempty"` - // In case of exceeding flood control, the number of seconds left to wait - // before the request can be repeated. - // - // optional - RetryAfter int `json:"retry_after,omitempty"` -} - -// BaseInputMedia is a base type for the InputMedia types. -type BaseInputMedia struct { - // Type of the result. - Type string `json:"type"` - // Media file to send. Pass a file_id to send a file - // that exists on the Telegram servers (recommended), - // pass an HTTP URL for Telegram to get a file from the Internet, - // or pass “attach://” to upload a new one - // using multipart/form-data under name. - Media RequestFileData `json:"media"` - // thumb intentionally missing as it is not currently compatible - - // Caption of the video to be sent, 0-1024 characters after entities parsing. - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities"` -} - -// InputMediaPhoto is a photo to send as part of a media group. -type InputMediaPhoto struct { - BaseInputMedia -} - -// InputMediaVideo is a video to send as part of a media group. -type InputMediaVideo struct { - BaseInputMedia - // Thumbnail of the file sent; can be ignored if thumbnail generation for - // the file is supported server-side. - // - // optional - Thumb RequestFileData `json:"thumb,omitempty"` - // Width video width - // - // optional - Width int `json:"width,omitempty"` - // Height video height - // - // optional - Height int `json:"height,omitempty"` - // Duration video duration - // - // optional - Duration int `json:"duration,omitempty"` - // SupportsStreaming pass True, if the uploaded video is suitable for streaming. - // - // optional - SupportsStreaming bool `json:"supports_streaming,omitempty"` -} - -// InputMediaAnimation is an animation to send as part of a media group. -type InputMediaAnimation struct { - BaseInputMedia - // Thumbnail of the file sent; can be ignored if thumbnail generation for - // the file is supported server-side. - // - // optional - Thumb RequestFileData `json:"thumb,omitempty"` - // Width video width - // - // optional - Width int `json:"width,omitempty"` - // Height video height - // - // optional - Height int `json:"height,omitempty"` - // Duration video duration - // - // optional - Duration int `json:"duration,omitempty"` -} - -// InputMediaAudio is an audio to send as part of a media group. -type InputMediaAudio struct { - BaseInputMedia - // Thumbnail of the file sent; can be ignored if thumbnail generation for - // the file is supported server-side. - // - // optional - Thumb RequestFileData `json:"thumb,omitempty"` - // Duration of the audio in seconds - // - // optional - Duration int `json:"duration,omitempty"` - // Performer of the audio - // - // optional - Performer string `json:"performer,omitempty"` - // Title of the audio - // - // optional - Title string `json:"title,omitempty"` -} - -// InputMediaDocument is a general file to send as part of a media group. -type InputMediaDocument struct { - BaseInputMedia - // Thumbnail of the file sent; can be ignored if thumbnail generation for - // the file is supported server-side. - // - // optional - Thumb RequestFileData `json:"thumb,omitempty"` - // DisableContentTypeDetection disables automatic server-side content type - // detection for files uploaded using multipart/form-data. Always true, if - // the document is sent as part of an album - // - // optional - DisableContentTypeDetection bool `json:"disable_content_type_detection,omitempty"` -} - -// Sticker represents a sticker. -type Sticker struct { - // FileID is an identifier for this file, which can be used to download or - // reuse the file - FileID string `json:"file_id"` - // FileUniqueID is a unique identifier for this file, - // which is supposed to be the same over time and for different bots. - // Can't be used to download or reuse the file. - FileUniqueID string `json:"file_unique_id"` - // Width sticker width - Width int `json:"width"` - // Height sticker height - Height int `json:"height"` - // IsAnimated true, if the sticker is animated - // - // optional - IsAnimated bool `json:"is_animated,omitempty"` - // Thumbnail sticker thumbnail in the .WEBP or .JPG format - // - // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` - // Emoji associated with the sticker - // - // optional - Emoji string `json:"emoji,omitempty"` - // SetName of the sticker set to which the sticker belongs - // - // optional - SetName string `json:"set_name,omitempty"` - // MaskPosition is for mask stickers, the position where the mask should be - // placed - // - // optional - MaskPosition *MaskPosition `json:"mask_position,omitempty"` - // FileSize - // - // optional - FileSize int `json:"file_size,omitempty"` -} - -// StickerSet represents a sticker set. -type StickerSet struct { - // Name sticker set name - Name string `json:"name"` - // Title sticker set title - Title string `json:"title"` - // IsAnimated true, if the sticker set contains animated stickers - IsAnimated bool `json:"is_animated"` - // ContainsMasks true, if the sticker set contains masks - ContainsMasks bool `json:"contains_masks"` - // Stickers list of all set stickers - Stickers []Sticker `json:"stickers"` - // Thumb is the sticker set thumbnail in the .WEBP or .TGS format - Thumbnail *PhotoSize `json:"thumb"` -} - -// MaskPosition describes the position on faces where a mask should be placed -// by default. -type MaskPosition struct { - // The part of the face relative to which the mask should be placed. - // One of “forehead”, “eyes”, “mouth”, or “chin”. - Point string `json:"point"` - // Shift by X-axis measured in widths of the mask scaled to the face size, - // from left to right. For example, choosing -1.0 will place mask just to - // the left of the default mask position. - XShift float64 `json:"x_shift"` - // Shift by Y-axis measured in heights of the mask scaled to the face size, - // from top to bottom. For example, 1.0 will place the mask just below the - // default mask position. - YShift float64 `json:"y_shift"` - // Mask scaling coefficient. For example, 2.0 means double size. - Scale float64 `json:"scale"` -} - -// Game represents a game. Use BotFather to create and edit games, their short -// names will act as unique identifiers. -type Game struct { - // Title of the game - Title string `json:"title"` - // Description of the game - Description string `json:"description"` - // Photo that will be displayed in the game message in chats. - Photo []PhotoSize `json:"photo"` - // Text a brief description of the game or high scores included in the game message. - // Can be automatically edited to include current high scores for the game - // when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters. - // - // optional - Text string `json:"text,omitempty"` - // TextEntities special entities that appear in text, such as usernames, URLs, bot commands, etc. - // - // optional - TextEntities []MessageEntity `json:"text_entities,omitempty"` - // Animation is an animation that will be displayed in the game message in chats. - // Upload via BotFather (https://t.me/botfather). - // - // optional - Animation Animation `json:"animation,omitempty"` -} - -// GameHighScore is a user's score and position on the leaderboard. -type GameHighScore struct { - // Position in high score table for the game - Position int `json:"position"` - // User user - User User `json:"user"` - // Score score - Score int `json:"score"` -} - -// CallbackGame is for starting a game in an inline keyboard button. -type CallbackGame struct{} - -// WebhookInfo is information about a currently set webhook. -type WebhookInfo struct { - // URL webhook URL, may be empty if webhook is not set up. - URL string `json:"url"` - // HasCustomCertificate true, if a custom certificate was provided for webhook certificate checks. - HasCustomCertificate bool `json:"has_custom_certificate"` - // PendingUpdateCount number of updates awaiting delivery. - PendingUpdateCount int `json:"pending_update_count"` - // IPAddress is the currently used webhook IP address - // - // optional - IPAddress string `json:"ip_address,omitempty"` - // LastErrorDate unix time for the most recent error - // that happened when trying to deliver an update via webhook. - // - // optional - LastErrorDate int `json:"last_error_date,omitempty"` - // LastErrorMessage error message in human-readable format for the most recent error - // that happened when trying to deliver an update via webhook. - // - // optional - LastErrorMessage string `json:"last_error_message,omitempty"` - // MaxConnections maximum allowed number of simultaneous - // HTTPS connections to the webhook for update delivery. - // - // optional - MaxConnections int `json:"max_connections,omitempty"` - // AllowedUpdates is a list of update types the bot is subscribed to. - // Defaults to all update types - // - // optional - AllowedUpdates []string `json:"allowed_updates,omitempty"` -} - -// IsSet returns true if a webhook is currently set. -func (info WebhookInfo) IsSet() bool { - return info.URL != "" -} - -// InlineQuery is a Query from Telegram for an inline request. -type InlineQuery struct { - // ID unique identifier for this query - ID string `json:"id"` - // From sender - From *User `json:"from"` - // Query text of the query (up to 256 characters). - Query string `json:"query"` - // Offset of the results to be returned, can be controlled by the bot. - Offset string `json:"offset"` - // Type of the chat, from which the inline query was sent. Can be either - // “sender” for a private chat with the inline query sender, “private”, - // “group”, “supergroup”, or “channel”. The chat type should be always known - // for requests sent from official clients and most third-party clients, - // unless the request was sent from a secret chat - // - // optional - ChatType string `json:"chat_type"` - // Location sender location, only for bots that request user location. - // - // optional - Location *Location `json:"location,omitempty"` -} - -// InlineQueryResultCachedAudio is an inline query response with cached audio. -type InlineQueryResultCachedAudio struct { - // Type of the result, must be audio - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // AudioID a valid file identifier for the audio file - AudioID string `json:"audio_file_id"` - // Caption 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the audio - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedDocument is an inline query response with cached document. -type InlineQueryResultCachedDocument struct { - // Type of the result, must be a document - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // DocumentID a valid file identifier for the file - DocumentID string `json:"document_file_id"` - // Title for the result - // - // optional - Title string `json:"title,omitempty"` - // Caption of the document to be sent, 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // Description short description of the result - // - // optional - Description string `json:"description,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // // See formatting options for more details - // // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the file - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedGIF is an inline query response with cached gif. -type InlineQueryResultCachedGIF struct { - // Type of the result, must be gif. - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes. - ID string `json:"id"` - // GifID a valid file identifier for the GIF file. - GIFID string `json:"gif_file_id"` - // Title for the result - // - // optional - Title string `json:"title,omitempty"` - // Caption of the GIF file to be sent, 0-1024 characters after entities parsing. - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message. - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the GIF animation. - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedMPEG4GIF is an inline query response with cached -// H.264/MPEG-4 AVC video without sound gif. -type InlineQueryResultCachedMPEG4GIF struct { - // Type of the result, must be mpeg4_gif - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // MPEG4FileID a valid file identifier for the MP4 file - MPEG4FileID string `json:"mpeg4_file_id"` - // Title for the result - // - // optional - Title string `json:"title,omitempty"` - // Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing. - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message. - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the video animation. - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedPhoto is an inline query response with cached photo. -type InlineQueryResultCachedPhoto struct { - // Type of the result, must be a photo. - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes. - ID string `json:"id"` - // PhotoID a valid file identifier of the photo. - PhotoID string `json:"photo_file_id"` - // Title for the result. - // - // optional - Title string `json:"title,omitempty"` - // Description short description of the result. - // - // optional - Description string `json:"description,omitempty"` - // Caption of the photo to be sent, 0-1024 characters after entities parsing. - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the photo caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message. - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the photo. - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedSticker is an inline query response with cached sticker. -type InlineQueryResultCachedSticker struct { - // Type of the result, must be a sticker - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // StickerID a valid file identifier of the sticker - StickerID string `json:"sticker_file_id"` - // Title is a title - Title string `json:"title"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the sticker - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedVideo is an inline query response with cached video. -type InlineQueryResultCachedVideo struct { - // Type of the result, must be video - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // VideoID a valid file identifier for the video file - VideoID string `json:"video_file_id"` - // Title for the result - Title string `json:"title"` - // Description short description of the result - // - // optional - Description string `json:"description,omitempty"` - // Caption of the video to be sent, 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the video - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultCachedVoice is an inline query response with cached voice. -type InlineQueryResultCachedVoice struct { - // Type of the result, must be voice - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // VoiceID a valid file identifier for the voice message - VoiceID string `json:"voice_file_id"` - // Title voice message title - Title string `json:"title"` - // Caption 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the voice message - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultArticle represents a link to an article or web page. -type InlineQueryResultArticle struct { - // Type of the result, must be article. - Type string `json:"type"` - // ID unique identifier for this result, 1-64 Bytes. - ID string `json:"id"` - // Title of the result - Title string `json:"title"` - // InputMessageContent content of the message to be sent. - InputMessageContent interface{} `json:"input_message_content,omitempty"` - // ReplyMarkup Inline keyboard attached to the message. - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // URL of the result. - // - // optional - URL string `json:"url,omitempty"` - // HideURL pass True, if you don't want the URL to be shown in the message. - // - // optional - HideURL bool `json:"hide_url,omitempty"` - // Description short description of the result. - // - // optional - Description string `json:"description,omitempty"` - // ThumbURL url of the thumbnail for the result - // - // optional - ThumbURL string `json:"thumb_url,omitempty"` - // ThumbWidth thumbnail width - // - // optional - ThumbWidth int `json:"thumb_width,omitempty"` - // ThumbHeight thumbnail height - // - // optional - ThumbHeight int `json:"thumb_height,omitempty"` -} - -// InlineQueryResultAudio is an inline query response audio. -type InlineQueryResultAudio struct { - // Type of the result, must be audio - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // URL a valid url for the audio file - URL string `json:"audio_url"` - // Title is a title - Title string `json:"title"` - // Caption 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // Performer is a performer - // - // optional - Performer string `json:"performer,omitempty"` - // Duration audio duration in seconds - // - // optional - Duration int `json:"audio_duration,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the audio - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultContact is an inline query response contact. -type InlineQueryResultContact struct { - Type string `json:"type"` // required - ID string `json:"id"` // required - PhoneNumber string `json:"phone_number"` // required - FirstName string `json:"first_name"` // required - LastName string `json:"last_name"` - VCard string `json:"vcard"` - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - InputMessageContent interface{} `json:"input_message_content,omitempty"` - ThumbURL string `json:"thumb_url"` - ThumbWidth int `json:"thumb_width"` - ThumbHeight int `json:"thumb_height"` -} - -// InlineQueryResultGame is an inline query response game. -type InlineQueryResultGame struct { - // Type of the result, must be game - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // GameShortName short name of the game - GameShortName string `json:"game_short_name"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` -} - -// InlineQueryResultDocument is an inline query response document. -type InlineQueryResultDocument struct { - // Type of the result, must be a document - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // Title for the result - Title string `json:"title"` - // Caption of the document to be sent, 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // URL a valid url for the file - URL string `json:"document_url"` - // MimeType of the content of the file, either “application/pdf” or “application/zip” - MimeType string `json:"mime_type"` - // Description short description of the result - // - // optional - Description string `json:"description,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the file - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` - // ThumbURL url of the thumbnail (jpeg only) for the file - // - // optional - ThumbURL string `json:"thumb_url,omitempty"` - // ThumbWidth thumbnail width - // - // optional - ThumbWidth int `json:"thumb_width,omitempty"` - // ThumbHeight thumbnail height - // - // optional - ThumbHeight int `json:"thumb_height,omitempty"` -} - -// InlineQueryResultGIF is an inline query response GIF. -type InlineQueryResultGIF struct { - // Type of the result, must be gif. - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes. - ID string `json:"id"` - // URL a valid URL for the GIF file. File size must not exceed 1MB. - URL string `json:"gif_url"` - // ThumbURL url of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result. - ThumbURL string `json:"thumb_url"` - // Width of the GIF - // - // optional - Width int `json:"gif_width,omitempty"` - // Height of the GIF - // - // optional - Height int `json:"gif_height,omitempty"` - // Duration of the GIF - // - // optional - Duration int `json:"gif_duration,omitempty"` - // Title for the result - // - // optional - Title string `json:"title,omitempty"` - // Caption of the GIF file to be sent, 0-1024 characters after entities parsing. - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the GIF animation. - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultLocation is an inline query response location. -type InlineQueryResultLocation struct { - // Type of the result, must be location - Type string `json:"type"` - // ID unique identifier for this result, 1-64 Bytes - ID string `json:"id"` - // Latitude of the location in degrees - Latitude float64 `json:"latitude"` - // Longitude of the location in degrees - Longitude float64 `json:"longitude"` - // Title of the location - Title string `json:"title"` - // HorizontalAccuracy is the radius of uncertainty for the location, - // measured in meters; 0-1500 - // - // optional - HorizontalAccuracy float64 `json:"horizontal_accuracy"` - // LivePeriod is the period in seconds for which the location can be - // updated, should be between 60 and 86400. - // - // optional - LivePeriod int `json:"live_period"` - // Heading is for live locations, a direction in which the user is moving, - // in degrees. Must be between 1 and 360 if specified. - // - // optional - Heading int `json:"heading"` - // ProximityAlertRadius is for live locations, a maximum distance for - // proximity alerts about approaching another chat member, in meters. Must - // be between 1 and 100000 if specified. - // - // optional - ProximityAlertRadius int `json:"proximity_alert_radius"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the location - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` - // ThumbURL url of the thumbnail for the result - // - // optional - ThumbURL string `json:"thumb_url,omitempty"` - // ThumbWidth thumbnail width - // - // optional - ThumbWidth int `json:"thumb_width,omitempty"` - // ThumbHeight thumbnail height - // - // optional - ThumbHeight int `json:"thumb_height,omitempty"` -} - -// InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF. -type InlineQueryResultMPEG4GIF struct { - // Type of the result, must be mpeg4_gif - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // URL a valid URL for the MP4 file. File size must not exceed 1MB - URL string `json:"mpeg4_url"` - // Width video width - // - // optional - Width int `json:"mpeg4_width"` - // Height vVideo height - // - // optional - Height int `json:"mpeg4_height"` - // Duration video duration - // - // optional - Duration int `json:"mpeg4_duration"` - // ThumbURL url of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result. - ThumbURL string `json:"thumb_url"` - // Title for the result - // - // optional - Title string `json:"title,omitempty"` - // Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing. - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the video animation - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultPhoto is an inline query response photo. -type InlineQueryResultPhoto struct { - // Type of the result, must be article. - Type string `json:"type"` - // ID unique identifier for this result, 1-64 Bytes. - ID string `json:"id"` - // URL a valid URL of the photo. Photo must be in jpeg format. - // Photo size must not exceed 5MB. - URL string `json:"photo_url"` - // MimeType - MimeType string `json:"mime_type"` - // Width of the photo - // - // optional - Width int `json:"photo_width,omitempty"` - // Height of the photo - // - // optional - Height int `json:"photo_height,omitempty"` - // ThumbURL url of the thumbnail for the photo. - // - // optional - ThumbURL string `json:"thumb_url,omitempty"` - // Title for the result - // - // optional - Title string `json:"title,omitempty"` - // Description short description of the result - // - // optional - Description string `json:"description,omitempty"` - // Caption of the photo to be sent, 0-1024 characters after entities parsing. - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the photo caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // ReplyMarkup inline keyboard attached to the message. - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // InputMessageContent content of the message to be sent instead of the photo. - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultVenue is an inline query response venue. -type InlineQueryResultVenue struct { - // Type of the result, must be venue - Type string `json:"type"` - // ID unique identifier for this result, 1-64 Bytes - ID string `json:"id"` - // Latitude of the venue location in degrees - Latitude float64 `json:"latitude"` - // Longitude of the venue location in degrees - Longitude float64 `json:"longitude"` - // Title of the venue - Title string `json:"title"` - // Address of the venue - Address string `json:"address"` - // FoursquareID foursquare identifier of the venue if known - // - // optional - FoursquareID string `json:"foursquare_id,omitempty"` - // FoursquareType foursquare type of the venue, if known. - // (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) - // - // optional - FoursquareType string `json:"foursquare_type,omitempty"` - // GooglePlaceID is the Google Places identifier of the venue - // - // optional - GooglePlaceID string `json:"google_place_id,omitempty"` - // GooglePlaceType is the Google Places type of the venue - // - // optional - GooglePlaceType string `json:"google_place_type,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the venue - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` - // ThumbURL url of the thumbnail for the result - // - // optional - ThumbURL string `json:"thumb_url,omitempty"` - // ThumbWidth thumbnail width - // - // optional - ThumbWidth int `json:"thumb_width,omitempty"` - // ThumbHeight thumbnail height - // - // optional - ThumbHeight int `json:"thumb_height,omitempty"` -} - -// InlineQueryResultVideo is an inline query response video. -type InlineQueryResultVideo struct { - // Type of the result, must be video - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // URL a valid url for the embedded video player or video file - URL string `json:"video_url"` - // MimeType of the content of video url, “text/html” or “video/mp4” - MimeType string `json:"mime_type"` - // - // ThumbURL url of the thumbnail (jpeg only) for the video - // optional - ThumbURL string `json:"thumb_url,omitempty"` - // Title for the result - Title string `json:"title"` - // Caption of the video to be sent, 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // Width video width - // - // optional - Width int `json:"video_width,omitempty"` - // Height video height - // - // optional - Height int `json:"video_height,omitempty"` - // Duration video duration in seconds - // - // optional - Duration int `json:"video_duration,omitempty"` - // Description short description of the result - // - // optional - Description string `json:"description,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the video. - // This field is required if InlineQueryResultVideo is used to send - // an HTML-page as a result (e.g., a YouTube video). - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// InlineQueryResultVoice is an inline query response voice. -type InlineQueryResultVoice struct { - // Type of the result, must be voice - Type string `json:"type"` - // ID unique identifier for this result, 1-64 bytes - ID string `json:"id"` - // URL a valid URL for the voice recording - URL string `json:"voice_url"` - // Title recording title - Title string `json:"title"` - // Caption 0-1024 characters after entities parsing - // - // optional - Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // CaptionEntities is a list of special entities that appear in the caption, - // which can be specified instead of parse_mode - // - // optional - CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` - // Duration recording duration in seconds - // - // optional - Duration int `json:"voice_duration,omitempty"` - // ReplyMarkup inline keyboard attached to the message - // - // optional - ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` - // InputMessageContent content of the message to be sent instead of the voice recording - // - // optional - InputMessageContent interface{} `json:"input_message_content,omitempty"` -} - -// ChosenInlineResult is an inline query result chosen by a User -type ChosenInlineResult struct { - // ResultID the unique identifier for the result that was chosen - ResultID string `json:"result_id"` - // From the user that chose the result - From *User `json:"from"` - // Location sender location, only for bots that require user location - // - // optional - Location *Location `json:"location,omitempty"` - // InlineMessageID identifier of the sent inline message. - // Available only if there is an inline keyboard attached to the message. - // Will be also received in callback queries and can be used to edit the message. - // - // optional - InlineMessageID string `json:"inline_message_id,omitempty"` - // Query the query that was used to obtain the result - Query string `json:"query"` -} - -// InputTextMessageContent contains text for displaying -// as an inline query result. -type InputTextMessageContent struct { - // Text of the message to be sent, 1-4096 characters - Text string `json:"message_text"` - // ParseMode mode for parsing entities in the message text. - // See formatting options for more details - // (https://core.telegram.org/bots/api#formatting-options). - // - // optional - ParseMode string `json:"parse_mode,omitempty"` - // Entities is a list of special entities that appear in message text, which - // can be specified instead of parse_mode - // - // optional - Entities []MessageEntity `json:"entities,omitempty"` - // DisableWebPagePreview disables link previews for links in the sent message - // - // optional - DisableWebPagePreview bool `json:"disable_web_page_preview,omitempty"` -} - -// InputLocationMessageContent contains a location for displaying -// as an inline query result. -type InputLocationMessageContent struct { - // Latitude of the location in degrees - Latitude float64 `json:"latitude"` - // Longitude of the location in degrees - Longitude float64 `json:"longitude"` - // HorizontalAccuracy is the radius of uncertainty for the location, - // measured in meters; 0-1500 - // - // optional - HorizontalAccuracy float64 `json:"horizontal_accuracy"` - // LivePeriod is the period in seconds for which the location can be - // updated, should be between 60 and 86400 - // - // optional - LivePeriod int `json:"live_period,omitempty"` - // Heading is for live locations, a direction in which the user is moving, - // in degrees. Must be between 1 and 360 if specified. - // - // optional - Heading int `json:"heading"` - // ProximityAlertRadius is for live locations, a maximum distance for - // proximity alerts about approaching another chat member, in meters. Must - // be between 1 and 100000 if specified. - // - // optional - ProximityAlertRadius int `json:"proximity_alert_radius"` -} - -// InputVenueMessageContent contains a venue for displaying -// as an inline query result. -type InputVenueMessageContent struct { - // Latitude of the venue in degrees - Latitude float64 `json:"latitude"` - // Longitude of the venue in degrees - Longitude float64 `json:"longitude"` - // Title name of the venue - Title string `json:"title"` - // Address of the venue - Address string `json:"address"` - // FoursquareID foursquare identifier of the venue, if known - // - // optional - FoursquareID string `json:"foursquare_id,omitempty"` - // FoursquareType Foursquare type of the venue, if known - // - // optional - FoursquareType string `json:"foursquare_type,omitempty"` - // GooglePlaceID is the Google Places identifier of the venue - // - // optional - GooglePlaceID string `json:"google_place_id"` - // GooglePlaceType is the Google Places type of the venue - // - // optional - GooglePlaceType string `json:"google_place_type"` -} - -// InputContactMessageContent contains a contact for displaying -// as an inline query result. -type InputContactMessageContent struct { - // PhoneNumber contact's phone number - PhoneNumber string `json:"phone_number"` - // FirstName contact's first name - FirstName string `json:"first_name"` - // LastName contact's last name - // - // optional - LastName string `json:"last_name,omitempty"` - // Additional data about the contact in the form of a vCard - // - // optional - VCard string `json:"vcard,omitempty"` -} - -// InputInvoiceMessageContent represents the content of an invoice message to be -// sent as the result of an inline query. -type InputInvoiceMessageContent struct { - // Product name, 1-32 characters - Title string `json:"title"` - // Product description, 1-255 characters - Description string `json:"description"` - // Bot-defined invoice payload, 1-128 bytes. This will not be displayed to - // the user, use for your internal processes. - Payload string `json:"payload"` - // Payment provider token, obtained via Botfather - ProviderToken string `json:"provider_token"` - // Three-letter ISO 4217 currency code - Currency string `json:"currency"` - // Price breakdown, a JSON-serialized list of components (e.g. product - // price, tax, discount, delivery cost, delivery tax, bonus, etc.) - Prices []LabeledPrice `json:"prices"` - // The maximum accepted amount for tips in the smallest units of the - // currency (integer, not float/double). - // - // optional - MaxTipAmount int `json:"max_tip_amount,omitempty"` - // An array of suggested amounts of tip in the smallest units of the - // currency (integer, not float/double). At most 4 suggested tip amounts can - // be specified. The suggested tip amounts must be positive, passed in a - // strictly increased order and must not exceed max_tip_amount. - // - // optional - SuggestedTipAmounts []int `json:"suggested_tip_amounts,omitempty"` - // A JSON-serialized object for data about the invoice, which will be shared - // with the payment provider. A detailed description of the required fields - // should be provided by the payment provider. - // - // optional - ProviderData string `json:"provider_data,omitempty"` - // URL of the product photo for the invoice. Can be a photo of the goods or - // a marketing image for a service. People like it better when they see what - // they are paying for. - // - // optional - PhotoURL string `json:"photo_url,omitempty"` - // Photo size - // - // optional - PhotoSize int `json:"photo_size,omitempty"` - // Photo width - // - // optional - PhotoWidth int `json:"photo_width,omitempty"` - // Photo height - // - // optional - PhotoHeight int `json:"photo_height,omitempty"` - // Pass True, if you require the user's full name to complete the order - // - // optional - NeedName bool `json:"need_name,omitempty"` - // Pass True, if you require the user's phone number to complete the order - // - // optional - NeedPhoneNumber bool `json:"need_phone_number,omitempty"` - // Pass True, if you require the user's email address to complete the order - // - // optional - NeedEmail bool `json:"need_email,omitempty"` - // Pass True, if you require the user's shipping address to complete the order - // - // optional - NeedShippingAddress bool `json:"need_shipping_address,omitempty"` - // Pass True, if user's phone number should be sent to provider - // - // optional - SendPhoneNumberToProvider bool `json:"send_phone_number_to_provider,omitempty"` - // Pass True, if user's email address should be sent to provider - // - // optional - SendEmailToProvider bool `json:"send_email_to_provider,omitempty"` - // Pass True, if the final price depends on the shipping method - // - // optional - IsFlexible bool `json:"is_flexible,omitempty"` -} - -// LabeledPrice represents a portion of the price for goods or services. -type LabeledPrice struct { - // Label portion label - Label string `json:"label"` - // Amount price of the product in the smallest units of the currency (integer, not float/double). - // For example, for a price of US$ 1.45 pass amount = 145. - // See the exp parameter in currencies.json - // (https://core.telegram.org/bots/payments/currencies.json), - // it shows the number of digits past the decimal point - // for each currency (2 for the majority of currencies). - Amount int `json:"amount"` -} - -// Invoice contains basic information about an invoice. -type Invoice struct { - // Title product name - Title string `json:"title"` - // Description product description - Description string `json:"description"` - // StartParameter unique bot deep-linking parameter that can be used to generate this invoice - StartParameter string `json:"start_parameter"` - // Currency three-letter ISO 4217 currency code - // (see https://core.telegram.org/bots/payments#supported-currencies) - Currency string `json:"currency"` - // TotalAmount total price in the smallest units of the currency (integer, not float/double). - // For example, for a price of US$ 1.45 pass amount = 145. - // See the exp parameter in currencies.json - // (https://core.telegram.org/bots/payments/currencies.json), - // it shows the number of digits past the decimal point - // for each currency (2 for the majority of currencies). - TotalAmount int `json:"total_amount"` -} - -// ShippingAddress represents a shipping address. -type ShippingAddress struct { - // CountryCode ISO 3166-1 alpha-2 country code - CountryCode string `json:"country_code"` - // State if applicable - State string `json:"state"` - // City city - City string `json:"city"` - // StreetLine1 first line for the address - StreetLine1 string `json:"street_line1"` - // StreetLine2 second line for the address - StreetLine2 string `json:"street_line2"` - // PostCode address post code - PostCode string `json:"post_code"` -} - -// OrderInfo represents information about an order. -type OrderInfo struct { - // Name user name - // - // optional - Name string `json:"name,omitempty"` - // PhoneNumber user's phone number - // - // optional - PhoneNumber string `json:"phone_number,omitempty"` - // Email user email - // - // optional - Email string `json:"email,omitempty"` - // ShippingAddress user shipping address - // - // optional - ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` -} - -// ShippingOption represents one shipping option. -type ShippingOption struct { - // ID shipping option identifier - ID string `json:"id"` - // Title option title - Title string `json:"title"` - // Prices list of price portions - Prices []LabeledPrice `json:"prices"` -} - -// SuccessfulPayment contains basic information about a successful payment. -type SuccessfulPayment struct { - // Currency three-letter ISO 4217 currency code - // (see https://core.telegram.org/bots/payments#supported-currencies) - Currency string `json:"currency"` - // TotalAmount total price in the smallest units of the currency (integer, not float/double). - // For example, for a price of US$ 1.45 pass amount = 145. - // See the exp parameter in currencies.json, - // (https://core.telegram.org/bots/payments/currencies.json) - // it shows the number of digits past the decimal point - // for each currency (2 for the majority of currencies). - TotalAmount int `json:"total_amount"` - // InvoicePayload bot specified invoice payload - InvoicePayload string `json:"invoice_payload"` - // ShippingOptionID identifier of the shipping option chosen by the user - // - // optional - ShippingOptionID string `json:"shipping_option_id,omitempty"` - // OrderInfo order info provided by the user - // - // optional - OrderInfo *OrderInfo `json:"order_info,omitempty"` - // TelegramPaymentChargeID telegram payment identifier - TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` - // ProviderPaymentChargeID provider payment identifier - ProviderPaymentChargeID string `json:"provider_payment_charge_id"` -} - -// ShippingQuery contains information about an incoming shipping query. -type ShippingQuery struct { - // ID unique query identifier - ID string `json:"id"` - // From user who sent the query - From *User `json:"from"` - // InvoicePayload bot specified invoice payload - InvoicePayload string `json:"invoice_payload"` - // ShippingAddress user specified shipping address - ShippingAddress *ShippingAddress `json:"shipping_address"` -} - -// PreCheckoutQuery contains information about an incoming pre-checkout query. -type PreCheckoutQuery struct { - // ID unique query identifier - ID string `json:"id"` - // From user who sent the query - From *User `json:"from"` - // Currency three-letter ISO 4217 currency code - // // (see https://core.telegram.org/bots/payments#supported-currencies) - Currency string `json:"currency"` - // TotalAmount total price in the smallest units of the currency (integer, not float/double). - // // For example, for a price of US$ 1.45 pass amount = 145. - // // See the exp parameter in currencies.json, - // // (https://core.telegram.org/bots/payments/currencies.json) - // // it shows the number of digits past the decimal point - // // for each currency (2 for the majority of currencies). - TotalAmount int `json:"total_amount"` - // InvoicePayload bot specified invoice payload - InvoicePayload string `json:"invoice_payload"` - // ShippingOptionID identifier of the shipping option chosen by the user - // - // optional - ShippingOptionID string `json:"shipping_option_id,omitempty"` - // OrderInfo order info provided by the user - // - // optional - OrderInfo *OrderInfo `json:"order_info,omitempty"` -} diff --git a/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/golang/protobuf/AUTHORS deleted file mode 100644 index 15167cd7..00000000 --- a/vendor/github.com/golang/protobuf/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/golang/protobuf/CONTRIBUTORS deleted file mode 100644 index 1c4577e9..00000000 --- a/vendor/github.com/golang/protobuf/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 0f646931..00000000 --- a/vendor/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/golang/protobuf/proto/buffer.go b/vendor/github.com/golang/protobuf/proto/buffer.go deleted file mode 100644 index e810e6fe..00000000 --- a/vendor/github.com/golang/protobuf/proto/buffer.go +++ /dev/null @@ -1,324 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "errors" - "fmt" - - "google.golang.org/protobuf/encoding/prototext" - "google.golang.org/protobuf/encoding/protowire" - "google.golang.org/protobuf/runtime/protoimpl" -) - -const ( - WireVarint = 0 - WireFixed32 = 5 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 -) - -// EncodeVarint returns the varint encoded bytes of v. -func EncodeVarint(v uint64) []byte { - return protowire.AppendVarint(nil, v) -} - -// SizeVarint returns the length of the varint encoded bytes of v. -// This is equal to len(EncodeVarint(v)). -func SizeVarint(v uint64) int { - return protowire.SizeVarint(v) -} - -// DecodeVarint parses a varint encoded integer from b, -// returning the integer value and the length of the varint. -// It returns (0, 0) if there is a parse error. -func DecodeVarint(b []byte) (uint64, int) { - v, n := protowire.ConsumeVarint(b) - if n < 0 { - return 0, 0 - } - return v, n -} - -// Buffer is a buffer for encoding and decoding the protobuf wire format. -// It may be reused between invocations to reduce memory usage. -type Buffer struct { - buf []byte - idx int - deterministic bool -} - -// NewBuffer allocates a new Buffer initialized with buf, -// where the contents of buf are considered the unread portion of the buffer. -func NewBuffer(buf []byte) *Buffer { - return &Buffer{buf: buf} -} - -// SetDeterministic specifies whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexographical order. This is an implementation detail and -// subject to change. -func (b *Buffer) SetDeterministic(deterministic bool) { - b.deterministic = deterministic -} - -// SetBuf sets buf as the internal buffer, -// where the contents of buf are considered the unread portion of the buffer. -func (b *Buffer) SetBuf(buf []byte) { - b.buf = buf - b.idx = 0 -} - -// Reset clears the internal buffer of all written and unread data. -func (b *Buffer) Reset() { - b.buf = b.buf[:0] - b.idx = 0 -} - -// Bytes returns the internal buffer. -func (b *Buffer) Bytes() []byte { - return b.buf -} - -// Unread returns the unread portion of the buffer. -func (b *Buffer) Unread() []byte { - return b.buf[b.idx:] -} - -// Marshal appends the wire-format encoding of m to the buffer. -func (b *Buffer) Marshal(m Message) error { - var err error - b.buf, err = marshalAppend(b.buf, m, b.deterministic) - return err -} - -// Unmarshal parses the wire-format message in the buffer and -// places the decoded results in m. -// It does not reset m before unmarshaling. -func (b *Buffer) Unmarshal(m Message) error { - err := UnmarshalMerge(b.Unread(), m) - b.idx = len(b.buf) - return err -} - -type unknownFields struct{ XXX_unrecognized protoimpl.UnknownFields } - -func (m *unknownFields) String() string { panic("not implemented") } -func (m *unknownFields) Reset() { panic("not implemented") } -func (m *unknownFields) ProtoMessage() { panic("not implemented") } - -// DebugPrint dumps the encoded bytes of b with a header and footer including s -// to stdout. This is only intended for debugging. -func (*Buffer) DebugPrint(s string, b []byte) { - m := MessageReflect(new(unknownFields)) - m.SetUnknown(b) - b, _ = prototext.MarshalOptions{AllowPartial: true, Indent: "\t"}.Marshal(m.Interface()) - fmt.Printf("==== %s ====\n%s==== %s ====\n", s, b, s) -} - -// EncodeVarint appends an unsigned varint encoding to the buffer. -func (b *Buffer) EncodeVarint(v uint64) error { - b.buf = protowire.AppendVarint(b.buf, v) - return nil -} - -// EncodeZigzag32 appends a 32-bit zig-zag varint encoding to the buffer. -func (b *Buffer) EncodeZigzag32(v uint64) error { - return b.EncodeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) -} - -// EncodeZigzag64 appends a 64-bit zig-zag varint encoding to the buffer. -func (b *Buffer) EncodeZigzag64(v uint64) error { - return b.EncodeVarint(uint64((uint64(v) << 1) ^ uint64((int64(v) >> 63)))) -} - -// EncodeFixed32 appends a 32-bit little-endian integer to the buffer. -func (b *Buffer) EncodeFixed32(v uint64) error { - b.buf = protowire.AppendFixed32(b.buf, uint32(v)) - return nil -} - -// EncodeFixed64 appends a 64-bit little-endian integer to the buffer. -func (b *Buffer) EncodeFixed64(v uint64) error { - b.buf = protowire.AppendFixed64(b.buf, uint64(v)) - return nil -} - -// EncodeRawBytes appends a length-prefixed raw bytes to the buffer. -func (b *Buffer) EncodeRawBytes(v []byte) error { - b.buf = protowire.AppendBytes(b.buf, v) - return nil -} - -// EncodeStringBytes appends a length-prefixed raw bytes to the buffer. -// It does not validate whether v contains valid UTF-8. -func (b *Buffer) EncodeStringBytes(v string) error { - b.buf = protowire.AppendString(b.buf, v) - return nil -} - -// EncodeMessage appends a length-prefixed encoded message to the buffer. -func (b *Buffer) EncodeMessage(m Message) error { - var err error - b.buf = protowire.AppendVarint(b.buf, uint64(Size(m))) - b.buf, err = marshalAppend(b.buf, m, b.deterministic) - return err -} - -// DecodeVarint consumes an encoded unsigned varint from the buffer. -func (b *Buffer) DecodeVarint() (uint64, error) { - v, n := protowire.ConsumeVarint(b.buf[b.idx:]) - if n < 0 { - return 0, protowire.ParseError(n) - } - b.idx += n - return uint64(v), nil -} - -// DecodeZigzag32 consumes an encoded 32-bit zig-zag varint from the buffer. -func (b *Buffer) DecodeZigzag32() (uint64, error) { - v, err := b.DecodeVarint() - if err != nil { - return 0, err - } - return uint64((uint32(v) >> 1) ^ uint32((int32(v&1)<<31)>>31)), nil -} - -// DecodeZigzag64 consumes an encoded 64-bit zig-zag varint from the buffer. -func (b *Buffer) DecodeZigzag64() (uint64, error) { - v, err := b.DecodeVarint() - if err != nil { - return 0, err - } - return uint64((uint64(v) >> 1) ^ uint64((int64(v&1)<<63)>>63)), nil -} - -// DecodeFixed32 consumes a 32-bit little-endian integer from the buffer. -func (b *Buffer) DecodeFixed32() (uint64, error) { - v, n := protowire.ConsumeFixed32(b.buf[b.idx:]) - if n < 0 { - return 0, protowire.ParseError(n) - } - b.idx += n - return uint64(v), nil -} - -// DecodeFixed64 consumes a 64-bit little-endian integer from the buffer. -func (b *Buffer) DecodeFixed64() (uint64, error) { - v, n := protowire.ConsumeFixed64(b.buf[b.idx:]) - if n < 0 { - return 0, protowire.ParseError(n) - } - b.idx += n - return uint64(v), nil -} - -// DecodeRawBytes consumes a length-prefixed raw bytes from the buffer. -// If alloc is specified, it returns a copy the raw bytes -// rather than a sub-slice of the buffer. -func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) { - v, n := protowire.ConsumeBytes(b.buf[b.idx:]) - if n < 0 { - return nil, protowire.ParseError(n) - } - b.idx += n - if alloc { - v = append([]byte(nil), v...) - } - return v, nil -} - -// DecodeStringBytes consumes a length-prefixed raw bytes from the buffer. -// It does not validate whether the raw bytes contain valid UTF-8. -func (b *Buffer) DecodeStringBytes() (string, error) { - v, n := protowire.ConsumeString(b.buf[b.idx:]) - if n < 0 { - return "", protowire.ParseError(n) - } - b.idx += n - return v, nil -} - -// DecodeMessage consumes a length-prefixed message from the buffer. -// It does not reset m before unmarshaling. -func (b *Buffer) DecodeMessage(m Message) error { - v, err := b.DecodeRawBytes(false) - if err != nil { - return err - } - return UnmarshalMerge(v, m) -} - -// DecodeGroup consumes a message group from the buffer. -// It assumes that the start group marker has already been consumed and -// consumes all bytes until (and including the end group marker). -// It does not reset m before unmarshaling. -func (b *Buffer) DecodeGroup(m Message) error { - v, n, err := consumeGroup(b.buf[b.idx:]) - if err != nil { - return err - } - b.idx += n - return UnmarshalMerge(v, m) -} - -// consumeGroup parses b until it finds an end group marker, returning -// the raw bytes of the message (excluding the end group marker) and the -// the total length of the message (including the end group marker). -func consumeGroup(b []byte) ([]byte, int, error) { - b0 := b - depth := 1 // assume this follows a start group marker - for { - _, wtyp, tagLen := protowire.ConsumeTag(b) - if tagLen < 0 { - return nil, 0, protowire.ParseError(tagLen) - } - b = b[tagLen:] - - var valLen int - switch wtyp { - case protowire.VarintType: - _, valLen = protowire.ConsumeVarint(b) - case protowire.Fixed32Type: - _, valLen = protowire.ConsumeFixed32(b) - case protowire.Fixed64Type: - _, valLen = protowire.ConsumeFixed64(b) - case protowire.BytesType: - _, valLen = protowire.ConsumeBytes(b) - case protowire.StartGroupType: - depth++ - case protowire.EndGroupType: - depth-- - default: - return nil, 0, errors.New("proto: cannot parse reserved wire type") - } - if valLen < 0 { - return nil, 0, protowire.ParseError(valLen) - } - b = b[valLen:] - - if depth == 0 { - return b0[:len(b0)-len(b)-tagLen], len(b0) - len(b), nil - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/defaults.go b/vendor/github.com/golang/protobuf/proto/defaults.go deleted file mode 100644 index d399bf06..00000000 --- a/vendor/github.com/golang/protobuf/proto/defaults.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "google.golang.org/protobuf/reflect/protoreflect" -) - -// SetDefaults sets unpopulated scalar fields to their default values. -// Fields within a oneof are not set even if they have a default value. -// SetDefaults is recursively called upon any populated message fields. -func SetDefaults(m Message) { - if m != nil { - setDefaults(MessageReflect(m)) - } -} - -func setDefaults(m protoreflect.Message) { - fds := m.Descriptor().Fields() - for i := 0; i < fds.Len(); i++ { - fd := fds.Get(i) - if !m.Has(fd) { - if fd.HasDefault() && fd.ContainingOneof() == nil { - v := fd.Default() - if fd.Kind() == protoreflect.BytesKind { - v = protoreflect.ValueOf(append([]byte(nil), v.Bytes()...)) // copy the default bytes - } - m.Set(fd, v) - } - continue - } - } - - m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - switch { - // Handle singular message. - case fd.Cardinality() != protoreflect.Repeated: - if fd.Message() != nil { - setDefaults(m.Get(fd).Message()) - } - // Handle list of messages. - case fd.IsList(): - if fd.Message() != nil { - ls := m.Get(fd).List() - for i := 0; i < ls.Len(); i++ { - setDefaults(ls.Get(i).Message()) - } - } - // Handle map of messages. - case fd.IsMap(): - if fd.MapValue().Message() != nil { - ms := m.Get(fd).Map() - ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool { - setDefaults(v.Message()) - return true - }) - } - } - return true - }) -} diff --git a/vendor/github.com/golang/protobuf/proto/deprecated.go b/vendor/github.com/golang/protobuf/proto/deprecated.go deleted file mode 100644 index e8db57e0..00000000 --- a/vendor/github.com/golang/protobuf/proto/deprecated.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "encoding/json" - "errors" - "fmt" - "strconv" - - protoV2 "google.golang.org/protobuf/proto" -) - -var ( - // Deprecated: No longer returned. - ErrNil = errors.New("proto: Marshal called with nil") - - // Deprecated: No longer returned. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") - - // Deprecated: No longer returned. - ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") -) - -// Deprecated: Do not use. -type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } - -// Deprecated: Do not use. -func GetStats() Stats { return Stats{} } - -// Deprecated: Do not use. -func MarshalMessageSet(interface{}) ([]byte, error) { - return nil, errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func UnmarshalMessageSet([]byte, interface{}) error { - return errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func MarshalMessageSetJSON(interface{}) ([]byte, error) { - return nil, errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func UnmarshalMessageSetJSON([]byte, interface{}) error { - return errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func RegisterMessageSetType(Message, int32, string) {} - -// Deprecated: Do not use. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// Deprecated: Do not use. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// Deprecated: Do not use; this type existed for intenal-use only. -type InternalMessageInfo struct{} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) DiscardUnknown(m Message) { - DiscardUnknown(m) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Marshal(b []byte, m Message, deterministic bool) ([]byte, error) { - return protoV2.MarshalOptions{Deterministic: deterministic}.MarshalAppend(b, MessageV2(m)) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Merge(dst, src Message) { - protoV2.Merge(MessageV2(dst), MessageV2(src)) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Size(m Message) int { - return protoV2.Size(MessageV2(m)) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Unmarshal(m Message, b []byte) error { - return protoV2.UnmarshalOptions{Merge: true}.Unmarshal(b, MessageV2(m)) -} diff --git a/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/golang/protobuf/proto/discard.go deleted file mode 100644 index 2187e877..00000000 --- a/vendor/github.com/golang/protobuf/proto/discard.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "google.golang.org/protobuf/reflect/protoreflect" -) - -// DiscardUnknown recursively discards all unknown fields from this message -// and all embedded messages. -// -// When unmarshaling a message with unrecognized fields, the tags and values -// of such fields are preserved in the Message. This allows a later call to -// marshal to be able to produce a message that continues to have those -// unrecognized fields. To avoid this, DiscardUnknown is used to -// explicitly clear the unknown fields after unmarshaling. -func DiscardUnknown(m Message) { - if m != nil { - discardUnknown(MessageReflect(m)) - } -} - -func discardUnknown(m protoreflect.Message) { - m.Range(func(fd protoreflect.FieldDescriptor, val protoreflect.Value) bool { - switch { - // Handle singular message. - case fd.Cardinality() != protoreflect.Repeated: - if fd.Message() != nil { - discardUnknown(m.Get(fd).Message()) - } - // Handle list of messages. - case fd.IsList(): - if fd.Message() != nil { - ls := m.Get(fd).List() - for i := 0; i < ls.Len(); i++ { - discardUnknown(ls.Get(i).Message()) - } - } - // Handle map of messages. - case fd.IsMap(): - if fd.MapValue().Message() != nil { - ms := m.Get(fd).Map() - ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool { - discardUnknown(v.Message()) - return true - }) - } - } - return true - }) - - // Discard unknown fields. - if len(m.GetUnknown()) > 0 { - m.SetUnknown(nil) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index 42fc120c..00000000 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "errors" - "fmt" - "reflect" - - "google.golang.org/protobuf/encoding/protowire" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - "google.golang.org/protobuf/runtime/protoiface" - "google.golang.org/protobuf/runtime/protoimpl" -) - -type ( - // ExtensionDesc represents an extension descriptor and - // is used to interact with an extension field in a message. - // - // Variables of this type are generated in code by protoc-gen-go. - ExtensionDesc = protoimpl.ExtensionInfo - - // ExtensionRange represents a range of message extensions. - // Used in code generated by protoc-gen-go. - ExtensionRange = protoiface.ExtensionRangeV1 - - // Deprecated: Do not use; this is an internal type. - Extension = protoimpl.ExtensionFieldV1 - - // Deprecated: Do not use; this is an internal type. - XXX_InternalExtensions = protoimpl.ExtensionFields -) - -// ErrMissingExtension reports whether the extension was not present. -var ErrMissingExtension = errors.New("proto: missing extension") - -var errNotExtendable = errors.New("proto: not an extendable proto.Message") - -// HasExtension reports whether the extension field is present in m -// either as an explicitly populated field or as an unknown field. -func HasExtension(m Message, xt *ExtensionDesc) (has bool) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return false - } - - // Check whether any populated known field matches the field number. - xtd := xt.TypeDescriptor() - if isValidExtension(mr.Descriptor(), xtd) { - has = mr.Has(xtd) - } else { - mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { - has = int32(fd.Number()) == xt.Field - return !has - }) - } - - // Check whether any unknown field matches the field number. - for b := mr.GetUnknown(); !has && len(b) > 0; { - num, _, n := protowire.ConsumeField(b) - has = int32(num) == xt.Field - b = b[n:] - } - return has -} - -// ClearExtension removes the extension field from m -// either as an explicitly populated field or as an unknown field. -func ClearExtension(m Message, xt *ExtensionDesc) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return - } - - xtd := xt.TypeDescriptor() - if isValidExtension(mr.Descriptor(), xtd) { - mr.Clear(xtd) - } else { - mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { - if int32(fd.Number()) == xt.Field { - mr.Clear(fd) - return false - } - return true - }) - } - clearUnknown(mr, fieldNum(xt.Field)) -} - -// ClearAllExtensions clears all extensions from m. -// This includes populated fields and unknown fields in the extension range. -func ClearAllExtensions(m Message) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return - } - - mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { - if fd.IsExtension() { - mr.Clear(fd) - } - return true - }) - clearUnknown(mr, mr.Descriptor().ExtensionRanges()) -} - -// GetExtension retrieves a proto2 extended field from m. -// -// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), -// then GetExtension parses the encoded field and returns a Go value of the specified type. -// If the field is not present, then the default value is returned (if one is specified), -// otherwise ErrMissingExtension is reported. -// -// If the descriptor is type incomplete (i.e., ExtensionDesc.ExtensionType is nil), -// then GetExtension returns the raw encoded bytes for the extension field. -func GetExtension(m Message, xt *ExtensionDesc) (interface{}, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { - return nil, errNotExtendable - } - - // Retrieve the unknown fields for this extension field. - var bo protoreflect.RawFields - for bi := mr.GetUnknown(); len(bi) > 0; { - num, _, n := protowire.ConsumeField(bi) - if int32(num) == xt.Field { - bo = append(bo, bi[:n]...) - } - bi = bi[n:] - } - - // For type incomplete descriptors, only retrieve the unknown fields. - if xt.ExtensionType == nil { - return []byte(bo), nil - } - - // If the extension field only exists as unknown fields, unmarshal it. - // This is rarely done since proto.Unmarshal eagerly unmarshals extensions. - xtd := xt.TypeDescriptor() - if !isValidExtension(mr.Descriptor(), xtd) { - return nil, fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m) - } - if !mr.Has(xtd) && len(bo) > 0 { - m2 := mr.New() - if err := (proto.UnmarshalOptions{ - Resolver: extensionResolver{xt}, - }.Unmarshal(bo, m2.Interface())); err != nil { - return nil, err - } - if m2.Has(xtd) { - mr.Set(xtd, m2.Get(xtd)) - clearUnknown(mr, fieldNum(xt.Field)) - } - } - - // Check whether the message has the extension field set or a default. - var pv protoreflect.Value - switch { - case mr.Has(xtd): - pv = mr.Get(xtd) - case xtd.HasDefault(): - pv = xtd.Default() - default: - return nil, ErrMissingExtension - } - - v := xt.InterfaceOf(pv) - rv := reflect.ValueOf(v) - if isScalarKind(rv.Kind()) { - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - v = rv2.Interface() - } - return v, nil -} - -// extensionResolver is a custom extension resolver that stores a single -// extension type that takes precedence over the global registry. -type extensionResolver struct{ xt protoreflect.ExtensionType } - -func (r extensionResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { - if xtd := r.xt.TypeDescriptor(); xtd.FullName() == field { - return r.xt, nil - } - return protoregistry.GlobalTypes.FindExtensionByName(field) -} - -func (r extensionResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { - if xtd := r.xt.TypeDescriptor(); xtd.ContainingMessage().FullName() == message && xtd.Number() == field { - return r.xt, nil - } - return protoregistry.GlobalTypes.FindExtensionByNumber(message, field) -} - -// GetExtensions returns a list of the extensions values present in m, -// corresponding with the provided list of extension descriptors, xts. -// If an extension is missing in m, the corresponding value is nil. -func GetExtensions(m Message, xts []*ExtensionDesc) ([]interface{}, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return nil, errNotExtendable - } - - vs := make([]interface{}, len(xts)) - for i, xt := range xts { - v, err := GetExtension(m, xt) - if err != nil { - if err == ErrMissingExtension { - continue - } - return vs, err - } - vs[i] = v - } - return vs, nil -} - -// SetExtension sets an extension field in m to the provided value. -func SetExtension(m Message, xt *ExtensionDesc, v interface{}) error { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { - return errNotExtendable - } - - rv := reflect.ValueOf(v) - if reflect.TypeOf(v) != reflect.TypeOf(xt.ExtensionType) { - return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", v, xt.ExtensionType) - } - if rv.Kind() == reflect.Ptr { - if rv.IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", v) - } - if isScalarKind(rv.Elem().Kind()) { - v = rv.Elem().Interface() - } - } - - xtd := xt.TypeDescriptor() - if !isValidExtension(mr.Descriptor(), xtd) { - return fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m) - } - mr.Set(xtd, xt.ValueOf(v)) - clearUnknown(mr, fieldNum(xt.Field)) - return nil -} - -// SetRawExtension inserts b into the unknown fields of m. -// -// Deprecated: Use Message.ProtoReflect.SetUnknown instead. -func SetRawExtension(m Message, fnum int32, b []byte) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return - } - - // Verify that the raw field is valid. - for b0 := b; len(b0) > 0; { - num, _, n := protowire.ConsumeField(b0) - if int32(num) != fnum { - panic(fmt.Sprintf("mismatching field number: got %d, want %d", num, fnum)) - } - b0 = b0[n:] - } - - ClearExtension(m, &ExtensionDesc{Field: fnum}) - mr.SetUnknown(append(mr.GetUnknown(), b...)) -} - -// ExtensionDescs returns a list of extension descriptors found in m, -// containing descriptors for both populated extension fields in m and -// also unknown fields of m that are in the extension range. -// For the later case, an type incomplete descriptor is provided where only -// the ExtensionDesc.Field field is populated. -// The order of the extension descriptors is undefined. -func ExtensionDescs(m Message) ([]*ExtensionDesc, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { - return nil, errNotExtendable - } - - // Collect a set of known extension descriptors. - extDescs := make(map[protoreflect.FieldNumber]*ExtensionDesc) - mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - if fd.IsExtension() { - xt := fd.(protoreflect.ExtensionTypeDescriptor) - if xd, ok := xt.Type().(*ExtensionDesc); ok { - extDescs[fd.Number()] = xd - } - } - return true - }) - - // Collect a set of unknown extension descriptors. - extRanges := mr.Descriptor().ExtensionRanges() - for b := mr.GetUnknown(); len(b) > 0; { - num, _, n := protowire.ConsumeField(b) - if extRanges.Has(num) && extDescs[num] == nil { - extDescs[num] = nil - } - b = b[n:] - } - - // Transpose the set of descriptors into a list. - var xts []*ExtensionDesc - for num, xt := range extDescs { - if xt == nil { - xt = &ExtensionDesc{Field: int32(num)} - } - xts = append(xts, xt) - } - return xts, nil -} - -// isValidExtension reports whether xtd is a valid extension descriptor for md. -func isValidExtension(md protoreflect.MessageDescriptor, xtd protoreflect.ExtensionTypeDescriptor) bool { - return xtd.ContainingMessage() == md && md.ExtensionRanges().Has(xtd.Number()) -} - -// isScalarKind reports whether k is a protobuf scalar kind (except bytes). -// This function exists for historical reasons since the representation of -// scalars differs between v1 and v2, where v1 uses *T and v2 uses T. -func isScalarKind(k reflect.Kind) bool { - switch k { - case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: - return true - default: - return false - } -} - -// clearUnknown removes unknown fields from m where remover.Has reports true. -func clearUnknown(m protoreflect.Message, remover interface { - Has(protoreflect.FieldNumber) bool -}) { - var bo protoreflect.RawFields - for bi := m.GetUnknown(); len(bi) > 0; { - num, _, n := protowire.ConsumeField(bi) - if !remover.Has(num) { - bo = append(bo, bi[:n]...) - } - bi = bi[n:] - } - if bi := m.GetUnknown(); len(bi) != len(bo) { - m.SetUnknown(bo) - } -} - -type fieldNum protoreflect.FieldNumber - -func (n1 fieldNum) Has(n2 protoreflect.FieldNumber) bool { - return protoreflect.FieldNumber(n1) == n2 -} diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index dcdc2202..00000000 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "fmt" - "reflect" - "strconv" - "strings" - "sync" - - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/runtime/protoimpl" -) - -// StructProperties represents protocol buffer type information for a -// generated protobuf message in the open-struct API. -// -// Deprecated: Do not use. -type StructProperties struct { - // Prop are the properties for each field. - // - // Fields belonging to a oneof are stored in OneofTypes instead, with a - // single Properties representing the parent oneof held here. - // - // The order of Prop matches the order of fields in the Go struct. - // Struct fields that are not related to protobufs have a "XXX_" prefix - // in the Properties.Name and must be ignored by the user. - Prop []*Properties - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the protobuf field name. - OneofTypes map[string]*OneofProperties -} - -// Properties represents the type information for a protobuf message field. -// -// Deprecated: Do not use. -type Properties struct { - // Name is a placeholder name with little meaningful semantic value. - // If the name has an "XXX_" prefix, the entire Properties must be ignored. - Name string - // OrigName is the protobuf field name or oneof name. - OrigName string - // JSONName is the JSON name for the protobuf field. - JSONName string - // Enum is a placeholder name for enums. - // For historical reasons, this is neither the Go name for the enum, - // nor the protobuf name for the enum. - Enum string // Deprecated: Do not use. - // Weak contains the full name of the weakly referenced message. - Weak string - // Wire is a string representation of the wire type. - Wire string - // WireType is the protobuf wire type for the field. - WireType int - // Tag is the protobuf field number. - Tag int - // Required reports whether this is a required field. - Required bool - // Optional reports whether this is a optional field. - Optional bool - // Repeated reports whether this is a repeated field. - Repeated bool - // Packed reports whether this is a packed repeated field of scalars. - Packed bool - // Proto3 reports whether this field operates under the proto3 syntax. - Proto3 bool - // Oneof reports whether this field belongs within a oneof. - Oneof bool - - // Default is the default value in string form. - Default string - // HasDefault reports whether the field has a default value. - HasDefault bool - - // MapKeyProp is the properties for the key field for a map field. - MapKeyProp *Properties - // MapValProp is the properties for the value field for a map field. - MapValProp *Properties -} - -// OneofProperties represents the type information for a protobuf oneof. -// -// Deprecated: Do not use. -type OneofProperties struct { - // Type is a pointer to the generated wrapper type for the field value. - // This is nil for messages that are not in the open-struct API. - Type reflect.Type - // Field is the index into StructProperties.Prop for the containing oneof. - Field int - // Prop is the properties for the field. - Prop *Properties -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s += "," + strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != "" { - s += ",json=" + p.JSONName - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if len(p.Weak) > 0 { - s += ",weak=" + p.Weak - } - if p.Proto3 { - s += ",proto3" - } - if p.Oneof { - s += ",oneof" - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(tag string) { - // For example: "bytes,49,opt,name=foo,def=hello!" - for len(tag) > 0 { - i := strings.IndexByte(tag, ',') - if i < 0 { - i = len(tag) - } - switch s := tag[:i]; { - case strings.HasPrefix(s, "name="): - p.OrigName = s[len("name="):] - case strings.HasPrefix(s, "json="): - p.JSONName = s[len("json="):] - case strings.HasPrefix(s, "enum="): - p.Enum = s[len("enum="):] - case strings.HasPrefix(s, "weak="): - p.Weak = s[len("weak="):] - case strings.Trim(s, "0123456789") == "": - n, _ := strconv.ParseUint(s, 10, 32) - p.Tag = int(n) - case s == "opt": - p.Optional = true - case s == "req": - p.Required = true - case s == "rep": - p.Repeated = true - case s == "varint" || s == "zigzag32" || s == "zigzag64": - p.Wire = s - p.WireType = WireVarint - case s == "fixed32": - p.Wire = s - p.WireType = WireFixed32 - case s == "fixed64": - p.Wire = s - p.WireType = WireFixed64 - case s == "bytes": - p.Wire = s - p.WireType = WireBytes - case s == "group": - p.Wire = s - p.WireType = WireStartGroup - case s == "packed": - p.Packed = true - case s == "proto3": - p.Proto3 = true - case s == "oneof": - p.Oneof = true - case strings.HasPrefix(s, "def="): - // The default tag is special in that everything afterwards is the - // default regardless of the presence of commas. - p.HasDefault = true - p.Default, i = tag[len("def="):], len(tag) - } - tag = strings.TrimPrefix(tag[i:], ",") - } -} - -// Init populates the properties from a protocol buffer struct tag. -// -// Deprecated: Do not use. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.Name = name - p.OrigName = name - if tag == "" { - return - } - p.Parse(tag) - - if typ != nil && typ.Kind() == reflect.Map { - p.MapKeyProp = new(Properties) - p.MapKeyProp.Init(nil, "Key", f.Tag.Get("protobuf_key"), nil) - p.MapValProp = new(Properties) - p.MapValProp.Init(nil, "Value", f.Tag.Get("protobuf_val"), nil) - } -} - -var propertiesCache sync.Map // map[reflect.Type]*StructProperties - -// GetProperties returns the list of properties for the type represented by t, -// which must be a generated protocol buffer message in the open-struct API, -// where protobuf message fields are represented by exported Go struct fields. -// -// Deprecated: Use protobuf reflection instead. -func GetProperties(t reflect.Type) *StructProperties { - if p, ok := propertiesCache.Load(t); ok { - return p.(*StructProperties) - } - p, _ := propertiesCache.LoadOrStore(t, newProperties(t)) - return p.(*StructProperties) -} - -func newProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t)) - } - - var hasOneof bool - prop := new(StructProperties) - - // Construct a list of properties for each field in the struct. - for i := 0; i < t.NumField(); i++ { - p := new(Properties) - f := t.Field(i) - tagField := f.Tag.Get("protobuf") - p.Init(f.Type, f.Name, tagField, &f) - - tagOneof := f.Tag.Get("protobuf_oneof") - if tagOneof != "" { - hasOneof = true - p.OrigName = tagOneof - } - - // Rename unrelated struct fields with the "XXX_" prefix since so much - // user code simply checks for this to exclude special fields. - if tagField == "" && tagOneof == "" && !strings.HasPrefix(p.Name, "XXX_") { - p.Name = "XXX_" + p.Name - p.OrigName = "XXX_" + p.OrigName - } else if p.Weak != "" { - p.Name = p.OrigName // avoid possible "XXX_" prefix on weak field - } - - prop.Prop = append(prop.Prop, p) - } - - // Construct a mapping of oneof field names to properties. - if hasOneof { - var oneofWrappers []interface{} - if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok { - oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{}) - } - if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok { - oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{}) - } - if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(protoreflect.ProtoMessage); ok { - if m, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *protoimpl.MessageInfo }); ok { - oneofWrappers = m.ProtoMessageInfo().OneofWrappers - } - } - - prop.OneofTypes = make(map[string]*OneofProperties) - for _, wrapper := range oneofWrappers { - p := &OneofProperties{ - Type: reflect.ValueOf(wrapper).Type(), // *T - Prop: new(Properties), - } - f := p.Type.Elem().Field(0) - p.Prop.Name = f.Name - p.Prop.Parse(f.Tag.Get("protobuf")) - - // Determine the struct field that contains this oneof. - // Each wrapper is assignable to exactly one parent field. - var foundOneof bool - for i := 0; i < t.NumField() && !foundOneof; i++ { - if p.Type.AssignableTo(t.Field(i).Type) { - p.Field = i - foundOneof = true - } - } - if !foundOneof { - panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t)) - } - prop.OneofTypes[p.Prop.OrigName] = p - } - } - - return prop -} - -func (sp *StructProperties) Len() int { return len(sp.Prop) } -func (sp *StructProperties) Less(i, j int) bool { return false } -func (sp *StructProperties) Swap(i, j int) { return } diff --git a/vendor/github.com/golang/protobuf/proto/proto.go b/vendor/github.com/golang/protobuf/proto/proto.go deleted file mode 100644 index 5aee89c3..00000000 --- a/vendor/github.com/golang/protobuf/proto/proto.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package proto provides functionality for handling protocol buffer messages. -// In particular, it provides marshaling and unmarshaling between a protobuf -// message and the binary wire format. -// -// See https://developers.google.com/protocol-buffers/docs/gotutorial for -// more information. -// -// Deprecated: Use the "google.golang.org/protobuf/proto" package instead. -package proto - -import ( - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/runtime/protoiface" - "google.golang.org/protobuf/runtime/protoimpl" -) - -const ( - ProtoPackageIsVersion1 = true - ProtoPackageIsVersion2 = true - ProtoPackageIsVersion3 = true - ProtoPackageIsVersion4 = true -) - -// GeneratedEnum is any enum type generated by protoc-gen-go -// which is a named int32 kind. -// This type exists for documentation purposes. -type GeneratedEnum interface{} - -// GeneratedMessage is any message type generated by protoc-gen-go -// which is a pointer to a named struct kind. -// This type exists for documentation purposes. -type GeneratedMessage interface{} - -// Message is a protocol buffer message. -// -// This is the v1 version of the message interface and is marginally better -// than an empty interface as it lacks any method to programatically interact -// with the contents of the message. -// -// A v2 message is declared in "google.golang.org/protobuf/proto".Message and -// exposes protobuf reflection as a first-class feature of the interface. -// -// To convert a v1 message to a v2 message, use the MessageV2 function. -// To convert a v2 message to a v1 message, use the MessageV1 function. -type Message = protoiface.MessageV1 - -// MessageV1 converts either a v1 or v2 message to a v1 message. -// It returns nil if m is nil. -func MessageV1(m GeneratedMessage) protoiface.MessageV1 { - return protoimpl.X.ProtoMessageV1Of(m) -} - -// MessageV2 converts either a v1 or v2 message to a v2 message. -// It returns nil if m is nil. -func MessageV2(m GeneratedMessage) protoV2.Message { - return protoimpl.X.ProtoMessageV2Of(m) -} - -// MessageReflect returns a reflective view for a message. -// It returns nil if m is nil. -func MessageReflect(m Message) protoreflect.Message { - return protoimpl.X.MessageOf(m) -} - -// Marshaler is implemented by messages that can marshal themselves. -// This interface is used by the following functions: Size, Marshal, -// Buffer.Marshal, and Buffer.EncodeMessage. -// -// Deprecated: Do not implement. -type Marshaler interface { - // Marshal formats the encoded bytes of the message. - // It should be deterministic and emit valid protobuf wire data. - // The caller takes ownership of the returned buffer. - Marshal() ([]byte, error) -} - -// Unmarshaler is implemented by messages that can unmarshal themselves. -// This interface is used by the following functions: Unmarshal, UnmarshalMerge, -// Buffer.Unmarshal, Buffer.DecodeMessage, and Buffer.DecodeGroup. -// -// Deprecated: Do not implement. -type Unmarshaler interface { - // Unmarshal parses the encoded bytes of the protobuf wire input. - // The provided buffer is only valid for during method call. - // It should not reset the receiver message. - Unmarshal([]byte) error -} - -// Merger is implemented by messages that can merge themselves. -// This interface is used by the following functions: Clone and Merge. -// -// Deprecated: Do not implement. -type Merger interface { - // Merge merges the contents of src into the receiver message. - // It clones all data structures in src such that it aliases no mutable - // memory referenced by src. - Merge(src Message) -} - -// RequiredNotSetError is an error type returned when -// marshaling or unmarshaling a message with missing required fields. -type RequiredNotSetError struct { - err error -} - -func (e *RequiredNotSetError) Error() string { - if e.err != nil { - return e.err.Error() - } - return "proto: required field not set" -} -func (e *RequiredNotSetError) RequiredNotSet() bool { - return true -} - -func checkRequiredNotSet(m protoV2.Message) error { - if err := protoV2.CheckInitialized(m); err != nil { - return &RequiredNotSetError{err: err} - } - return nil -} - -// Clone returns a deep copy of src. -func Clone(src Message) Message { - return MessageV1(protoV2.Clone(MessageV2(src))) -} - -// Merge merges src into dst, which must be messages of the same type. -// -// Populated scalar fields in src are copied to dst, while populated -// singular messages in src are merged into dst by recursively calling Merge. -// The elements of every list field in src is appended to the corresponded -// list fields in dst. The entries of every map field in src is copied into -// the corresponding map field in dst, possibly replacing existing entries. -// The unknown fields of src are appended to the unknown fields of dst. -func Merge(dst, src Message) { - protoV2.Merge(MessageV2(dst), MessageV2(src)) -} - -// Equal reports whether two messages are equal. -// If two messages marshal to the same bytes under deterministic serialization, -// then Equal is guaranteed to report true. -// -// Two messages are equal if they are the same protobuf message type, -// have the same set of populated known and extension field values, -// and the same set of unknown fields values. -// -// Scalar values are compared with the equivalent of the == operator in Go, -// except bytes values which are compared using bytes.Equal and -// floating point values which specially treat NaNs as equal. -// Message values are compared by recursively calling Equal. -// Lists are equal if each element value is also equal. -// Maps are equal if they have the same set of keys, where the pair of values -// for each key is also equal. -func Equal(x, y Message) bool { - return protoV2.Equal(MessageV2(x), MessageV2(y)) -} - -func isMessageSet(md protoreflect.MessageDescriptor) bool { - ms, ok := md.(interface{ IsMessageSet() bool }) - return ok && ms.IsMessageSet() -} diff --git a/vendor/github.com/golang/protobuf/proto/registry.go b/vendor/github.com/golang/protobuf/proto/registry.go deleted file mode 100644 index 066b4323..00000000 --- a/vendor/github.com/golang/protobuf/proto/registry.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "bytes" - "compress/gzip" - "fmt" - "io/ioutil" - "reflect" - "strings" - "sync" - - "google.golang.org/protobuf/reflect/protodesc" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - "google.golang.org/protobuf/runtime/protoimpl" -) - -// filePath is the path to the proto source file. -type filePath = string // e.g., "google/protobuf/descriptor.proto" - -// fileDescGZIP is the compressed contents of the encoded FileDescriptorProto. -type fileDescGZIP = []byte - -var fileCache sync.Map // map[filePath]fileDescGZIP - -// RegisterFile is called from generated code to register the compressed -// FileDescriptorProto with the file path for a proto source file. -// -// Deprecated: Use protoregistry.GlobalFiles.RegisterFile instead. -func RegisterFile(s filePath, d fileDescGZIP) { - // Decompress the descriptor. - zr, err := gzip.NewReader(bytes.NewReader(d)) - if err != nil { - panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err)) - } - b, err := ioutil.ReadAll(zr) - if err != nil { - panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err)) - } - - // Construct a protoreflect.FileDescriptor from the raw descriptor. - // Note that DescBuilder.Build automatically registers the constructed - // file descriptor with the v2 registry. - protoimpl.DescBuilder{RawDescriptor: b}.Build() - - // Locally cache the raw descriptor form for the file. - fileCache.Store(s, d) -} - -// FileDescriptor returns the compressed FileDescriptorProto given the file path -// for a proto source file. It returns nil if not found. -// -// Deprecated: Use protoregistry.GlobalFiles.FindFileByPath instead. -func FileDescriptor(s filePath) fileDescGZIP { - if v, ok := fileCache.Load(s); ok { - return v.(fileDescGZIP) - } - - // Find the descriptor in the v2 registry. - var b []byte - if fd, _ := protoregistry.GlobalFiles.FindFileByPath(s); fd != nil { - b, _ = Marshal(protodesc.ToFileDescriptorProto(fd)) - } - - // Locally cache the raw descriptor form for the file. - if len(b) > 0 { - v, _ := fileCache.LoadOrStore(s, protoimpl.X.CompressGZIP(b)) - return v.(fileDescGZIP) - } - return nil -} - -// enumName is the name of an enum. For historical reasons, the enum name is -// neither the full Go name nor the full protobuf name of the enum. -// The name is the dot-separated combination of just the proto package that the -// enum is declared within followed by the Go type name of the generated enum. -type enumName = string // e.g., "my.proto.package.GoMessage_GoEnum" - -// enumsByName maps enum values by name to their numeric counterpart. -type enumsByName = map[string]int32 - -// enumsByNumber maps enum values by number to their name counterpart. -type enumsByNumber = map[int32]string - -var enumCache sync.Map // map[enumName]enumsByName -var numFilesCache sync.Map // map[protoreflect.FullName]int - -// RegisterEnum is called from the generated code to register the mapping of -// enum value names to enum numbers for the enum identified by s. -// -// Deprecated: Use protoregistry.GlobalTypes.RegisterEnum instead. -func RegisterEnum(s enumName, _ enumsByNumber, m enumsByName) { - if _, ok := enumCache.Load(s); ok { - panic("proto: duplicate enum registered: " + s) - } - enumCache.Store(s, m) - - // This does not forward registration to the v2 registry since this API - // lacks sufficient information to construct a complete v2 enum descriptor. -} - -// EnumValueMap returns the mapping from enum value names to enum numbers for -// the enum of the given name. It returns nil if not found. -// -// Deprecated: Use protoregistry.GlobalTypes.FindEnumByName instead. -func EnumValueMap(s enumName) enumsByName { - if v, ok := enumCache.Load(s); ok { - return v.(enumsByName) - } - - // Check whether the cache is stale. If the number of files in the current - // package differs, then it means that some enums may have been recently - // registered upstream that we do not know about. - var protoPkg protoreflect.FullName - if i := strings.LastIndexByte(s, '.'); i >= 0 { - protoPkg = protoreflect.FullName(s[:i]) - } - v, _ := numFilesCache.Load(protoPkg) - numFiles, _ := v.(int) - if protoregistry.GlobalFiles.NumFilesByPackage(protoPkg) == numFiles { - return nil // cache is up-to-date; was not found earlier - } - - // Update the enum cache for all enums declared in the given proto package. - numFiles = 0 - protoregistry.GlobalFiles.RangeFilesByPackage(protoPkg, func(fd protoreflect.FileDescriptor) bool { - walkEnums(fd, func(ed protoreflect.EnumDescriptor) { - name := protoimpl.X.LegacyEnumName(ed) - if _, ok := enumCache.Load(name); !ok { - m := make(enumsByName) - evs := ed.Values() - for i := evs.Len() - 1; i >= 0; i-- { - ev := evs.Get(i) - m[string(ev.Name())] = int32(ev.Number()) - } - enumCache.LoadOrStore(name, m) - } - }) - numFiles++ - return true - }) - numFilesCache.Store(protoPkg, numFiles) - - // Check cache again for enum map. - if v, ok := enumCache.Load(s); ok { - return v.(enumsByName) - } - return nil -} - -// walkEnums recursively walks all enums declared in d. -func walkEnums(d interface { - Enums() protoreflect.EnumDescriptors - Messages() protoreflect.MessageDescriptors -}, f func(protoreflect.EnumDescriptor)) { - eds := d.Enums() - for i := eds.Len() - 1; i >= 0; i-- { - f(eds.Get(i)) - } - mds := d.Messages() - for i := mds.Len() - 1; i >= 0; i-- { - walkEnums(mds.Get(i), f) - } -} - -// messageName is the full name of protobuf message. -type messageName = string - -var messageTypeCache sync.Map // map[messageName]reflect.Type - -// RegisterType is called from generated code to register the message Go type -// for a message of the given name. -// -// Deprecated: Use protoregistry.GlobalTypes.RegisterMessage instead. -func RegisterType(m Message, s messageName) { - mt := protoimpl.X.LegacyMessageTypeOf(m, protoreflect.FullName(s)) - if err := protoregistry.GlobalTypes.RegisterMessage(mt); err != nil { - panic(err) - } - messageTypeCache.Store(s, reflect.TypeOf(m)) -} - -// RegisterMapType is called from generated code to register the Go map type -// for a protobuf message representing a map entry. -// -// Deprecated: Do not use. -func RegisterMapType(m interface{}, s messageName) { - t := reflect.TypeOf(m) - if t.Kind() != reflect.Map { - panic(fmt.Sprintf("invalid map kind: %v", t)) - } - if _, ok := messageTypeCache.Load(s); ok { - panic(fmt.Errorf("proto: duplicate proto message registered: %s", s)) - } - messageTypeCache.Store(s, t) -} - -// MessageType returns the message type for a named message. -// It returns nil if not found. -// -// Deprecated: Use protoregistry.GlobalTypes.FindMessageByName instead. -func MessageType(s messageName) reflect.Type { - if v, ok := messageTypeCache.Load(s); ok { - return v.(reflect.Type) - } - - // Derive the message type from the v2 registry. - var t reflect.Type - if mt, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(s)); mt != nil { - t = messageGoType(mt) - } - - // If we could not get a concrete type, it is possible that it is a - // pseudo-message for a map entry. - if t == nil { - d, _ := protoregistry.GlobalFiles.FindDescriptorByName(protoreflect.FullName(s)) - if md, _ := d.(protoreflect.MessageDescriptor); md != nil && md.IsMapEntry() { - kt := goTypeForField(md.Fields().ByNumber(1)) - vt := goTypeForField(md.Fields().ByNumber(2)) - t = reflect.MapOf(kt, vt) - } - } - - // Locally cache the message type for the given name. - if t != nil { - v, _ := messageTypeCache.LoadOrStore(s, t) - return v.(reflect.Type) - } - return nil -} - -func goTypeForField(fd protoreflect.FieldDescriptor) reflect.Type { - switch k := fd.Kind(); k { - case protoreflect.EnumKind: - if et, _ := protoregistry.GlobalTypes.FindEnumByName(fd.Enum().FullName()); et != nil { - return enumGoType(et) - } - return reflect.TypeOf(protoreflect.EnumNumber(0)) - case protoreflect.MessageKind, protoreflect.GroupKind: - if mt, _ := protoregistry.GlobalTypes.FindMessageByName(fd.Message().FullName()); mt != nil { - return messageGoType(mt) - } - return reflect.TypeOf((*protoreflect.Message)(nil)).Elem() - default: - return reflect.TypeOf(fd.Default().Interface()) - } -} - -func enumGoType(et protoreflect.EnumType) reflect.Type { - return reflect.TypeOf(et.New(0)) -} - -func messageGoType(mt protoreflect.MessageType) reflect.Type { - return reflect.TypeOf(MessageV1(mt.Zero().Interface())) -} - -// MessageName returns the full protobuf name for the given message type. -// -// Deprecated: Use protoreflect.MessageDescriptor.FullName instead. -func MessageName(m Message) messageName { - if m == nil { - return "" - } - if m, ok := m.(interface{ XXX_MessageName() messageName }); ok { - return m.XXX_MessageName() - } - return messageName(protoimpl.X.MessageDescriptorOf(m).FullName()) -} - -// RegisterExtension is called from the generated code to register -// the extension descriptor. -// -// Deprecated: Use protoregistry.GlobalTypes.RegisterExtension instead. -func RegisterExtension(d *ExtensionDesc) { - if err := protoregistry.GlobalTypes.RegisterExtension(d); err != nil { - panic(err) - } -} - -type extensionsByNumber = map[int32]*ExtensionDesc - -var extensionCache sync.Map // map[messageName]extensionsByNumber - -// RegisteredExtensions returns a map of the registered extensions for the -// provided protobuf message, indexed by the extension field number. -// -// Deprecated: Use protoregistry.GlobalTypes.RangeExtensionsByMessage instead. -func RegisteredExtensions(m Message) extensionsByNumber { - // Check whether the cache is stale. If the number of extensions for - // the given message differs, then it means that some extensions were - // recently registered upstream that we do not know about. - s := MessageName(m) - v, _ := extensionCache.Load(s) - xs, _ := v.(extensionsByNumber) - if protoregistry.GlobalTypes.NumExtensionsByMessage(protoreflect.FullName(s)) == len(xs) { - return xs // cache is up-to-date - } - - // Cache is stale, re-compute the extensions map. - xs = make(extensionsByNumber) - protoregistry.GlobalTypes.RangeExtensionsByMessage(protoreflect.FullName(s), func(xt protoreflect.ExtensionType) bool { - if xd, ok := xt.(*ExtensionDesc); ok { - xs[int32(xt.TypeDescriptor().Number())] = xd - } else { - // TODO: This implies that the protoreflect.ExtensionType is a - // custom type not generated by protoc-gen-go. We could try and - // convert the type to an ExtensionDesc. - } - return true - }) - extensionCache.Store(s, xs) - return xs -} diff --git a/vendor/github.com/golang/protobuf/proto/text_decode.go b/vendor/github.com/golang/protobuf/proto/text_decode.go deleted file mode 100644 index 47eb3e44..00000000 --- a/vendor/github.com/golang/protobuf/proto/text_decode.go +++ /dev/null @@ -1,801 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" - - "google.golang.org/protobuf/encoding/prototext" - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" -) - -const wrapTextUnmarshalV2 = false - -// ParseError is returned by UnmarshalText. -type ParseError struct { - Message string - - // Deprecated: Do not use. - Line, Offset int -} - -func (e *ParseError) Error() string { - if wrapTextUnmarshalV2 { - return e.Message - } - if e.Line == 1 { - return fmt.Sprintf("line 1.%d: %v", e.Offset, e.Message) - } - return fmt.Sprintf("line %d: %v", e.Line, e.Message) -} - -// UnmarshalText parses a proto text formatted string into m. -func UnmarshalText(s string, m Message) error { - if u, ok := m.(encoding.TextUnmarshaler); ok { - return u.UnmarshalText([]byte(s)) - } - - m.Reset() - mi := MessageV2(m) - - if wrapTextUnmarshalV2 { - err := prototext.UnmarshalOptions{ - AllowPartial: true, - }.Unmarshal([]byte(s), mi) - if err != nil { - return &ParseError{Message: err.Error()} - } - return checkRequiredNotSet(mi) - } else { - if err := newTextParser(s).unmarshalMessage(mi.ProtoReflect(), ""); err != nil { - return err - } - return checkRequiredNotSet(mi) - } -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) unmarshalMessage(m protoreflect.Message, terminator string) (err error) { - md := m.Descriptor() - fds := md.Fields() - - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - seen := make(map[protoreflect.FieldNumber]bool) - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - if err := p.unmarshalExtensionOrAny(m, seen); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := protoreflect.Name(tok.value) - fd := fds.ByName(name) - switch { - case fd == nil: - gd := fds.ByName(protoreflect.Name(strings.ToLower(string(name)))) - if gd != nil && gd.Kind() == protoreflect.GroupKind && gd.Message().Name() == name { - fd = gd - } - case fd.Kind() == protoreflect.GroupKind && fd.Message().Name() != name: - fd = nil - case fd.IsWeak() && fd.Message().IsPlaceholder(): - fd = nil - } - if fd == nil { - typeName := string(md.FullName()) - if m, ok := m.Interface().(Message); ok { - t := reflect.TypeOf(m) - if t.Kind() == reflect.Ptr { - typeName = t.Elem().String() - } - } - return p.errorf("unknown field name %q in %v", name, typeName) - } - if od := fd.ContainingOneof(); od != nil && m.WhichOneof(od) != nil { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, od.Name()) - } - if fd.Cardinality() != protoreflect.Repeated && seen[fd.Number()] { - return p.errorf("non-repeated field %q was repeated", fd.Name()) - } - seen[fd.Number()] = true - - // Consume any colon. - if err := p.checkForColon(fd); err != nil { - return err - } - - // Parse into the field. - v := m.Get(fd) - if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) { - v = m.Mutable(fd) - } - if v, err = p.unmarshalValue(v, fd); err != nil { - return err - } - m.Set(fd, v) - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - } - return nil -} - -func (p *textParser) unmarshalExtensionOrAny(m protoreflect.Message, seen map[protoreflect.FieldNumber]bool) error { - name, err := p.consumeExtensionOrAnyName() - if err != nil { - return err - } - - // If it contains a slash, it's an Any type URL. - if slashIdx := strings.LastIndex(name, "/"); slashIdx >= 0 { - tok := p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - - mt, err := protoregistry.GlobalTypes.FindMessageByURL(name) - if err != nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", name[slashIdx+len("/"):]) - } - m2 := mt.New() - if err := p.unmarshalMessage(m2, terminator); err != nil { - return err - } - b, err := protoV2.Marshal(m2.Interface()) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", name[slashIdx+len("/"):], err) - } - - urlFD := m.Descriptor().Fields().ByName("type_url") - valFD := m.Descriptor().Fields().ByName("value") - if seen[urlFD.Number()] { - return p.errorf("Any message unpacked multiple times, or %q already set", urlFD.Name()) - } - if seen[valFD.Number()] { - return p.errorf("Any message unpacked multiple times, or %q already set", valFD.Name()) - } - m.Set(urlFD, protoreflect.ValueOfString(name)) - m.Set(valFD, protoreflect.ValueOfBytes(b)) - seen[urlFD.Number()] = true - seen[valFD.Number()] = true - return nil - } - - xname := protoreflect.FullName(name) - xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname) - if xt == nil && isMessageSet(m.Descriptor()) { - xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension")) - } - if xt == nil { - return p.errorf("unrecognized extension %q", name) - } - fd := xt.TypeDescriptor() - if fd.ContainingMessage().FullName() != m.Descriptor().FullName() { - return p.errorf("extension field %q does not extend message %q", name, m.Descriptor().FullName()) - } - - if err := p.checkForColon(fd); err != nil { - return err - } - - v := m.Get(fd) - if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) { - v = m.Mutable(fd) - } - v, err = p.unmarshalValue(v, fd) - if err != nil { - return err - } - m.Set(fd, v) - return p.consumeOptionalSeparator() -} - -func (p *textParser) unmarshalValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == "" { - return v, p.errorf("unexpected EOF") - } - - switch { - case fd.IsList(): - lv := v.List() - var err error - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - vv := lv.NewElement() - vv, err = p.unmarshalSingularValue(vv, fd) - if err != nil { - return v, err - } - lv.Append(vv) - - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return v, p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return v, nil - } - - // One value of the repeated field. - p.back() - vv := lv.NewElement() - vv, err = p.unmarshalSingularValue(vv, fd) - if err != nil { - return v, err - } - lv.Append(vv) - return v, nil - case fd.IsMap(): - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return v, p.errorf("expected '{' or '<', found %q", tok.value) - } - - keyFD := fd.MapKey() - valFD := fd.MapValue() - - mv := v.Map() - kv := keyFD.Default() - vv := mv.NewValue() - for { - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == terminator { - break - } - var err error - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return v, err - } - if kv, err = p.unmarshalSingularValue(kv, keyFD); err != nil { - return v, err - } - if err := p.consumeOptionalSeparator(); err != nil { - return v, err - } - case "value": - if err := p.checkForColon(valFD); err != nil { - return v, err - } - if vv, err = p.unmarshalSingularValue(vv, valFD); err != nil { - return v, err - } - if err := p.consumeOptionalSeparator(); err != nil { - return v, err - } - default: - p.back() - return v, p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - mv.Set(kv.MapKey(), vv) - return v, nil - default: - p.back() - return p.unmarshalSingularValue(v, fd) - } -} - -func (p *textParser) unmarshalSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == "" { - return v, p.errorf("unexpected EOF") - } - - switch fd.Kind() { - case protoreflect.BoolKind: - switch tok.value { - case "true", "1", "t", "True": - return protoreflect.ValueOfBool(true), nil - case "false", "0", "f", "False": - return protoreflect.ValueOfBool(false), nil - } - case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfInt32(int32(x)), nil - } - - // The C++ parser accepts large positive hex numbers that uses - // two's complement arithmetic to represent negative numbers. - // This feature is here for backwards compatibility with C++. - if strings.HasPrefix(tok.value, "0x") { - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfInt32(int32(-(int64(^x) + 1))), nil - } - } - case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - return protoreflect.ValueOfInt64(int64(x)), nil - } - - // The C++ parser accepts large positive hex numbers that uses - // two's complement arithmetic to represent negative numbers. - // This feature is here for backwards compatibility with C++. - if strings.HasPrefix(tok.value, "0x") { - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - return protoreflect.ValueOfInt64(int64(-(int64(^x) + 1))), nil - } - } - case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfUint32(uint32(x)), nil - } - case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - return protoreflect.ValueOfUint64(uint64(x)), nil - } - case protoreflect.FloatKind: - // Ignore 'f' for compatibility with output generated by C++, - // but don't remove 'f' when the value is "-inf" or "inf". - v := tok.value - if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" { - v = v[:len(v)-len("f")] - } - if x, err := strconv.ParseFloat(v, 32); err == nil { - return protoreflect.ValueOfFloat32(float32(x)), nil - } - case protoreflect.DoubleKind: - // Ignore 'f' for compatibility with output generated by C++, - // but don't remove 'f' when the value is "-inf" or "inf". - v := tok.value - if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" { - v = v[:len(v)-len("f")] - } - if x, err := strconv.ParseFloat(v, 64); err == nil { - return protoreflect.ValueOfFloat64(float64(x)), nil - } - case protoreflect.StringKind: - if isQuote(tok.value[0]) { - return protoreflect.ValueOfString(tok.unquoted), nil - } - case protoreflect.BytesKind: - if isQuote(tok.value[0]) { - return protoreflect.ValueOfBytes([]byte(tok.unquoted)), nil - } - case protoreflect.EnumKind: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfEnum(protoreflect.EnumNumber(x)), nil - } - vd := fd.Enum().Values().ByName(protoreflect.Name(tok.value)) - if vd != nil { - return protoreflect.ValueOfEnum(vd.Number()), nil - } - case protoreflect.MessageKind, protoreflect.GroupKind: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return v, p.errorf("expected '{' or '<', found %q", tok.value) - } - err := p.unmarshalMessage(v.Message(), terminator) - return v, err - default: - panic(fmt.Sprintf("invalid kind %v", fd.Kind())) - } - return v, p.errorf("invalid %v: %v", fd.Kind(), tok.value) -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(fd protoreflect.FieldDescriptor) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - if fd.Message() == nil { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -// consumeExtensionOrAnyName consumes an extension name or an Any type URL and -// the following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtensionOrAnyName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in unmarshalMessage to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -var errBadUTF8 = errors.New("proto: bad UTF-8") - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(rune(i)), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} diff --git a/vendor/github.com/golang/protobuf/proto/text_encode.go b/vendor/github.com/golang/protobuf/proto/text_encode.go deleted file mode 100644 index a31134ee..00000000 --- a/vendor/github.com/golang/protobuf/proto/text_encode.go +++ /dev/null @@ -1,560 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "bytes" - "encoding" - "fmt" - "io" - "math" - "sort" - "strings" - - "google.golang.org/protobuf/encoding/prototext" - "google.golang.org/protobuf/encoding/protowire" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" -) - -const wrapTextMarshalV2 = false - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line) - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes the proto text format of m to w. -func (tm *TextMarshaler) Marshal(w io.Writer, m Message) error { - b, err := tm.marshal(m) - if len(b) > 0 { - if _, err := w.Write(b); err != nil { - return err - } - } - return err -} - -// Text returns a proto text formatted string of m. -func (tm *TextMarshaler) Text(m Message) string { - b, _ := tm.marshal(m) - return string(b) -} - -func (tm *TextMarshaler) marshal(m Message) ([]byte, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return []byte(""), nil - } - - if wrapTextMarshalV2 { - if m, ok := m.(encoding.TextMarshaler); ok { - return m.MarshalText() - } - - opts := prototext.MarshalOptions{ - AllowPartial: true, - EmitUnknown: true, - } - if !tm.Compact { - opts.Indent = " " - } - if !tm.ExpandAny { - opts.Resolver = (*protoregistry.Types)(nil) - } - return opts.Marshal(mr.Interface()) - } else { - w := &textWriter{ - compact: tm.Compact, - expandAny: tm.ExpandAny, - complete: true, - } - - if m, ok := m.(encoding.TextMarshaler); ok { - b, err := m.MarshalText() - if err != nil { - return nil, err - } - w.Write(b) - return w.buf, nil - } - - err := w.writeMessage(mr) - return w.buf, err - } -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// MarshalText writes the proto text format of m to w. -func MarshalText(w io.Writer, m Message) error { return defaultTextMarshaler.Marshal(w, m) } - -// MarshalTextString returns a proto text formatted string of m. -func MarshalTextString(m Message) string { return defaultTextMarshaler.Text(m) } - -// CompactText writes the compact proto text format of m to w. -func CompactText(w io.Writer, m Message) error { return compactTextMarshaler.Marshal(w, m) } - -// CompactTextString returns a compact proto text formatted string of m. -func CompactTextString(m Message) string { return compactTextMarshaler.Text(m) } - -var ( - newline = []byte("\n") - endBraceNewline = []byte("}\n") - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - compact bool // same as TextMarshaler.Compact - expandAny bool // same as TextMarshaler.ExpandAny - complete bool // whether the current position is a complete line - indent int // indentation level; never negative - buf []byte -} - -func (w *textWriter) Write(p []byte) (n int, _ error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - w.buf = append(w.buf, p...) - w.complete = false - return len(p), nil - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - w.buf = append(w.buf, ' ') - n++ - } - w.buf = append(w.buf, frag...) - n += len(frag) - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - w.buf = append(w.buf, frag...) - n += len(frag) - if i+1 < len(frags) { - w.buf = append(w.buf, '\n') - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - w.buf = append(w.buf, c) - w.complete = c == '\n' - return nil -} - -func (w *textWriter) writeName(fd protoreflect.FieldDescriptor) { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - - if fd.Kind() != protoreflect.GroupKind { - w.buf = append(w.buf, fd.Name()...) - w.WriteByte(':') - } else { - // Use message type name for group field name. - w.buf = append(w.buf, fd.Message().Name()...) - } - - if !w.compact { - w.WriteByte(' ') - } -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (w *textWriter) writeProto3Any(m protoreflect.Message) (bool, error) { - md := m.Descriptor() - fdURL := md.Fields().ByName("type_url") - fdVal := md.Fields().ByName("value") - - url := m.Get(fdURL).String() - mt, err := protoregistry.GlobalTypes.FindMessageByURL(url) - if err != nil { - return false, nil - } - - b := m.Get(fdVal).Bytes() - m2 := mt.New() - if err := proto.Unmarshal(b, m2.Interface()); err != nil { - return false, nil - } - w.Write([]byte("[")) - if requiresQuotes(url) { - w.writeQuotedString(url) - } else { - w.Write([]byte(url)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.indent++ - } - if err := w.writeMessage(m2); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.indent-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (w *textWriter) writeMessage(m protoreflect.Message) error { - md := m.Descriptor() - if w.expandAny && md.FullName() == "google.protobuf.Any" { - if canExpand, err := w.writeProto3Any(m); canExpand { - return err - } - } - - fds := md.Fields() - for i := 0; i < fds.Len(); { - fd := fds.Get(i) - if od := fd.ContainingOneof(); od != nil { - fd = m.WhichOneof(od) - i += od.Fields().Len() - } else { - i++ - } - if fd == nil || !m.Has(fd) { - continue - } - - switch { - case fd.IsList(): - lv := m.Get(fd).List() - for j := 0; j < lv.Len(); j++ { - w.writeName(fd) - v := lv.Get(j) - if err := w.writeSingularValue(v, fd); err != nil { - return err - } - w.WriteByte('\n') - } - case fd.IsMap(): - kfd := fd.MapKey() - vfd := fd.MapValue() - mv := m.Get(fd).Map() - - type entry struct{ key, val protoreflect.Value } - var entries []entry - mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { - entries = append(entries, entry{k.Value(), v}) - return true - }) - sort.Slice(entries, func(i, j int) bool { - switch kfd.Kind() { - case protoreflect.BoolKind: - return !entries[i].key.Bool() && entries[j].key.Bool() - case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: - return entries[i].key.Int() < entries[j].key.Int() - case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind: - return entries[i].key.Uint() < entries[j].key.Uint() - case protoreflect.StringKind: - return entries[i].key.String() < entries[j].key.String() - default: - panic("invalid kind") - } - }) - for _, entry := range entries { - w.writeName(fd) - w.WriteByte('<') - if !w.compact { - w.WriteByte('\n') - } - w.indent++ - w.writeName(kfd) - if err := w.writeSingularValue(entry.key, kfd); err != nil { - return err - } - w.WriteByte('\n') - w.writeName(vfd) - if err := w.writeSingularValue(entry.val, vfd); err != nil { - return err - } - w.WriteByte('\n') - w.indent-- - w.WriteByte('>') - w.WriteByte('\n') - } - default: - w.writeName(fd) - if err := w.writeSingularValue(m.Get(fd), fd); err != nil { - return err - } - w.WriteByte('\n') - } - } - - if b := m.GetUnknown(); len(b) > 0 { - w.writeUnknownFields(b) - } - return w.writeExtensions(m) -} - -func (w *textWriter) writeSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) error { - switch fd.Kind() { - case protoreflect.FloatKind, protoreflect.DoubleKind: - switch vf := v.Float(); { - case math.IsInf(vf, +1): - w.Write(posInf) - case math.IsInf(vf, -1): - w.Write(negInf) - case math.IsNaN(vf): - w.Write(nan) - default: - fmt.Fprint(w, v.Interface()) - } - case protoreflect.StringKind: - // NOTE: This does not validate UTF-8 for historical reasons. - w.writeQuotedString(string(v.String())) - case protoreflect.BytesKind: - w.writeQuotedString(string(v.Bytes())) - case protoreflect.MessageKind, protoreflect.GroupKind: - var bra, ket byte = '<', '>' - if fd.Kind() == protoreflect.GroupKind { - bra, ket = '{', '}' - } - w.WriteByte(bra) - if !w.compact { - w.WriteByte('\n') - } - w.indent++ - m := v.Message() - if m2, ok := m.Interface().(encoding.TextMarshaler); ok { - b, err := m2.MarshalText() - if err != nil { - return err - } - w.Write(b) - } else { - w.writeMessage(m) - } - w.indent-- - w.WriteByte(ket) - case protoreflect.EnumKind: - if ev := fd.Enum().Values().ByNumber(v.Enum()); ev != nil { - fmt.Fprint(w, ev.Name()) - } else { - fmt.Fprint(w, v.Enum()) - } - default: - fmt.Fprint(w, v.Interface()) - } - return nil -} - -// writeQuotedString writes a quoted string in the protocol buffer text format. -func (w *textWriter) writeQuotedString(s string) { - w.WriteByte('"') - for i := 0; i < len(s); i++ { - switch c := s[i]; c { - case '\n': - w.buf = append(w.buf, `\n`...) - case '\r': - w.buf = append(w.buf, `\r`...) - case '\t': - w.buf = append(w.buf, `\t`...) - case '"': - w.buf = append(w.buf, `\"`...) - case '\\': - w.buf = append(w.buf, `\\`...) - default: - if isPrint := c >= 0x20 && c < 0x7f; isPrint { - w.buf = append(w.buf, c) - } else { - w.buf = append(w.buf, fmt.Sprintf(`\%03o`, c)...) - } - } - } - w.WriteByte('"') -} - -func (w *textWriter) writeUnknownFields(b []byte) { - if !w.compact { - fmt.Fprintf(w, "/* %d unknown bytes */\n", len(b)) - } - - for len(b) > 0 { - num, wtyp, n := protowire.ConsumeTag(b) - if n < 0 { - return - } - b = b[n:] - - if wtyp == protowire.EndGroupType { - w.indent-- - w.Write(endBraceNewline) - continue - } - fmt.Fprint(w, num) - if wtyp != protowire.StartGroupType { - w.WriteByte(':') - } - if !w.compact || wtyp == protowire.StartGroupType { - w.WriteByte(' ') - } - switch wtyp { - case protowire.VarintType: - v, n := protowire.ConsumeVarint(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprint(w, v) - case protowire.Fixed32Type: - v, n := protowire.ConsumeFixed32(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprint(w, v) - case protowire.Fixed64Type: - v, n := protowire.ConsumeFixed64(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprint(w, v) - case protowire.BytesType: - v, n := protowire.ConsumeBytes(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprintf(w, "%q", v) - case protowire.StartGroupType: - w.WriteByte('{') - w.indent++ - default: - fmt.Fprintf(w, "/* unknown wire type %d */", wtyp) - } - w.WriteByte('\n') - } -} - -// writeExtensions writes all the extensions in m. -func (w *textWriter) writeExtensions(m protoreflect.Message) error { - md := m.Descriptor() - if md.ExtensionRanges().Len() == 0 { - return nil - } - - type ext struct { - desc protoreflect.FieldDescriptor - val protoreflect.Value - } - var exts []ext - m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - if fd.IsExtension() { - exts = append(exts, ext{fd, v}) - } - return true - }) - sort.Slice(exts, func(i, j int) bool { - return exts[i].desc.Number() < exts[j].desc.Number() - }) - - for _, ext := range exts { - // For message set, use the name of the message as the extension name. - name := string(ext.desc.FullName()) - if isMessageSet(ext.desc.ContainingMessage()) { - name = strings.TrimSuffix(name, ".message_set_extension") - } - - if !ext.desc.IsList() { - if err := w.writeSingularExtension(name, ext.val, ext.desc); err != nil { - return err - } - } else { - lv := ext.val.List() - for i := 0; i < lv.Len(); i++ { - if err := w.writeSingularExtension(name, lv.Get(i), ext.desc); err != nil { - return err - } - } - } - } - return nil -} - -func (w *textWriter) writeSingularExtension(name string, v protoreflect.Value, fd protoreflect.FieldDescriptor) error { - fmt.Fprintf(w, "[%s]:", name) - if !w.compact { - w.WriteByte(' ') - } - if err := w.writeSingularValue(v, fd); err != nil { - return err - } - w.WriteByte('\n') - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - for i := 0; i < w.indent*2; i++ { - w.buf = append(w.buf, ' ') - } - w.complete = false -} diff --git a/vendor/github.com/golang/protobuf/proto/wire.go b/vendor/github.com/golang/protobuf/proto/wire.go deleted file mode 100644 index d7c28da5..00000000 --- a/vendor/github.com/golang/protobuf/proto/wire.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/runtime/protoiface" -) - -// Size returns the size in bytes of the wire-format encoding of m. -func Size(m Message) int { - if m == nil { - return 0 - } - mi := MessageV2(m) - return protoV2.Size(mi) -} - -// Marshal returns the wire-format encoding of m. -func Marshal(m Message) ([]byte, error) { - b, err := marshalAppend(nil, m, false) - if b == nil { - b = zeroBytes - } - return b, err -} - -var zeroBytes = make([]byte, 0, 0) - -func marshalAppend(buf []byte, m Message, deterministic bool) ([]byte, error) { - if m == nil { - return nil, ErrNil - } - mi := MessageV2(m) - nbuf, err := protoV2.MarshalOptions{ - Deterministic: deterministic, - AllowPartial: true, - }.MarshalAppend(buf, mi) - if err != nil { - return buf, err - } - if len(buf) == len(nbuf) { - if !mi.ProtoReflect().IsValid() { - return buf, ErrNil - } - } - return nbuf, checkRequiredNotSet(mi) -} - -// Unmarshal parses a wire-format message in b and places the decoded results in m. -// -// Unmarshal resets m before starting to unmarshal, so any existing data in m is always -// removed. Use UnmarshalMerge to preserve and append to existing data. -func Unmarshal(b []byte, m Message) error { - m.Reset() - return UnmarshalMerge(b, m) -} - -// UnmarshalMerge parses a wire-format message in b and places the decoded results in m. -func UnmarshalMerge(b []byte, m Message) error { - mi := MessageV2(m) - out, err := protoV2.UnmarshalOptions{ - AllowPartial: true, - Merge: true, - }.UnmarshalState(protoiface.UnmarshalInput{ - Buf: b, - Message: mi.ProtoReflect(), - }) - if err != nil { - return err - } - if out.Flags&protoiface.UnmarshalInitialized > 0 { - return nil - } - return checkRequiredNotSet(mi) -} diff --git a/vendor/github.com/golang/protobuf/proto/wrappers.go b/vendor/github.com/golang/protobuf/proto/wrappers.go deleted file mode 100644 index 398e3485..00000000 --- a/vendor/github.com/golang/protobuf/proto/wrappers.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -// Bool stores v in a new bool value and returns a pointer to it. -func Bool(v bool) *bool { return &v } - -// Int stores v in a new int32 value and returns a pointer to it. -// -// Deprecated: Use Int32 instead. -func Int(v int) *int32 { return Int32(int32(v)) } - -// Int32 stores v in a new int32 value and returns a pointer to it. -func Int32(v int32) *int32 { return &v } - -// Int64 stores v in a new int64 value and returns a pointer to it. -func Int64(v int64) *int64 { return &v } - -// Uint32 stores v in a new uint32 value and returns a pointer to it. -func Uint32(v uint32) *uint32 { return &v } - -// Uint64 stores v in a new uint64 value and returns a pointer to it. -func Uint64(v uint64) *uint64 { return &v } - -// Float32 stores v in a new float32 value and returns a pointer to it. -func Float32(v float32) *float32 { return &v } - -// Float64 stores v in a new float64 value and returns a pointer to it. -func Float64(v float64) *float64 { return &v } - -// String stores v in a new string value and returns a pointer to it. -func String(v string) *string { return &v } diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go deleted file mode 100644 index 85f9f573..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/any.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ptypes - -import ( - "fmt" - "strings" - - "github.com/golang/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - - anypb "github.com/golang/protobuf/ptypes/any" -) - -const urlPrefix = "type.googleapis.com/" - -// AnyMessageName returns the message name contained in an anypb.Any message. -// Most type assertions should use the Is function instead. -// -// Deprecated: Call the any.MessageName method instead. -func AnyMessageName(any *anypb.Any) (string, error) { - name, err := anyMessageName(any) - return string(name), err -} -func anyMessageName(any *anypb.Any) (protoreflect.FullName, error) { - if any == nil { - return "", fmt.Errorf("message is nil") - } - name := protoreflect.FullName(any.TypeUrl) - if i := strings.LastIndex(any.TypeUrl, "/"); i >= 0 { - name = name[i+len("/"):] - } - if !name.IsValid() { - return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl) - } - return name, nil -} - -// MarshalAny marshals the given message m into an anypb.Any message. -// -// Deprecated: Call the anypb.New function instead. -func MarshalAny(m proto.Message) (*anypb.Any, error) { - switch dm := m.(type) { - case DynamicAny: - m = dm.Message - case *DynamicAny: - if dm == nil { - return nil, proto.ErrNil - } - m = dm.Message - } - b, err := proto.Marshal(m) - if err != nil { - return nil, err - } - return &anypb.Any{TypeUrl: urlPrefix + proto.MessageName(m), Value: b}, nil -} - -// Empty returns a new message of the type specified in an anypb.Any message. -// It returns protoregistry.NotFound if the corresponding message type could not -// be resolved in the global registry. -// -// Deprecated: Use protoregistry.GlobalTypes.FindMessageByName instead -// to resolve the message name and create a new instance of it. -func Empty(any *anypb.Any) (proto.Message, error) { - name, err := anyMessageName(any) - if err != nil { - return nil, err - } - mt, err := protoregistry.GlobalTypes.FindMessageByName(name) - if err != nil { - return nil, err - } - return proto.MessageV1(mt.New().Interface()), nil -} - -// UnmarshalAny unmarshals the encoded value contained in the anypb.Any message -// into the provided message m. It returns an error if the target message -// does not match the type in the Any message or if an unmarshal error occurs. -// -// The target message m may be a *DynamicAny message. If the underlying message -// type could not be resolved, then this returns protoregistry.NotFound. -// -// Deprecated: Call the any.UnmarshalTo method instead. -func UnmarshalAny(any *anypb.Any, m proto.Message) error { - if dm, ok := m.(*DynamicAny); ok { - if dm.Message == nil { - var err error - dm.Message, err = Empty(any) - if err != nil { - return err - } - } - m = dm.Message - } - - anyName, err := AnyMessageName(any) - if err != nil { - return err - } - msgName := proto.MessageName(m) - if anyName != msgName { - return fmt.Errorf("mismatched message type: got %q want %q", anyName, msgName) - } - return proto.Unmarshal(any.Value, m) -} - -// Is reports whether the Any message contains a message of the specified type. -// -// Deprecated: Call the any.MessageIs method instead. -func Is(any *anypb.Any, m proto.Message) bool { - if any == nil || m == nil { - return false - } - name := proto.MessageName(m) - if !strings.HasSuffix(any.TypeUrl, name) { - return false - } - return len(any.TypeUrl) == len(name) || any.TypeUrl[len(any.TypeUrl)-len(name)-1] == '/' -} - -// DynamicAny is a value that can be passed to UnmarshalAny to automatically -// allocate a proto.Message for the type specified in an anypb.Any message. -// The allocated message is stored in the embedded proto.Message. -// -// Example: -// var x ptypes.DynamicAny -// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } -// fmt.Printf("unmarshaled message: %v", x.Message) -// -// Deprecated: Use the any.UnmarshalNew method instead to unmarshal -// the any message contents into a new instance of the underlying message. -type DynamicAny struct{ proto.Message } - -func (m DynamicAny) String() string { - if m.Message == nil { - return "" - } - return m.Message.String() -} -func (m DynamicAny) Reset() { - if m.Message == nil { - return - } - m.Message.Reset() -} -func (m DynamicAny) ProtoMessage() { - return -} -func (m DynamicAny) ProtoReflect() protoreflect.Message { - if m.Message == nil { - return nil - } - return dynamicAny{proto.MessageReflect(m.Message)} -} - -type dynamicAny struct{ protoreflect.Message } - -func (m dynamicAny) Type() protoreflect.MessageType { - return dynamicAnyType{m.Message.Type()} -} -func (m dynamicAny) New() protoreflect.Message { - return dynamicAnyType{m.Message.Type()}.New() -} -func (m dynamicAny) Interface() protoreflect.ProtoMessage { - return DynamicAny{proto.MessageV1(m.Message.Interface())} -} - -type dynamicAnyType struct{ protoreflect.MessageType } - -func (t dynamicAnyType) New() protoreflect.Message { - return dynamicAny{t.MessageType.New()} -} -func (t dynamicAnyType) Zero() protoreflect.Message { - return dynamicAny{t.MessageType.Zero()} -} diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go deleted file mode 100644 index 0ef27d33..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/golang/protobuf/ptypes/any/any.proto - -package any - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - anypb "google.golang.org/protobuf/types/known/anypb" - reflect "reflect" -) - -// Symbols defined in public import of google/protobuf/any.proto. - -type Any = anypb.Any - -var File_github_com_golang_protobuf_ptypes_any_any_proto protoreflect.FileDescriptor - -var file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = []byte{ - 0x0a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x2b, 0x5a, 0x29, - 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, - 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, - 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x3b, 0x61, 0x6e, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x33, -} - -var file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = []interface{}{} -var file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_github_com_golang_protobuf_ptypes_any_any_proto_init() } -func file_github_com_golang_protobuf_ptypes_any_any_proto_init() { - if File_github_com_golang_protobuf_ptypes_any_any_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc, - NumEnums: 0, - NumMessages: 0, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes, - DependencyIndexes: file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs, - }.Build() - File_github_com_golang_protobuf_ptypes_any_any_proto = out.File - file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = nil - file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = nil - file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = nil -} diff --git a/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/golang/protobuf/ptypes/doc.go deleted file mode 100644 index d3c33259..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ptypes provides functionality for interacting with well-known types. -// -// Deprecated: Well-known types have specialized functionality directly -// injected into the generated packages for each message type. -// See the deprecation notice for each function for the suggested alternative. -package ptypes diff --git a/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/golang/protobuf/ptypes/duration.go deleted file mode 100644 index b2b55dd8..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ptypes - -import ( - "errors" - "fmt" - "time" - - durationpb "github.com/golang/protobuf/ptypes/duration" -) - -// Range of google.protobuf.Duration as specified in duration.proto. -// This is about 10,000 years in seconds. -const ( - maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) - minSeconds = -maxSeconds -) - -// Duration converts a durationpb.Duration to a time.Duration. -// Duration returns an error if dur is invalid or overflows a time.Duration. -// -// Deprecated: Call the dur.AsDuration and dur.CheckValid methods instead. -func Duration(dur *durationpb.Duration) (time.Duration, error) { - if err := validateDuration(dur); err != nil { - return 0, err - } - d := time.Duration(dur.Seconds) * time.Second - if int64(d/time.Second) != dur.Seconds { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur) - } - if dur.Nanos != 0 { - d += time.Duration(dur.Nanos) * time.Nanosecond - if (d < 0) != (dur.Nanos < 0) { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur) - } - } - return d, nil -} - -// DurationProto converts a time.Duration to a durationpb.Duration. -// -// Deprecated: Call the durationpb.New function instead. -func DurationProto(d time.Duration) *durationpb.Duration { - nanos := d.Nanoseconds() - secs := nanos / 1e9 - nanos -= secs * 1e9 - return &durationpb.Duration{ - Seconds: int64(secs), - Nanos: int32(nanos), - } -} - -// validateDuration determines whether the durationpb.Duration is valid -// according to the definition in google/protobuf/duration.proto. -// A valid durpb.Duration may still be too large to fit into a time.Duration -// Note that the range of durationpb.Duration is about 10,000 years, -// while the range of time.Duration is about 290 years. -func validateDuration(dur *durationpb.Duration) error { - if dur == nil { - return errors.New("duration: nil Duration") - } - if dur.Seconds < minSeconds || dur.Seconds > maxSeconds { - return fmt.Errorf("duration: %v: seconds out of range", dur) - } - if dur.Nanos <= -1e9 || dur.Nanos >= 1e9 { - return fmt.Errorf("duration: %v: nanos out of range", dur) - } - // Seconds and Nanos must have the same sign, unless d.Nanos is zero. - if (dur.Seconds < 0 && dur.Nanos > 0) || (dur.Seconds > 0 && dur.Nanos < 0) { - return fmt.Errorf("duration: %v: seconds and nanos have different signs", dur) - } - return nil -} diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go deleted file mode 100644 index d0079ee3..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/golang/protobuf/ptypes/duration/duration.proto - -package duration - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - durationpb "google.golang.org/protobuf/types/known/durationpb" - reflect "reflect" -) - -// Symbols defined in public import of google/protobuf/duration.proto. - -type Duration = durationpb.Duration - -var File_github_com_golang_protobuf_ptypes_duration_duration_proto protoreflect.FileDescriptor - -var file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = []byte{ - 0x0a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x64, 0x75, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x35, 0x5a, 0x33, 0x67, - 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, - 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = []interface{}{} -var file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() } -func file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() { - if File_github_com_golang_protobuf_ptypes_duration_duration_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc, - NumEnums: 0, - NumMessages: 0, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes, - DependencyIndexes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs, - }.Build() - File_github_com_golang_protobuf_ptypes_duration_duration_proto = out.File - file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = nil - file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = nil - file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = nil -} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go deleted file mode 100644 index 8368a3f7..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ptypes - -import ( - "errors" - "fmt" - "time" - - timestamppb "github.com/golang/protobuf/ptypes/timestamp" -) - -// Range of google.protobuf.Duration as specified in timestamp.proto. -const ( - // Seconds field of the earliest valid Timestamp. - // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - minValidSeconds = -62135596800 - // Seconds field just after the latest valid Timestamp. - // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - maxValidSeconds = 253402300800 -) - -// Timestamp converts a timestamppb.Timestamp to a time.Time. -// It returns an error if the argument is invalid. -// -// Unlike most Go functions, if Timestamp returns an error, the first return -// value is not the zero time.Time. Instead, it is the value obtained from the -// time.Unix function when passed the contents of the Timestamp, in the UTC -// locale. This may or may not be a meaningful time; many invalid Timestamps -// do map to valid time.Times. -// -// A nil Timestamp returns an error. The first return value in that case is -// undefined. -// -// Deprecated: Call the ts.AsTime and ts.CheckValid methods instead. -func Timestamp(ts *timestamppb.Timestamp) (time.Time, error) { - // Don't return the zero value on error, because corresponds to a valid - // timestamp. Instead return whatever time.Unix gives us. - var t time.Time - if ts == nil { - t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp - } else { - t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() - } - return t, validateTimestamp(ts) -} - -// TimestampNow returns a google.protobuf.Timestamp for the current time. -// -// Deprecated: Call the timestamppb.Now function instead. -func TimestampNow() *timestamppb.Timestamp { - ts, err := TimestampProto(time.Now()) - if err != nil { - panic("ptypes: time.Now() out of Timestamp range") - } - return ts -} - -// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. -// It returns an error if the resulting Timestamp is invalid. -// -// Deprecated: Call the timestamppb.New function instead. -func TimestampProto(t time.Time) (*timestamppb.Timestamp, error) { - ts := ×tamppb.Timestamp{ - Seconds: t.Unix(), - Nanos: int32(t.Nanosecond()), - } - if err := validateTimestamp(ts); err != nil { - return nil, err - } - return ts, nil -} - -// TimestampString returns the RFC 3339 string for valid Timestamps. -// For invalid Timestamps, it returns an error message in parentheses. -// -// Deprecated: Call the ts.AsTime method instead, -// followed by a call to the Format method on the time.Time value. -func TimestampString(ts *timestamppb.Timestamp) string { - t, err := Timestamp(ts) - if err != nil { - return fmt.Sprintf("(%v)", err) - } - return t.Format(time.RFC3339Nano) -} - -// validateTimestamp determines whether a Timestamp is valid. -// A valid timestamp represents a time in the range [0001-01-01, 10000-01-01) -// and has a Nanos field in the range [0, 1e9). -// -// If the Timestamp is valid, validateTimestamp returns nil. -// Otherwise, it returns an error that describes the problem. -// -// Every valid Timestamp can be represented by a time.Time, -// but the converse is not true. -func validateTimestamp(ts *timestamppb.Timestamp) error { - if ts == nil { - return errors.New("timestamp: nil Timestamp") - } - if ts.Seconds < minValidSeconds { - return fmt.Errorf("timestamp: %v before 0001-01-01", ts) - } - if ts.Seconds >= maxValidSeconds { - return fmt.Errorf("timestamp: %v after 10000-01-01", ts) - } - if ts.Nanos < 0 || ts.Nanos >= 1e9 { - return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) - } - return nil -} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go deleted file mode 100644 index a76f8076..00000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/golang/protobuf/ptypes/timestamp/timestamp.proto - -package timestamp - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - timestamppb "google.golang.org/protobuf/types/known/timestamppb" - reflect "reflect" -) - -// Symbols defined in public import of google/protobuf/timestamp.proto. - -type Timestamp = timestamppb.Timestamp - -var File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto protoreflect.FileDescriptor - -var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = []byte{ - 0x0a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2f, 0x74, 0x69, - 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x37, - 0x5a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x3b, 0x74, 0x69, - 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x33, -} - -var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = []interface{}{} -var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() } -func file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() { - if File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc, - NumEnums: 0, - NumMessages: 0, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes, - DependencyIndexes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs, - }.Build() - File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto = out.File - file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = nil - file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = nil - file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = nil -} diff --git a/vendor/github.com/gopherjs/gopherjs/LICENSE b/vendor/github.com/gopherjs/gopherjs/LICENSE deleted file mode 100644 index d496fef1..00000000 --- a/vendor/github.com/gopherjs/gopherjs/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2013 Richard Musiol. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gopherjs/gopherjs/js/js.go b/vendor/github.com/gopherjs/gopherjs/js/js.go deleted file mode 100644 index 3fbf1d88..00000000 --- a/vendor/github.com/gopherjs/gopherjs/js/js.go +++ /dev/null @@ -1,168 +0,0 @@ -// Package js provides functions for interacting with native JavaScript APIs. Calls to these functions are treated specially by GopherJS and translated directly to their corresponding JavaScript syntax. -// -// Use MakeWrapper to expose methods to JavaScript. When passing values directly, the following type conversions are performed: -// -// | Go type | JavaScript type | Conversions back to interface{} | -// | --------------------- | --------------------- | ------------------------------- | -// | bool | Boolean | bool | -// | integers and floats | Number | float64 | -// | string | String | string | -// | []int8 | Int8Array | []int8 | -// | []int16 | Int16Array | []int16 | -// | []int32, []int | Int32Array | []int | -// | []uint8 | Uint8Array | []uint8 | -// | []uint16 | Uint16Array | []uint16 | -// | []uint32, []uint | Uint32Array | []uint | -// | []float32 | Float32Array | []float32 | -// | []float64 | Float64Array | []float64 | -// | all other slices | Array | []interface{} | -// | arrays | see slice type | see slice type | -// | functions | Function | func(...interface{}) *js.Object | -// | time.Time | Date | time.Time | -// | - | instanceof Node | *js.Object | -// | maps, structs | instanceof Object | map[string]interface{} | -// -// Additionally, for a struct containing a *js.Object field, only the content of the field will be passed to JavaScript and vice versa. -package js - -// Object is a container for a native JavaScript object. Calls to its methods are treated specially by GopherJS and translated directly to their JavaScript syntax. A nil pointer to Object is equal to JavaScript's "null". Object can not be used as a map key. -type Object struct{ object *Object } - -// Get returns the object's property with the given key. -func (o *Object) Get(key string) *Object { return o.object.Get(key) } - -// Set assigns the value to the object's property with the given key. -func (o *Object) Set(key string, value interface{}) { o.object.Set(key, value) } - -// Delete removes the object's property with the given key. -func (o *Object) Delete(key string) { o.object.Delete(key) } - -// Length returns the object's "length" property, converted to int. -func (o *Object) Length() int { return o.object.Length() } - -// Index returns the i'th element of an array. -func (o *Object) Index(i int) *Object { return o.object.Index(i) } - -// SetIndex sets the i'th element of an array. -func (o *Object) SetIndex(i int, value interface{}) { o.object.SetIndex(i, value) } - -// Call calls the object's method with the given name. -func (o *Object) Call(name string, args ...interface{}) *Object { return o.object.Call(name, args...) } - -// Invoke calls the object itself. This will fail if it is not a function. -func (o *Object) Invoke(args ...interface{}) *Object { return o.object.Invoke(args...) } - -// New creates a new instance of this type object. This will fail if it not a function (constructor). -func (o *Object) New(args ...interface{}) *Object { return o.object.New(args...) } - -// Bool returns the object converted to bool according to JavaScript type conversions. -func (o *Object) Bool() bool { return o.object.Bool() } - -// String returns the object converted to string according to JavaScript type conversions. -func (o *Object) String() string { return o.object.String() } - -// Int returns the object converted to int according to JavaScript type conversions (parseInt). -func (o *Object) Int() int { return o.object.Int() } - -// Int64 returns the object converted to int64 according to JavaScript type conversions (parseInt). -func (o *Object) Int64() int64 { return o.object.Int64() } - -// Uint64 returns the object converted to uint64 according to JavaScript type conversions (parseInt). -func (o *Object) Uint64() uint64 { return o.object.Uint64() } - -// Float returns the object converted to float64 according to JavaScript type conversions (parseFloat). -func (o *Object) Float() float64 { return o.object.Float() } - -// Interface returns the object converted to interface{}. See table in package comment for details. -func (o *Object) Interface() interface{} { return o.object.Interface() } - -// Unsafe returns the object as an uintptr, which can be converted via unsafe.Pointer. Not intended for public use. -func (o *Object) Unsafe() uintptr { return o.object.Unsafe() } - -// Error encapsulates JavaScript errors. Those are turned into a Go panic and may be recovered, giving an *Error that holds the JavaScript error object. -type Error struct { - *Object -} - -// Error returns the message of the encapsulated JavaScript error object. -func (err *Error) Error() string { - return "JavaScript error: " + err.Get("message").String() -} - -// Stack returns the stack property of the encapsulated JavaScript error object. -func (err *Error) Stack() string { - return err.Get("stack").String() -} - -// Global gives JavaScript's global object ("window" for browsers and "GLOBAL" for Node.js). -var Global *Object - -// Module gives the value of the "module" variable set by Node.js. Hint: Set a module export with 'js.Module.Get("exports").Set("exportName", ...)'. -var Module *Object - -// Undefined gives the JavaScript value "undefined". -var Undefined *Object - -// Debugger gets compiled to JavaScript's "debugger;" statement. -func Debugger() {} - -// InternalObject returns the internal JavaScript object that represents i. Not intended for public use. -func InternalObject(i interface{}) *Object { - return nil -} - -// MakeFunc wraps a function and gives access to the values of JavaScript's "this" and "arguments" keywords. -func MakeFunc(fn func(this *Object, arguments []*Object) interface{}) *Object { - return Global.Call("$makeFunc", InternalObject(fn)) -} - -// Keys returns the keys of the given JavaScript object. -func Keys(o *Object) []string { - if o == nil || o == Undefined { - return nil - } - a := Global.Get("Object").Call("keys", o) - s := make([]string, a.Length()) - for i := 0; i < a.Length(); i++ { - s[i] = a.Index(i).String() - } - return s -} - -// MakeWrapper creates a JavaScript object which has wrappers for the exported methods of i. Use explicit getter and setter methods to expose struct fields to JavaScript. -func MakeWrapper(i interface{}) *Object { - v := InternalObject(i) - o := Global.Get("Object").New() - o.Set("__internal_object__", v) - methods := v.Get("constructor").Get("methods") - for i := 0; i < methods.Length(); i++ { - m := methods.Index(i) - if m.Get("pkg").String() != "" { // not exported - continue - } - o.Set(m.Get("name").String(), func(args ...*Object) *Object { - return Global.Call("$externalizeFunction", v.Get(m.Get("prop").String()), m.Get("typ"), true).Call("apply", v, args) - }) - } - return o -} - -// NewArrayBuffer creates a JavaScript ArrayBuffer from a byte slice. -func NewArrayBuffer(b []byte) *Object { - slice := InternalObject(b) - offset := slice.Get("$offset").Int() - length := slice.Get("$length").Int() - return slice.Get("$array").Get("buffer").Call("slice", offset, offset+length) -} - -// M is a simple map type. It is intended as a shorthand for JavaScript objects (before conversion). -type M map[string]interface{} - -// S is a simple slice type. It is intended as a shorthand for JavaScript arrays (before conversion). -type S []interface{} - -func init() { - // avoid dead code elimination - e := Error{} - _ = e -} diff --git a/vendor/github.com/jmespath/go-jmespath/.gitignore b/vendor/github.com/jmespath/go-jmespath/.gitignore deleted file mode 100644 index 5091fb07..00000000 --- a/vendor/github.com/jmespath/go-jmespath/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/jpgo -jmespath-fuzz.zip -cpu.out -go-jmespath.test diff --git a/vendor/github.com/jmespath/go-jmespath/.travis.yml b/vendor/github.com/jmespath/go-jmespath/.travis.yml deleted file mode 100644 index c56f37c0..00000000 --- a/vendor/github.com/jmespath/go-jmespath/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go - -sudo: false - -go: - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - 1.13.x - - 1.14.x - - 1.15.x - - tip - -allow_failures: - - go: tip - -script: make build - -matrix: - include: - - language: go - go: 1.15.x - script: make test diff --git a/vendor/github.com/jmespath/go-jmespath/LICENSE b/vendor/github.com/jmespath/go-jmespath/LICENSE deleted file mode 100644 index b03310a9..00000000 --- a/vendor/github.com/jmespath/go-jmespath/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2015 James Saryerwinnie - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/github.com/jmespath/go-jmespath/Makefile b/vendor/github.com/jmespath/go-jmespath/Makefile deleted file mode 100644 index fb38ec27..00000000 --- a/vendor/github.com/jmespath/go-jmespath/Makefile +++ /dev/null @@ -1,51 +0,0 @@ - -CMD = jpgo - -SRC_PKGS=./ ./cmd/... ./fuzz/... - -help: - @echo "Please use \`make ' where is one of" - @echo " test to run all the tests" - @echo " build to build the library and jp executable" - @echo " generate to run codegen" - - -generate: - go generate ${SRC_PKGS} - -build: - rm -f $(CMD) - go build ${SRC_PKGS} - rm -f cmd/$(CMD)/$(CMD) && cd cmd/$(CMD)/ && go build ./... - mv cmd/$(CMD)/$(CMD) . - -test: test-internal-testify - echo "making tests ${SRC_PKGS}" - go test -v ${SRC_PKGS} - -check: - go vet ${SRC_PKGS} - @echo "golint ${SRC_PKGS}" - @lint=`golint ${SRC_PKGS}`; \ - lint=`echo "$$lint" | grep -v "astnodetype_string.go" | grep -v "toktype_string.go"`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ]; then exit 1; fi - -htmlc: - go test -coverprofile="/tmp/jpcov" && go tool cover -html="/tmp/jpcov" && unlink /tmp/jpcov - -buildfuzz: - go-fuzz-build github.com/jmespath/go-jmespath/fuzz - -fuzz: buildfuzz - go-fuzz -bin=./jmespath-fuzz.zip -workdir=fuzz/testdata - -bench: - go test -bench . -cpuprofile cpu.out - -pprof-cpu: - go tool pprof ./go-jmespath.test ./cpu.out - -test-internal-testify: - cd internal/testify && go test ./... - diff --git a/vendor/github.com/jmespath/go-jmespath/README.md b/vendor/github.com/jmespath/go-jmespath/README.md deleted file mode 100644 index 110ad799..00000000 --- a/vendor/github.com/jmespath/go-jmespath/README.md +++ /dev/null @@ -1,87 +0,0 @@ -# go-jmespath - A JMESPath implementation in Go - -[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath) - - - -go-jmespath is a GO implementation of JMESPath, -which is a query language for JSON. It will take a JSON -document and transform it into another JSON document -through a JMESPath expression. - -Using go-jmespath is really easy. There's a single function -you use, `jmespath.search`: - - -```go -> import "github.com/jmespath/go-jmespath" -> -> var jsondata = []byte(`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.Search("foo.bar.baz[2]", data) -result = 2 -``` - -In the example we gave the ``search`` function input data of -`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}` as well as the JMESPath -expression `foo.bar.baz[2]`, and the `search` function evaluated -the expression against the input data to produce the result ``2``. - -The JMESPath language can do a lot more than select an element -from a list. Here are a few more examples: - -```go -> var jsondata = []byte(`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search("foo.bar", data) -result = { "baz": [ 0, 1, 2, 3, 4 ] } - - -> var jsondata = []byte(`{"foo": [{"first": "a", "last": "b"}, - {"first": "c", "last": "d"}]}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search({"foo[*].first", data) -result [ 'a', 'c' ] - - -> var jsondata = []byte(`{"foo": [{"age": 20}, {"age": 25}, - {"age": 30}, {"age": 35}, - {"age": 40}]}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search("foo[?age > `30`]") -result = [ { age: 35 }, { age: 40 } ] -``` - -You can also pre-compile your query. This is usefull if -you are going to run multiple searches with it: - -```go - > var jsondata = []byte(`{"foo": "bar"}`) - > var data interface{} - > err := json.Unmarshal(jsondata, &data) - > precompiled, err := Compile("foo") - > if err != nil{ - > // ... handle the error - > } - > result, err := precompiled.Search(data) - result = "bar" -``` - -## More Resources - -The example above only show a small amount of what -a JMESPath expression can do. If you want to take a -tour of the language, the *best* place to go is the -[JMESPath Tutorial](http://jmespath.org/tutorial.html). - -One of the best things about JMESPath is that it is -implemented in many different programming languages including -python, ruby, php, lua, etc. To see a complete list of libraries, -check out the [JMESPath libraries page](http://jmespath.org/libraries.html). - -And finally, the full JMESPath specification can be found -on the [JMESPath site](http://jmespath.org/specification.html). diff --git a/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/jmespath/go-jmespath/api.go deleted file mode 100644 index 010efe9b..00000000 --- a/vendor/github.com/jmespath/go-jmespath/api.go +++ /dev/null @@ -1,49 +0,0 @@ -package jmespath - -import "strconv" - -// JMESPath is the representation of a compiled JMES path query. A JMESPath is -// safe for concurrent use by multiple goroutines. -type JMESPath struct { - ast ASTNode - intr *treeInterpreter -} - -// Compile parses a JMESPath expression and returns, if successful, a JMESPath -// object that can be used to match against data. -func Compile(expression string) (*JMESPath, error) { - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - jmespath := &JMESPath{ast: ast, intr: newInterpreter()} - return jmespath, nil -} - -// MustCompile is like Compile but panics if the expression cannot be parsed. -// It simplifies safe initialization of global variables holding compiled -// JMESPaths. -func MustCompile(expression string) *JMESPath { - jmespath, err := Compile(expression) - if err != nil { - panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error()) - } - return jmespath -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func (jp *JMESPath) Search(data interface{}) (interface{}, error) { - return jp.intr.Execute(jp.ast, data) -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func Search(expression string, data interface{}) (interface{}, error) { - intr := newInterpreter() - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - return intr.Execute(ast, data) -} diff --git a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go deleted file mode 100644 index 1cd2d239..00000000 --- a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type astNodeType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTAndExpressionASTNotExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection" - -var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 229, 245, 252, 265, 281, 289, 307} - -func (i astNodeType) String() string { - if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) { - return fmt.Sprintf("astNodeType(%d)", i) - } - return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/functions.go b/vendor/github.com/jmespath/go-jmespath/functions.go deleted file mode 100644 index 9b7cd89b..00000000 --- a/vendor/github.com/jmespath/go-jmespath/functions.go +++ /dev/null @@ -1,842 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "unicode/utf8" -) - -type jpFunction func(arguments []interface{}) (interface{}, error) - -type jpType string - -const ( - jpUnknown jpType = "unknown" - jpNumber jpType = "number" - jpString jpType = "string" - jpArray jpType = "array" - jpObject jpType = "object" - jpArrayNumber jpType = "array[number]" - jpArrayString jpType = "array[string]" - jpExpref jpType = "expref" - jpAny jpType = "any" -) - -type functionEntry struct { - name string - arguments []argSpec - handler jpFunction - hasExpRef bool -} - -type argSpec struct { - types []jpType - variadic bool -} - -type byExprString struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprString) Len() int { - return len(a.items) -} -func (a *byExprString) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprString) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(string) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(string) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type byExprFloat struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprFloat) Len() int { - return len(a.items) -} -func (a *byExprFloat) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprFloat) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(float64) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(float64) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type functionCaller struct { - functionTable map[string]functionEntry -} - -func newFunctionCaller() *functionCaller { - caller := &functionCaller{} - caller.functionTable = map[string]functionEntry{ - "length": { - name: "length", - arguments: []argSpec{ - {types: []jpType{jpString, jpArray, jpObject}}, - }, - handler: jpfLength, - }, - "starts_with": { - name: "starts_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfStartsWith, - }, - "abs": { - name: "abs", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfAbs, - }, - "avg": { - name: "avg", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfAvg, - }, - "ceil": { - name: "ceil", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfCeil, - }, - "contains": { - name: "contains", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - {types: []jpType{jpAny}}, - }, - handler: jpfContains, - }, - "ends_with": { - name: "ends_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfEndsWith, - }, - "floor": { - name: "floor", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfFloor, - }, - "map": { - name: "amp", - arguments: []argSpec{ - {types: []jpType{jpExpref}}, - {types: []jpType{jpArray}}, - }, - handler: jpfMap, - hasExpRef: true, - }, - "max": { - name: "max", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMax, - }, - "merge": { - name: "merge", - arguments: []argSpec{ - {types: []jpType{jpObject}, variadic: true}, - }, - handler: jpfMerge, - }, - "max_by": { - name: "max_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMaxBy, - hasExpRef: true, - }, - "sum": { - name: "sum", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfSum, - }, - "min": { - name: "min", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMin, - }, - "min_by": { - name: "min_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMinBy, - hasExpRef: true, - }, - "type": { - name: "type", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfType, - }, - "keys": { - name: "keys", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfKeys, - }, - "values": { - name: "values", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfValues, - }, - "sort": { - name: "sort", - arguments: []argSpec{ - {types: []jpType{jpArrayString, jpArrayNumber}}, - }, - handler: jpfSort, - }, - "sort_by": { - name: "sort_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfSortBy, - hasExpRef: true, - }, - "join": { - name: "join", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpArrayString}}, - }, - handler: jpfJoin, - }, - "reverse": { - name: "reverse", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - }, - handler: jpfReverse, - }, - "to_array": { - name: "to_array", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToArray, - }, - "to_string": { - name: "to_string", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToString, - }, - "to_number": { - name: "to_number", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToNumber, - }, - "not_null": { - name: "not_null", - arguments: []argSpec{ - {types: []jpType{jpAny}, variadic: true}, - }, - handler: jpfNotNull, - }, - } - return caller -} - -func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) { - if len(e.arguments) == 0 { - return arguments, nil - } - if !e.arguments[len(e.arguments)-1].variadic { - if len(e.arguments) != len(arguments) { - return nil, errors.New("incorrect number of args") - } - for i, spec := range e.arguments { - userArg := arguments[i] - err := spec.typeCheck(userArg) - if err != nil { - return nil, err - } - } - return arguments, nil - } - if len(arguments) < len(e.arguments) { - return nil, errors.New("Invalid arity.") - } - return arguments, nil -} - -func (a *argSpec) typeCheck(arg interface{}) error { - for _, t := range a.types { - switch t { - case jpNumber: - if _, ok := arg.(float64); ok { - return nil - } - case jpString: - if _, ok := arg.(string); ok { - return nil - } - case jpArray: - if isSliceType(arg) { - return nil - } - case jpObject: - if _, ok := arg.(map[string]interface{}); ok { - return nil - } - case jpArrayNumber: - if _, ok := toArrayNum(arg); ok { - return nil - } - case jpArrayString: - if _, ok := toArrayStr(arg); ok { - return nil - } - case jpAny: - return nil - case jpExpref: - if _, ok := arg.(expRef); ok { - return nil - } - } - } - return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types) -} - -func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) { - entry, ok := f.functionTable[name] - if !ok { - return nil, errors.New("unknown function: " + name) - } - resolvedArgs, err := entry.resolveArgs(arguments) - if err != nil { - return nil, err - } - if entry.hasExpRef { - var extra []interface{} - extra = append(extra, intr) - resolvedArgs = append(extra, resolvedArgs...) - } - return entry.handler(resolvedArgs) -} - -func jpfAbs(arguments []interface{}) (interface{}, error) { - num := arguments[0].(float64) - return math.Abs(num), nil -} - -func jpfLength(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if c, ok := arg.(string); ok { - return float64(utf8.RuneCountInString(c)), nil - } else if isSliceType(arg) { - v := reflect.ValueOf(arg) - return float64(v.Len()), nil - } else if c, ok := arg.(map[string]interface{}); ok { - return float64(len(c)), nil - } - return nil, errors.New("could not compute length()") -} - -func jpfStartsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - prefix := arguments[1].(string) - return strings.HasPrefix(search, prefix), nil -} - -func jpfAvg(arguments []interface{}) (interface{}, error) { - // We've already type checked the value so we can safely use - // type assertions. - args := arguments[0].([]interface{}) - length := float64(len(args)) - numerator := 0.0 - for _, n := range args { - numerator += n.(float64) - } - return numerator / length, nil -} -func jpfCeil(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Ceil(val), nil -} -func jpfContains(arguments []interface{}) (interface{}, error) { - search := arguments[0] - el := arguments[1] - if searchStr, ok := search.(string); ok { - if elStr, ok := el.(string); ok { - return strings.Index(searchStr, elStr) != -1, nil - } - return false, nil - } - // Otherwise this is a generic contains for []interface{} - general := search.([]interface{}) - for _, item := range general { - if item == el { - return true, nil - } - } - return false, nil -} -func jpfEndsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - suffix := arguments[1].(string) - return strings.HasSuffix(search, suffix), nil -} -func jpfFloor(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Floor(val), nil -} -func jpfMap(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - exp := arguments[1].(expRef) - node := exp.ref - arr := arguments[2].([]interface{}) - mapped := make([]interface{}, 0, len(arr)) - for _, value := range arr { - current, err := intr.Execute(node, value) - if err != nil { - return nil, err - } - mapped = append(mapped, current) - } - return mapped, nil -} -func jpfMax(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil - } - // Otherwise we're dealing with a max() of strings. - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil -} -func jpfMerge(arguments []interface{}) (interface{}, error) { - final := make(map[string]interface{}) - for _, m := range arguments { - mapped := m.(map[string]interface{}) - for key, value := range mapped { - final[key] = value - } - } - return final, nil -} -func jpfMaxBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - switch t := start.(type) { - case float64: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - case string: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - default: - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfSum(arguments []interface{}) (interface{}, error) { - items, _ := toArrayNum(arguments[0]) - sum := 0.0 - for _, item := range items { - sum += item - } - return sum, nil -} - -func jpfMin(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil - } - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil -} - -func jpfMinBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if t, ok := start.(float64); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else if t, ok := start.(string); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfType(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if _, ok := arg.(float64); ok { - return "number", nil - } - if _, ok := arg.(string); ok { - return "string", nil - } - if _, ok := arg.([]interface{}); ok { - return "array", nil - } - if _, ok := arg.(map[string]interface{}); ok { - return "object", nil - } - if arg == nil { - return "null", nil - } - if arg == true || arg == false { - return "boolean", nil - } - return nil, errors.New("unknown type") -} -func jpfKeys(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for key := range arg { - collected = append(collected, key) - } - return collected, nil -} -func jpfValues(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for _, value := range arg { - collected = append(collected, value) - } - return collected, nil -} -func jpfSort(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - d := sort.Float64Slice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil - } - // Otherwise we're dealing with sort()'ing strings. - items, _ := toArrayStr(arguments[0]) - d := sort.StringSlice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil -} -func jpfSortBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return arr, nil - } else if len(arr) == 1 { - return arr, nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if _, ok := start.(float64); ok { - sortable := &byExprFloat{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else if _, ok := start.(string); ok { - sortable := &byExprString{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfJoin(arguments []interface{}) (interface{}, error) { - sep := arguments[0].(string) - // We can't just do arguments[1].([]string), we have to - // manually convert each item to a string. - arrayStr := []string{} - for _, item := range arguments[1].([]interface{}) { - arrayStr = append(arrayStr, item.(string)) - } - return strings.Join(arrayStr, sep), nil -} -func jpfReverse(arguments []interface{}) (interface{}, error) { - if s, ok := arguments[0].(string); ok { - r := []rune(s) - for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r), nil - } - items := arguments[0].([]interface{}) - length := len(items) - reversed := make([]interface{}, length) - for i, item := range items { - reversed[length-(i+1)] = item - } - return reversed, nil -} -func jpfToArray(arguments []interface{}) (interface{}, error) { - if _, ok := arguments[0].([]interface{}); ok { - return arguments[0], nil - } - return arguments[:1:1], nil -} -func jpfToString(arguments []interface{}) (interface{}, error) { - if v, ok := arguments[0].(string); ok { - return v, nil - } - result, err := json.Marshal(arguments[0]) - if err != nil { - return nil, err - } - return string(result), nil -} -func jpfToNumber(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if v, ok := arg.(float64); ok { - return v, nil - } - if v, ok := arg.(string); ok { - conv, err := strconv.ParseFloat(v, 64) - if err != nil { - return nil, nil - } - return conv, nil - } - if _, ok := arg.([]interface{}); ok { - return nil, nil - } - if _, ok := arg.(map[string]interface{}); ok { - return nil, nil - } - if arg == nil { - return nil, nil - } - if arg == true || arg == false { - return nil, nil - } - return nil, errors.New("unknown type") -} -func jpfNotNull(arguments []interface{}) (interface{}, error) { - for _, arg := range arguments { - if arg != nil { - return arg, nil - } - } - return nil, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/go.mod b/vendor/github.com/jmespath/go-jmespath/go.mod deleted file mode 100644 index 4d448e88..00000000 --- a/vendor/github.com/jmespath/go-jmespath/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module github.com/jmespath/go-jmespath - -go 1.14 - -require github.com/jmespath/go-jmespath/internal/testify v1.5.1 diff --git a/vendor/github.com/jmespath/go-jmespath/go.sum b/vendor/github.com/jmespath/go-jmespath/go.sum deleted file mode 100644 index d2db411e..00000000 --- a/vendor/github.com/jmespath/go-jmespath/go.sum +++ /dev/null @@ -1,11 +0,0 @@ -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter.go b/vendor/github.com/jmespath/go-jmespath/interpreter.go deleted file mode 100644 index 13c74604..00000000 --- a/vendor/github.com/jmespath/go-jmespath/interpreter.go +++ /dev/null @@ -1,418 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" - "unicode" - "unicode/utf8" -) - -/* This is a tree based interpreter. It walks the AST and directly - interprets the AST to search through a JSON document. -*/ - -type treeInterpreter struct { - fCall *functionCaller -} - -func newInterpreter() *treeInterpreter { - interpreter := treeInterpreter{} - interpreter.fCall = newFunctionCaller() - return &interpreter -} - -type expRef struct { - ref ASTNode -} - -// Execute takes an ASTNode and input data and interprets the AST directly. -// It will produce the result of applying the JMESPath expression associated -// with the ASTNode to the input data "value". -func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) { - switch node.nodeType { - case ASTComparator: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - right, err := intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - switch node.value { - case tEQ: - return objsEqual(left, right), nil - case tNE: - return !objsEqual(left, right), nil - } - leftNum, ok := left.(float64) - if !ok { - return nil, nil - } - rightNum, ok := right.(float64) - if !ok { - return nil, nil - } - switch node.value { - case tGT: - return leftNum > rightNum, nil - case tGTE: - return leftNum >= rightNum, nil - case tLT: - return leftNum < rightNum, nil - case tLTE: - return leftNum <= rightNum, nil - } - case ASTExpRef: - return expRef{ref: node.children[0]}, nil - case ASTFunctionExpression: - resolvedArgs := []interface{}{} - for _, arg := range node.children { - current, err := intr.Execute(arg, value) - if err != nil { - return nil, err - } - resolvedArgs = append(resolvedArgs, current) - } - return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr) - case ASTField: - if m, ok := value.(map[string]interface{}); ok { - key := node.value.(string) - return m[key], nil - } - return intr.fieldFromStruct(node.value.(string), value) - case ASTFilterProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.filterProjectionWithReflection(node, left) - } - return nil, nil - } - compareNode := node.children[2] - collected := []interface{}{} - for _, element := range sliceType { - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil - case ASTFlatten: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - // If we can't type convert to []interface{}, there's - // a chance this could still work via reflection if we're - // dealing with user provided types. - if isSliceType(left) { - return intr.flattenWithReflection(left) - } - return nil, nil - } - flattened := []interface{}{} - for _, element := range sliceType { - if elementSlice, ok := element.([]interface{}); ok { - flattened = append(flattened, elementSlice...) - } else if isSliceType(element) { - reflectFlat := []interface{}{} - v := reflect.ValueOf(element) - for i := 0; i < v.Len(); i++ { - reflectFlat = append(reflectFlat, v.Index(i).Interface()) - } - flattened = append(flattened, reflectFlat...) - } else { - flattened = append(flattened, element) - } - } - return flattened, nil - case ASTIdentity, ASTCurrentNode: - return value, nil - case ASTIndex: - if sliceType, ok := value.([]interface{}); ok { - index := node.value.(int) - if index < 0 { - index += len(sliceType) - } - if index < len(sliceType) && index >= 0 { - return sliceType[index], nil - } - return nil, nil - } - // Otherwise try via reflection. - rv := reflect.ValueOf(value) - if rv.Kind() == reflect.Slice { - index := node.value.(int) - if index < 0 { - index += rv.Len() - } - if index < rv.Len() && index >= 0 { - v := rv.Index(index) - return v.Interface(), nil - } - } - return nil, nil - case ASTKeyValPair: - return intr.Execute(node.children[0], value) - case ASTLiteral: - return node.value, nil - case ASTMultiSelectHash: - if value == nil { - return nil, nil - } - collected := make(map[string]interface{}) - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - key := child.value.(string) - collected[key] = current - } - return collected, nil - case ASTMultiSelectList: - if value == nil { - return nil, nil - } - collected := []interface{}{} - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - collected = append(collected, current) - } - return collected, nil - case ASTOrExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - matched, err = intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - } - return matched, nil - case ASTAndExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return matched, nil - } - return intr.Execute(node.children[1], value) - case ASTNotExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return true, nil - } - return false, nil - case ASTPipe: - result := value - var err error - for _, child := range node.children { - result, err = intr.Execute(child, result) - if err != nil { - return nil, err - } - } - return result, nil - case ASTProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.projectWithReflection(node, left) - } - return nil, nil - } - collected := []interface{}{} - var current interface{} - for _, element := range sliceType { - current, err = intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - case ASTSubexpression, ASTIndexExpression: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - return intr.Execute(node.children[1], left) - case ASTSlice: - sliceType, ok := value.([]interface{}) - if !ok { - if isSliceType(value) { - return intr.sliceWithReflection(node, value) - } - return nil, nil - } - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - return slice(sliceType, sliceParams) - case ASTValueProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - mapType, ok := left.(map[string]interface{}) - if !ok { - return nil, nil - } - values := make([]interface{}, len(mapType)) - for _, value := range mapType { - values = append(values, value) - } - collected := []interface{}{} - for _, element := range values { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - } - return nil, errors.New("Unknown AST node: " + node.nodeType.String()) -} - -func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) { - rv := reflect.ValueOf(value) - first, n := utf8.DecodeRuneInString(key) - fieldName := string(unicode.ToUpper(first)) + key[n:] - if rv.Kind() == reflect.Struct { - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } else if rv.Kind() == reflect.Ptr { - // Handle multiple levels of indirection? - if rv.IsNil() { - return nil, nil - } - rv = rv.Elem() - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } - return nil, nil -} - -func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - flattened := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - if reflect.TypeOf(element).Kind() == reflect.Slice { - // Then insert the contents of the element - // slice into the flattened slice, - // i.e flattened = append(flattened, mySlice...) - elementV := reflect.ValueOf(element) - for j := 0; j < elementV.Len(); j++ { - flattened = append( - flattened, elementV.Index(j).Interface()) - } - } else { - flattened = append(flattened, element) - } - } - return flattened, nil -} - -func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - final := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - final = append(final, element) - } - return slice(final, sliceParams) -} - -func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) { - compareNode := node.children[2] - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil -} - -func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) { - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if result != nil { - collected = append(collected, result) - } - } - return collected, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/lexer.go b/vendor/github.com/jmespath/go-jmespath/lexer.go deleted file mode 100644 index 817900c8..00000000 --- a/vendor/github.com/jmespath/go-jmespath/lexer.go +++ /dev/null @@ -1,420 +0,0 @@ -package jmespath - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - "unicode/utf8" -) - -type token struct { - tokenType tokType - value string - position int - length int -} - -type tokType int - -const eof = -1 - -// Lexer contains information about the expression being tokenized. -type Lexer struct { - expression string // The expression provided by the user. - currentPos int // The current position in the string. - lastWidth int // The width of the current rune. This - buf bytes.Buffer // Internal buffer used for building up values. -} - -// SyntaxError is the main error used whenever a lexing or parsing error occurs. -type SyntaxError struct { - msg string // Error message displayed to user - Expression string // Expression that generated a SyntaxError - Offset int // The location in the string where the error occurred -} - -func (e SyntaxError) Error() string { - // In the future, it would be good to underline the specific - // location where the error occurred. - return "SyntaxError: " + e.msg -} - -// HighlightLocation will show where the syntax error occurred. -// It will place a "^" character on a line below the expression -// at the point where the syntax error occurred. -func (e SyntaxError) HighlightLocation() string { - return e.Expression + "\n" + strings.Repeat(" ", e.Offset) + "^" -} - -//go:generate stringer -type=tokType -const ( - tUnknown tokType = iota - tStar - tDot - tFilter - tFlatten - tLparen - tRparen - tLbracket - tRbracket - tLbrace - tRbrace - tOr - tPipe - tNumber - tUnquotedIdentifier - tQuotedIdentifier - tComma - tColon - tLT - tLTE - tGT - tGTE - tEQ - tNE - tJSONLiteral - tStringLiteral - tCurrent - tExpref - tAnd - tNot - tEOF -) - -var basicTokens = map[rune]tokType{ - '.': tDot, - '*': tStar, - ',': tComma, - ':': tColon, - '{': tLbrace, - '}': tRbrace, - ']': tRbracket, // tLbracket not included because it could be "[]" - '(': tLparen, - ')': tRparen, - '@': tCurrent, -} - -// Bit mask for [a-zA-Z_] shifted down 64 bits to fit in a single uint64. -// When using this bitmask just be sure to shift the rune down 64 bits -// before checking against identifierStartBits. -const identifierStartBits uint64 = 576460745995190270 - -// Bit mask for [a-zA-Z0-9], 128 bits -> 2 uint64s. -var identifierTrailingBits = [2]uint64{287948901175001088, 576460745995190270} - -var whiteSpace = map[rune]bool{ - ' ': true, '\t': true, '\n': true, '\r': true, -} - -func (t token) String() string { - return fmt.Sprintf("Token{%+v, %s, %d, %d}", - t.tokenType, t.value, t.position, t.length) -} - -// NewLexer creates a new JMESPath lexer. -func NewLexer() *Lexer { - lexer := Lexer{} - return &lexer -} - -func (lexer *Lexer) next() rune { - if lexer.currentPos >= len(lexer.expression) { - lexer.lastWidth = 0 - return eof - } - r, w := utf8.DecodeRuneInString(lexer.expression[lexer.currentPos:]) - lexer.lastWidth = w - lexer.currentPos += w - return r -} - -func (lexer *Lexer) back() { - lexer.currentPos -= lexer.lastWidth -} - -func (lexer *Lexer) peek() rune { - t := lexer.next() - lexer.back() - return t -} - -// tokenize takes an expression and returns corresponding tokens. -func (lexer *Lexer) tokenize(expression string) ([]token, error) { - var tokens []token - lexer.expression = expression - lexer.currentPos = 0 - lexer.lastWidth = 0 -loop: - for { - r := lexer.next() - if identifierStartBits&(1<<(uint64(r)-64)) > 0 { - t := lexer.consumeUnquotedIdentifier() - tokens = append(tokens, t) - } else if val, ok := basicTokens[r]; ok { - // Basic single char token. - t := token{ - tokenType: val, - value: string(r), - position: lexer.currentPos - lexer.lastWidth, - length: 1, - } - tokens = append(tokens, t) - } else if r == '-' || (r >= '0' && r <= '9') { - t := lexer.consumeNumber() - tokens = append(tokens, t) - } else if r == '[' { - t := lexer.consumeLBracket() - tokens = append(tokens, t) - } else if r == '"' { - t, err := lexer.consumeQuotedIdentifier() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '\'' { - t, err := lexer.consumeRawStringLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '`' { - t, err := lexer.consumeLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '|' { - t := lexer.matchOrElse(r, '|', tOr, tPipe) - tokens = append(tokens, t) - } else if r == '<' { - t := lexer.matchOrElse(r, '=', tLTE, tLT) - tokens = append(tokens, t) - } else if r == '>' { - t := lexer.matchOrElse(r, '=', tGTE, tGT) - tokens = append(tokens, t) - } else if r == '!' { - t := lexer.matchOrElse(r, '=', tNE, tNot) - tokens = append(tokens, t) - } else if r == '=' { - t := lexer.matchOrElse(r, '=', tEQ, tUnknown) - tokens = append(tokens, t) - } else if r == '&' { - t := lexer.matchOrElse(r, '&', tAnd, tExpref) - tokens = append(tokens, t) - } else if r == eof { - break loop - } else if _, ok := whiteSpace[r]; ok { - // Ignore whitespace - } else { - return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r))) - } - } - tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0}) - return tokens, nil -} - -// Consume characters until the ending rune "r" is reached. -// If the end of the expression is reached before seeing the -// terminating rune "r", then an error is returned. -// If no error occurs then the matching substring is returned. -// The returned string will not include the ending rune. -func (lexer *Lexer) consumeUntil(end rune) (string, error) { - start := lexer.currentPos - current := lexer.next() - for current != end && current != eof { - if current == '\\' && lexer.peek() != eof { - lexer.next() - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return "", SyntaxError{ - msg: "Unclosed delimiter: " + string(end), - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - return lexer.expression[start : lexer.currentPos-lexer.lastWidth], nil -} - -func (lexer *Lexer) consumeLiteral() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('`') - if err != nil { - return token{}, err - } - value = strings.Replace(value, "\\`", "`", -1) - return token{ - tokenType: tJSONLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) consumeRawStringLiteral() (token, error) { - start := lexer.currentPos - currentIndex := start - current := lexer.next() - for current != '\'' && lexer.peek() != eof { - if current == '\\' && lexer.peek() == '\'' { - chunk := lexer.expression[currentIndex : lexer.currentPos-1] - lexer.buf.WriteString(chunk) - lexer.buf.WriteString("'") - lexer.next() - currentIndex = lexer.currentPos - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return token{}, SyntaxError{ - msg: "Unclosed delimiter: '", - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - if currentIndex < lexer.currentPos { - lexer.buf.WriteString(lexer.expression[currentIndex : lexer.currentPos-1]) - } - value := lexer.buf.String() - // Reset the buffer so it can reused again. - lexer.buf.Reset() - return token{ - tokenType: tStringLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: lexer.expression, - Offset: lexer.currentPos - 1, - } -} - -// Checks for a two char token, otherwise matches a single character -// token. This is used whenever a two char token overlaps a single -// char token, e.g. "||" -> tPipe, "|" -> tOr. -func (lexer *Lexer) matchOrElse(first rune, second rune, matchedType tokType, singleCharType tokType) token { - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == second { - t = token{ - tokenType: matchedType, - value: string(first) + string(second), - position: start, - length: 2, - } - } else { - lexer.back() - t = token{ - tokenType: singleCharType, - value: string(first), - position: start, - length: 1, - } - } - return t -} - -func (lexer *Lexer) consumeLBracket() token { - // There's three options here: - // 1. A filter expression "[?" - // 2. A flatten operator "[]" - // 3. A bare rbracket "[" - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == '?' { - t = token{ - tokenType: tFilter, - value: "[?", - position: start, - length: 2, - } - } else if nextRune == ']' { - t = token{ - tokenType: tFlatten, - value: "[]", - position: start, - length: 2, - } - } else { - t = token{ - tokenType: tLbracket, - value: "[", - position: start, - length: 1, - } - lexer.back() - } - return t -} - -func (lexer *Lexer) consumeQuotedIdentifier() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('"') - if err != nil { - return token{}, err - } - var decoded string - asJSON := []byte("\"" + value + "\"") - if err := json.Unmarshal([]byte(asJSON), &decoded); err != nil { - return token{}, err - } - return token{ - tokenType: tQuotedIdentifier, - value: decoded, - position: start - 1, - length: len(decoded), - }, nil -} - -func (lexer *Lexer) consumeUnquotedIdentifier() token { - // Consume runes until we reach the end of an unquoted - // identifier. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < 0 || r > 128 || identifierTrailingBits[uint64(r)/64]&(1<<(uint64(r)%64)) == 0 { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tUnquotedIdentifier, - value: value, - position: start, - length: lexer.currentPos - start, - } -} - -func (lexer *Lexer) consumeNumber() token { - // Consume runes until we reach something that's not a number. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < '0' || r > '9' { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tNumber, - value: value, - position: start, - length: lexer.currentPos - start, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/parser.go b/vendor/github.com/jmespath/go-jmespath/parser.go deleted file mode 100644 index 4abc303a..00000000 --- a/vendor/github.com/jmespath/go-jmespath/parser.go +++ /dev/null @@ -1,603 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" -) - -type astNodeType int - -//go:generate stringer -type astNodeType -const ( - ASTEmpty astNodeType = iota - ASTComparator - ASTCurrentNode - ASTExpRef - ASTFunctionExpression - ASTField - ASTFilterProjection - ASTFlatten - ASTIdentity - ASTIndex - ASTIndexExpression - ASTKeyValPair - ASTLiteral - ASTMultiSelectHash - ASTMultiSelectList - ASTOrExpression - ASTAndExpression - ASTNotExpression - ASTPipe - ASTProjection - ASTSubexpression - ASTSlice - ASTValueProjection -) - -// ASTNode represents the abstract syntax tree of a JMESPath expression. -type ASTNode struct { - nodeType astNodeType - value interface{} - children []ASTNode -} - -func (node ASTNode) String() string { - return node.PrettyPrint(0) -} - -// PrettyPrint will pretty print the parsed AST. -// The AST is an implementation detail and this pretty print -// function is provided as a convenience method to help with -// debugging. You should not rely on its output as the internal -// structure of the AST may change at any time. -func (node ASTNode) PrettyPrint(indent int) string { - spaces := strings.Repeat(" ", indent) - output := fmt.Sprintf("%s%s {\n", spaces, node.nodeType) - nextIndent := indent + 2 - if node.value != nil { - if converted, ok := node.value.(fmt.Stringer); ok { - // Account for things like comparator nodes - // that are enums with a String() method. - output += fmt.Sprintf("%svalue: %s\n", strings.Repeat(" ", nextIndent), converted.String()) - } else { - output += fmt.Sprintf("%svalue: %#v\n", strings.Repeat(" ", nextIndent), node.value) - } - } - lastIndex := len(node.children) - if lastIndex > 0 { - output += fmt.Sprintf("%schildren: {\n", strings.Repeat(" ", nextIndent)) - childIndent := nextIndent + 2 - for _, elem := range node.children { - output += elem.PrettyPrint(childIndent) - } - } - output += fmt.Sprintf("%s}\n", spaces) - return output -} - -var bindingPowers = map[tokType]int{ - tEOF: 0, - tUnquotedIdentifier: 0, - tQuotedIdentifier: 0, - tRbracket: 0, - tRparen: 0, - tComma: 0, - tRbrace: 0, - tNumber: 0, - tCurrent: 0, - tExpref: 0, - tColon: 0, - tPipe: 1, - tOr: 2, - tAnd: 3, - tEQ: 5, - tLT: 5, - tLTE: 5, - tGT: 5, - tGTE: 5, - tNE: 5, - tFlatten: 9, - tStar: 20, - tFilter: 21, - tDot: 40, - tNot: 45, - tLbrace: 50, - tLbracket: 55, - tLparen: 60, -} - -// Parser holds state about the current expression being parsed. -type Parser struct { - expression string - tokens []token - index int -} - -// NewParser creates a new JMESPath parser. -func NewParser() *Parser { - p := Parser{} - return &p -} - -// Parse will compile a JMESPath expression. -func (p *Parser) Parse(expression string) (ASTNode, error) { - lexer := NewLexer() - p.expression = expression - p.index = 0 - tokens, err := lexer.tokenize(expression) - if err != nil { - return ASTNode{}, err - } - p.tokens = tokens - parsed, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() != tEOF { - return ASTNode{}, p.syntaxError(fmt.Sprintf( - "Unexpected token at the end of the expression: %s", p.current())) - } - return parsed, nil -} - -func (p *Parser) parseExpression(bindingPower int) (ASTNode, error) { - var err error - leftToken := p.lookaheadToken(0) - p.advance() - leftNode, err := p.nud(leftToken) - if err != nil { - return ASTNode{}, err - } - currentToken := p.current() - for bindingPower < bindingPowers[currentToken] { - p.advance() - leftNode, err = p.led(currentToken, leftNode) - if err != nil { - return ASTNode{}, err - } - currentToken = p.current() - } - return leftNode, nil -} - -func (p *Parser) parseIndexExpression() (ASTNode, error) { - if p.lookahead(0) == tColon || p.lookahead(1) == tColon { - return p.parseSliceExpression() - } - indexStr := p.lookaheadToken(0).value - parsedInt, err := strconv.Atoi(indexStr) - if err != nil { - return ASTNode{}, err - } - indexNode := ASTNode{nodeType: ASTIndex, value: parsedInt} - p.advance() - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return indexNode, nil -} - -func (p *Parser) parseSliceExpression() (ASTNode, error) { - parts := []*int{nil, nil, nil} - index := 0 - current := p.current() - for current != tRbracket && index < 3 { - if current == tColon { - index++ - p.advance() - } else if current == tNumber { - parsedInt, err := strconv.Atoi(p.lookaheadToken(0).value) - if err != nil { - return ASTNode{}, err - } - parts[index] = &parsedInt - p.advance() - } else { - return ASTNode{}, p.syntaxError( - "Expected tColon or tNumber" + ", received: " + p.current().String()) - } - current = p.current() - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTSlice, - value: parts, - }, nil -} - -func (p *Parser) match(tokenType tokType) error { - if p.current() == tokenType { - p.advance() - return nil - } - return p.syntaxError("Expected " + tokenType.String() + ", received: " + p.current().String()) -} - -func (p *Parser) led(tokenType tokType, node ASTNode) (ASTNode, error) { - switch tokenType { - case tDot: - if p.current() != tStar { - right, err := p.parseDotRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTSubexpression, - children: []ASTNode{node, right}, - }, err - } - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTValueProjection, - children: []ASTNode{node, right}, - }, err - case tPipe: - right, err := p.parseExpression(bindingPowers[tPipe]) - return ASTNode{nodeType: ASTPipe, children: []ASTNode{node, right}}, err - case tOr: - right, err := p.parseExpression(bindingPowers[tOr]) - return ASTNode{nodeType: ASTOrExpression, children: []ASTNode{node, right}}, err - case tAnd: - right, err := p.parseExpression(bindingPowers[tAnd]) - return ASTNode{nodeType: ASTAndExpression, children: []ASTNode{node, right}}, err - case tLparen: - name := node.value - var args []ASTNode - for p.current() != tRparen { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() == tComma { - if err := p.match(tComma); err != nil { - return ASTNode{}, err - } - } - args = append(args, expression) - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTFunctionExpression, - value: name, - children: args, - }, nil - case tFilter: - return p.parseFilter(node) - case tFlatten: - left := ASTNode{nodeType: ASTFlatten, children: []ASTNode{node}} - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{left, right}, - }, err - case tEQ, tNE, tGT, tGTE, tLT, tLTE: - right, err := p.parseExpression(bindingPowers[tokenType]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTComparator, - value: tokenType, - children: []ASTNode{node, right}, - }, nil - case tLbracket: - tokenType := p.current() - var right ASTNode - var err error - if tokenType == tNumber || tokenType == tColon { - right, err = p.parseIndexExpression() - if err != nil { - return ASTNode{}, err - } - return p.projectIfSlice(node, right) - } - // Otherwise this is a projection. - if err := p.match(tStar); err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{node, right}, - }, nil - } - return ASTNode{}, p.syntaxError("Unexpected token: " + tokenType.String()) -} - -func (p *Parser) nud(token token) (ASTNode, error) { - switch token.tokenType { - case tJSONLiteral: - var parsed interface{} - err := json.Unmarshal([]byte(token.value), &parsed) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTLiteral, value: parsed}, nil - case tStringLiteral: - return ASTNode{nodeType: ASTLiteral, value: token.value}, nil - case tUnquotedIdentifier: - return ASTNode{ - nodeType: ASTField, - value: token.value, - }, nil - case tQuotedIdentifier: - node := ASTNode{nodeType: ASTField, value: token.value} - if p.current() == tLparen { - return ASTNode{}, p.syntaxErrorToken("Can't have quoted identifier as function name.", token) - } - return node, nil - case tStar: - left := ASTNode{nodeType: ASTIdentity} - var right ASTNode - var err error - if p.current() == tRbracket { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - } - return ASTNode{nodeType: ASTValueProjection, children: []ASTNode{left, right}}, err - case tFilter: - return p.parseFilter(ASTNode{nodeType: ASTIdentity}) - case tLbrace: - return p.parseMultiSelectHash() - case tFlatten: - left := ASTNode{ - nodeType: ASTFlatten, - children: []ASTNode{{nodeType: ASTIdentity}}, - } - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTProjection, children: []ASTNode{left, right}}, nil - case tLbracket: - tokenType := p.current() - //var right ASTNode - if tokenType == tNumber || tokenType == tColon { - right, err := p.parseIndexExpression() - if err != nil { - return ASTNode{}, nil - } - return p.projectIfSlice(ASTNode{nodeType: ASTIdentity}, right) - } else if tokenType == tStar && p.lookahead(1) == tRbracket { - p.advance() - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{{nodeType: ASTIdentity}, right}, - }, nil - } else { - return p.parseMultiSelectList() - } - case tCurrent: - return ASTNode{nodeType: ASTCurrentNode}, nil - case tExpref: - expression, err := p.parseExpression(bindingPowers[tExpref]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTExpRef, children: []ASTNode{expression}}, nil - case tNot: - expression, err := p.parseExpression(bindingPowers[tNot]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTNotExpression, children: []ASTNode{expression}}, nil - case tLparen: - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return expression, nil - case tEOF: - return ASTNode{}, p.syntaxErrorToken("Incomplete expression", token) - } - - return ASTNode{}, p.syntaxErrorToken("Invalid token: "+token.tokenType.String(), token) -} - -func (p *Parser) parseMultiSelectList() (ASTNode, error) { - var expressions []ASTNode - for { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - expressions = append(expressions, expression) - if p.current() == tRbracket { - break - } - err = p.match(tComma) - if err != nil { - return ASTNode{}, err - } - } - err := p.match(tRbracket) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTMultiSelectList, - children: expressions, - }, nil -} - -func (p *Parser) parseMultiSelectHash() (ASTNode, error) { - var children []ASTNode - for { - keyToken := p.lookaheadToken(0) - if err := p.match(tUnquotedIdentifier); err != nil { - if err := p.match(tQuotedIdentifier); err != nil { - return ASTNode{}, p.syntaxError("Expected tQuotedIdentifier or tUnquotedIdentifier") - } - } - keyName := keyToken.value - err := p.match(tColon) - if err != nil { - return ASTNode{}, err - } - value, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - node := ASTNode{ - nodeType: ASTKeyValPair, - value: keyName, - children: []ASTNode{value}, - } - children = append(children, node) - if p.current() == tComma { - err := p.match(tComma) - if err != nil { - return ASTNode{}, nil - } - } else if p.current() == tRbrace { - err := p.match(tRbrace) - if err != nil { - return ASTNode{}, nil - } - break - } - } - return ASTNode{ - nodeType: ASTMultiSelectHash, - children: children, - }, nil -} - -func (p *Parser) projectIfSlice(left ASTNode, right ASTNode) (ASTNode, error) { - indexExpr := ASTNode{ - nodeType: ASTIndexExpression, - children: []ASTNode{left, right}, - } - if right.nodeType == ASTSlice { - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{indexExpr, right}, - }, err - } - return indexExpr, nil -} -func (p *Parser) parseFilter(node ASTNode) (ASTNode, error) { - var right, condition ASTNode - var err error - condition, err = p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - if p.current() == tFlatten { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tFilter]) - if err != nil { - return ASTNode{}, err - } - } - - return ASTNode{ - nodeType: ASTFilterProjection, - children: []ASTNode{node, right, condition}, - }, nil -} - -func (p *Parser) parseDotRHS(bindingPower int) (ASTNode, error) { - lookahead := p.current() - if tokensOneOf([]tokType{tQuotedIdentifier, tUnquotedIdentifier, tStar}, lookahead) { - return p.parseExpression(bindingPower) - } else if lookahead == tLbracket { - if err := p.match(tLbracket); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectList() - } else if lookahead == tLbrace { - if err := p.match(tLbrace); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectHash() - } - return ASTNode{}, p.syntaxError("Expected identifier, lbracket, or lbrace") -} - -func (p *Parser) parseProjectionRHS(bindingPower int) (ASTNode, error) { - current := p.current() - if bindingPowers[current] < 10 { - return ASTNode{nodeType: ASTIdentity}, nil - } else if current == tLbracket { - return p.parseExpression(bindingPower) - } else if current == tFilter { - return p.parseExpression(bindingPower) - } else if current == tDot { - err := p.match(tDot) - if err != nil { - return ASTNode{}, err - } - return p.parseDotRHS(bindingPower) - } else { - return ASTNode{}, p.syntaxError("Error") - } -} - -func (p *Parser) lookahead(number int) tokType { - return p.lookaheadToken(number).tokenType -} - -func (p *Parser) current() tokType { - return p.lookahead(0) -} - -func (p *Parser) lookaheadToken(number int) token { - return p.tokens[p.index+number] -} - -func (p *Parser) advance() { - p.index++ -} - -func tokensOneOf(elements []tokType, token tokType) bool { - for _, elem := range elements { - if elem == token { - return true - } - } - return false -} - -func (p *Parser) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: p.lookaheadToken(0).position, - } -} - -// Create a SyntaxError based on the provided token. -// This differs from syntaxError() which creates a SyntaxError -// based on the current lookahead token. -func (p *Parser) syntaxErrorToken(msg string, t token) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: t.position, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/toktype_string.go b/vendor/github.com/jmespath/go-jmespath/toktype_string.go deleted file mode 100644 index dae79cbd..00000000 --- a/vendor/github.com/jmespath/go-jmespath/toktype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type=tokType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _tokType_name = "tUnknowntStartDottFiltertFlattentLparentRparentLbrackettRbrackettLbracetRbracetOrtPipetNumbertUnquotedIdentifiertQuotedIdentifiertCommatColontLTtLTEtGTtGTEtEQtNEtJSONLiteraltStringLiteraltCurrenttExpreftAndtNottEOF" - -var _tokType_index = [...]uint8{0, 8, 13, 17, 24, 32, 39, 46, 55, 64, 71, 78, 81, 86, 93, 112, 129, 135, 141, 144, 148, 151, 155, 158, 161, 173, 187, 195, 202, 206, 210, 214} - -func (i tokType) String() string { - if i < 0 || i >= tokType(len(_tokType_index)-1) { - return fmt.Sprintf("tokType(%d)", i) - } - return _tokType_name[_tokType_index[i]:_tokType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/util.go b/vendor/github.com/jmespath/go-jmespath/util.go deleted file mode 100644 index ddc1b7d7..00000000 --- a/vendor/github.com/jmespath/go-jmespath/util.go +++ /dev/null @@ -1,185 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" -) - -// IsFalse determines if an object is false based on the JMESPath spec. -// JMESPath defines false values to be any of: -// - An empty string array, or hash. -// - The boolean value false. -// - nil -func isFalse(value interface{}) bool { - switch v := value.(type) { - case bool: - return !v - case []interface{}: - return len(v) == 0 - case map[string]interface{}: - return len(v) == 0 - case string: - return len(v) == 0 - case nil: - return true - } - // Try the reflection cases before returning false. - rv := reflect.ValueOf(value) - switch rv.Kind() { - case reflect.Struct: - // A struct type will never be false, even if - // all of its values are the zero type. - return false - case reflect.Slice, reflect.Map: - return rv.Len() == 0 - case reflect.Ptr: - if rv.IsNil() { - return true - } - // If it's a pointer type, we'll try to deref the pointer - // and evaluate the pointer value for isFalse. - element := rv.Elem() - return isFalse(element.Interface()) - } - return false -} - -// ObjsEqual is a generic object equality check. -// It will take two arbitrary objects and recursively determine -// if they are equal. -func objsEqual(left interface{}, right interface{}) bool { - return reflect.DeepEqual(left, right) -} - -// SliceParam refers to a single part of a slice. -// A slice consists of a start, a stop, and a step, similar to -// python slices. -type sliceParam struct { - N int - Specified bool -} - -// Slice supports [start:stop:step] style slicing that's supported in JMESPath. -func slice(slice []interface{}, parts []sliceParam) ([]interface{}, error) { - computed, err := computeSliceParams(len(slice), parts) - if err != nil { - return nil, err - } - start, stop, step := computed[0], computed[1], computed[2] - result := []interface{}{} - if step > 0 { - for i := start; i < stop; i += step { - result = append(result, slice[i]) - } - } else { - for i := start; i > stop; i += step { - result = append(result, slice[i]) - } - } - return result, nil -} - -func computeSliceParams(length int, parts []sliceParam) ([]int, error) { - var start, stop, step int - if !parts[2].Specified { - step = 1 - } else if parts[2].N == 0 { - return nil, errors.New("Invalid slice, step cannot be 0") - } else { - step = parts[2].N - } - var stepValueNegative bool - if step < 0 { - stepValueNegative = true - } else { - stepValueNegative = false - } - - if !parts[0].Specified { - if stepValueNegative { - start = length - 1 - } else { - start = 0 - } - } else { - start = capSlice(length, parts[0].N, step) - } - - if !parts[1].Specified { - if stepValueNegative { - stop = -1 - } else { - stop = length - } - } else { - stop = capSlice(length, parts[1].N, step) - } - return []int{start, stop, step}, nil -} - -func capSlice(length int, actual int, step int) int { - if actual < 0 { - actual += length - if actual < 0 { - if step < 0 { - actual = -1 - } else { - actual = 0 - } - } - } else if actual >= length { - if step < 0 { - actual = length - 1 - } else { - actual = length - } - } - return actual -} - -// ToArrayNum converts an empty interface type to a slice of float64. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. -func toArrayNum(data interface{}) ([]float64, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]float64, len(d)) - for i, el := range d { - item, ok := el.(float64) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -// ToArrayStr converts an empty interface type to a slice of strings. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. If the input data could be entirely -// converted, then the converted data, along with a second value of true, -// will be returned. -func toArrayStr(data interface{}) ([]string, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]string, len(d)) - for i, el := range d { - item, ok := el.(string) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -func isSliceType(v interface{}) bool { - if v == nil { - return false - } - return reflect.TypeOf(v).Kind() == reflect.Slice -} diff --git a/vendor/github.com/josharian/intern/README.md b/vendor/github.com/josharian/intern/README.md deleted file mode 100644 index ffc44b21..00000000 --- a/vendor/github.com/josharian/intern/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Docs: https://godoc.org/github.com/josharian/intern - -See also [Go issue 5160](https://golang.org/issue/5160). - -License: MIT diff --git a/vendor/github.com/josharian/intern/go.mod b/vendor/github.com/josharian/intern/go.mod deleted file mode 100644 index f2262ff0..00000000 --- a/vendor/github.com/josharian/intern/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/josharian/intern - -go 1.5 diff --git a/vendor/github.com/josharian/intern/intern.go b/vendor/github.com/josharian/intern/intern.go deleted file mode 100644 index 7acb1fe9..00000000 --- a/vendor/github.com/josharian/intern/intern.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package intern interns strings. -// Interning is best effort only. -// Interned strings may be removed automatically -// at any time without notification. -// All functions may be called concurrently -// with themselves and each other. -package intern - -import "sync" - -var ( - pool sync.Pool = sync.Pool{ - New: func() interface{} { - return make(map[string]string) - }, - } -) - -// String returns s, interned. -func String(s string) string { - m := pool.Get().(map[string]string) - c, ok := m[s] - if ok { - pool.Put(m) - return c - } - m[s] = s - pool.Put(m) - return s -} - -// Bytes returns b converted to a string, interned. -func Bytes(b []byte) string { - m := pool.Get().(map[string]string) - c, ok := m[string(b)] - if ok { - pool.Put(m) - return c - } - s := string(b) - m[s] = s - pool.Put(m) - return s -} diff --git a/vendor/github.com/josharian/intern/license.md b/vendor/github.com/josharian/intern/license.md deleted file mode 100644 index 353d3055..00000000 --- a/vendor/github.com/josharian/intern/license.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Josh Bleecher Snyder - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/json-iterator/go/.codecov.yml b/vendor/github.com/json-iterator/go/.codecov.yml deleted file mode 100644 index 955dc0be..00000000 --- a/vendor/github.com/json-iterator/go/.codecov.yml +++ /dev/null @@ -1,3 +0,0 @@ -ignore: - - "output_tests/.*" - diff --git a/vendor/github.com/json-iterator/go/.gitignore b/vendor/github.com/json-iterator/go/.gitignore deleted file mode 100644 index 15556530..00000000 --- a/vendor/github.com/json-iterator/go/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/vendor -/bug_test.go -/coverage.txt -/.idea diff --git a/vendor/github.com/json-iterator/go/.travis.yml b/vendor/github.com/json-iterator/go/.travis.yml deleted file mode 100644 index 449e67cd..00000000 --- a/vendor/github.com/json-iterator/go/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go - -go: - - 1.8.x - - 1.x - -before_install: - - go get -t -v ./... - -script: - - ./test.sh - -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/json-iterator/go/Gopkg.lock b/vendor/github.com/json-iterator/go/Gopkg.lock deleted file mode 100644 index c8a9fbb3..00000000 --- a/vendor/github.com/json-iterator/go/Gopkg.lock +++ /dev/null @@ -1,21 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/modern-go/concurrent" - packages = ["."] - revision = "e0a39a4cb4216ea8db28e22a69f4ec25610d513a" - version = "1.0.0" - -[[projects]] - name = "github.com/modern-go/reflect2" - packages = ["."] - revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" - version = "1.0.1" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "ea54a775e5a354cb015502d2e7aa4b74230fc77e894f34a838b268c25ec8eeb8" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/json-iterator/go/Gopkg.toml b/vendor/github.com/json-iterator/go/Gopkg.toml deleted file mode 100644 index 313a0f88..00000000 --- a/vendor/github.com/json-iterator/go/Gopkg.toml +++ /dev/null @@ -1,26 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - -ignored = ["github.com/davecgh/go-spew*","github.com/google/gofuzz*","github.com/stretchr/testify*"] - -[[constraint]] - name = "github.com/modern-go/reflect2" - version = "1.0.1" diff --git a/vendor/github.com/json-iterator/go/LICENSE b/vendor/github.com/json-iterator/go/LICENSE deleted file mode 100644 index 2cf4f5ab..00000000 --- a/vendor/github.com/json-iterator/go/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 json-iterator - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/json-iterator/go/README.md b/vendor/github.com/json-iterator/go/README.md deleted file mode 100644 index c589addf..00000000 --- a/vendor/github.com/json-iterator/go/README.md +++ /dev/null @@ -1,85 +0,0 @@ -[![Sourcegraph](https://sourcegraph.com/github.com/json-iterator/go/-/badge.svg)](https://sourcegraph.com/github.com/json-iterator/go?badge) -[![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/json-iterator/go) -[![Build Status](https://travis-ci.org/json-iterator/go.svg?branch=master)](https://travis-ci.org/json-iterator/go) -[![codecov](https://codecov.io/gh/json-iterator/go/branch/master/graph/badge.svg)](https://codecov.io/gh/json-iterator/go) -[![rcard](https://goreportcard.com/badge/github.com/json-iterator/go)](https://goreportcard.com/report/github.com/json-iterator/go) -[![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/json-iterator/go/master/LICENSE) -[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby) - -A high-performance 100% compatible drop-in replacement of "encoding/json" - -# Benchmark - -![benchmark](http://jsoniter.com/benchmarks/go-benchmark.png) - -Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go - -Raw Result (easyjson requires static code generation) - -| | ns/op | allocation bytes | allocation times | -| --------------- | ----------- | ---------------- | ---------------- | -| std decode | 35510 ns/op | 1960 B/op | 99 allocs/op | -| easyjson decode | 8499 ns/op | 160 B/op | 4 allocs/op | -| jsoniter decode | 5623 ns/op | 160 B/op | 3 allocs/op | -| std encode | 2213 ns/op | 712 B/op | 5 allocs/op | -| easyjson encode | 883 ns/op | 576 B/op | 3 allocs/op | -| jsoniter encode | 837 ns/op | 384 B/op | 4 allocs/op | - -Always benchmark with your own workload. -The result depends heavily on the data input. - -# Usage - -100% compatibility with standard lib - -Replace - -```go -import "encoding/json" -json.Marshal(&data) -``` - -with - -```go -import jsoniter "github.com/json-iterator/go" - -var json = jsoniter.ConfigCompatibleWithStandardLibrary -json.Marshal(&data) -``` - -Replace - -```go -import "encoding/json" -json.Unmarshal(input, &data) -``` - -with - -```go -import jsoniter "github.com/json-iterator/go" - -var json = jsoniter.ConfigCompatibleWithStandardLibrary -json.Unmarshal(input, &data) -``` - -[More documentation](http://jsoniter.com/migrate-from-go-std.html) - -# How to get - -``` -go get github.com/json-iterator/go -``` - -# Contribution Welcomed ! - -Contributors - -- [thockin](https://github.com/thockin) -- [mattn](https://github.com/mattn) -- [cch123](https://github.com/cch123) -- [Oleg Shaldybin](https://github.com/olegshaldybin) -- [Jason Toffaletti](https://github.com/toffaletti) - -Report issue or pull request, or email taowen@gmail.com, or [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby) diff --git a/vendor/github.com/json-iterator/go/adapter.go b/vendor/github.com/json-iterator/go/adapter.go deleted file mode 100644 index 92d2cc4a..00000000 --- a/vendor/github.com/json-iterator/go/adapter.go +++ /dev/null @@ -1,150 +0,0 @@ -package jsoniter - -import ( - "bytes" - "io" -) - -// RawMessage to make replace json with jsoniter -type RawMessage []byte - -// Unmarshal adapts to json/encoding Unmarshal API -// -// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. -// Refer to https://godoc.org/encoding/json#Unmarshal for more information -func Unmarshal(data []byte, v interface{}) error { - return ConfigDefault.Unmarshal(data, v) -} - -// UnmarshalFromString is a convenient method to read from string instead of []byte -func UnmarshalFromString(str string, v interface{}) error { - return ConfigDefault.UnmarshalFromString(str, v) -} - -// Get quick method to get value from deeply nested JSON structure -func Get(data []byte, path ...interface{}) Any { - return ConfigDefault.Get(data, path...) -} - -// Marshal adapts to json/encoding Marshal API -// -// Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API -// Refer to https://godoc.org/encoding/json#Marshal for more information -func Marshal(v interface{}) ([]byte, error) { - return ConfigDefault.Marshal(v) -} - -// MarshalIndent same as json.MarshalIndent. Prefix is not supported. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - return ConfigDefault.MarshalIndent(v, prefix, indent) -} - -// MarshalToString convenient method to write as string instead of []byte -func MarshalToString(v interface{}) (string, error) { - return ConfigDefault.MarshalToString(v) -} - -// NewDecoder adapts to json/stream NewDecoder API. -// -// NewDecoder returns a new decoder that reads from r. -// -// Instead of a json/encoding Decoder, an Decoder is returned -// Refer to https://godoc.org/encoding/json#NewDecoder for more information -func NewDecoder(reader io.Reader) *Decoder { - return ConfigDefault.NewDecoder(reader) -} - -// Decoder reads and decodes JSON values from an input stream. -// Decoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress) -type Decoder struct { - iter *Iterator -} - -// Decode decode JSON into interface{} -func (adapter *Decoder) Decode(obj interface{}) error { - if adapter.iter.head == adapter.iter.tail && adapter.iter.reader != nil { - if !adapter.iter.loadMore() { - return io.EOF - } - } - adapter.iter.ReadVal(obj) - err := adapter.iter.Error - if err == io.EOF { - return nil - } - return adapter.iter.Error -} - -// More is there more? -func (adapter *Decoder) More() bool { - iter := adapter.iter - if iter.Error != nil { - return false - } - c := iter.nextToken() - if c == 0 { - return false - } - iter.unreadByte() - return c != ']' && c != '}' -} - -// Buffered remaining buffer -func (adapter *Decoder) Buffered() io.Reader { - remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail] - return bytes.NewReader(remaining) -} - -// UseNumber causes the Decoder to unmarshal a number into an interface{} as a -// Number instead of as a float64. -func (adapter *Decoder) UseNumber() { - cfg := adapter.iter.cfg.configBeforeFrozen - cfg.UseNumber = true - adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) -} - -// DisallowUnknownFields causes the Decoder to return an error when the destination -// is a struct and the input contains object keys which do not match any -// non-ignored, exported fields in the destination. -func (adapter *Decoder) DisallowUnknownFields() { - cfg := adapter.iter.cfg.configBeforeFrozen - cfg.DisallowUnknownFields = true - adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) -} - -// NewEncoder same as json.NewEncoder -func NewEncoder(writer io.Writer) *Encoder { - return ConfigDefault.NewEncoder(writer) -} - -// Encoder same as json.Encoder -type Encoder struct { - stream *Stream -} - -// Encode encode interface{} as JSON to io.Writer -func (adapter *Encoder) Encode(val interface{}) error { - adapter.stream.WriteVal(val) - adapter.stream.WriteRaw("\n") - adapter.stream.Flush() - return adapter.stream.Error -} - -// SetIndent set the indention. Prefix is not supported -func (adapter *Encoder) SetIndent(prefix, indent string) { - config := adapter.stream.cfg.configBeforeFrozen - config.IndentionStep = len(indent) - adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) -} - -// SetEscapeHTML escape html by default, set to false to disable -func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) { - config := adapter.stream.cfg.configBeforeFrozen - config.EscapeHTML = escapeHTML - adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) -} - -// Valid reports whether data is a valid JSON encoding. -func Valid(data []byte) bool { - return ConfigDefault.Valid(data) -} diff --git a/vendor/github.com/json-iterator/go/any.go b/vendor/github.com/json-iterator/go/any.go deleted file mode 100644 index f6b8aeab..00000000 --- a/vendor/github.com/json-iterator/go/any.go +++ /dev/null @@ -1,325 +0,0 @@ -package jsoniter - -import ( - "errors" - "fmt" - "github.com/modern-go/reflect2" - "io" - "reflect" - "strconv" - "unsafe" -) - -// Any generic object representation. -// The lazy json implementation holds []byte and parse lazily. -type Any interface { - LastError() error - ValueType() ValueType - MustBeValid() Any - ToBool() bool - ToInt() int - ToInt32() int32 - ToInt64() int64 - ToUint() uint - ToUint32() uint32 - ToUint64() uint64 - ToFloat32() float32 - ToFloat64() float64 - ToString() string - ToVal(val interface{}) - Get(path ...interface{}) Any - Size() int - Keys() []string - GetInterface() interface{} - WriteTo(stream *Stream) -} - -type baseAny struct{} - -func (any *baseAny) Get(path ...interface{}) Any { - return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} -} - -func (any *baseAny) Size() int { - return 0 -} - -func (any *baseAny) Keys() []string { - return []string{} -} - -func (any *baseAny) ToVal(obj interface{}) { - panic("not implemented") -} - -// WrapInt32 turn int32 into Any interface -func WrapInt32(val int32) Any { - return &int32Any{baseAny{}, val} -} - -// WrapInt64 turn int64 into Any interface -func WrapInt64(val int64) Any { - return &int64Any{baseAny{}, val} -} - -// WrapUint32 turn uint32 into Any interface -func WrapUint32(val uint32) Any { - return &uint32Any{baseAny{}, val} -} - -// WrapUint64 turn uint64 into Any interface -func WrapUint64(val uint64) Any { - return &uint64Any{baseAny{}, val} -} - -// WrapFloat64 turn float64 into Any interface -func WrapFloat64(val float64) Any { - return &floatAny{baseAny{}, val} -} - -// WrapString turn string into Any interface -func WrapString(val string) Any { - return &stringAny{baseAny{}, val} -} - -// Wrap turn a go object into Any interface -func Wrap(val interface{}) Any { - if val == nil { - return &nilAny{} - } - asAny, isAny := val.(Any) - if isAny { - return asAny - } - typ := reflect2.TypeOf(val) - switch typ.Kind() { - case reflect.Slice: - return wrapArray(val) - case reflect.Struct: - return wrapStruct(val) - case reflect.Map: - return wrapMap(val) - case reflect.String: - return WrapString(val.(string)) - case reflect.Int: - if strconv.IntSize == 32 { - return WrapInt32(int32(val.(int))) - } - return WrapInt64(int64(val.(int))) - case reflect.Int8: - return WrapInt32(int32(val.(int8))) - case reflect.Int16: - return WrapInt32(int32(val.(int16))) - case reflect.Int32: - return WrapInt32(val.(int32)) - case reflect.Int64: - return WrapInt64(val.(int64)) - case reflect.Uint: - if strconv.IntSize == 32 { - return WrapUint32(uint32(val.(uint))) - } - return WrapUint64(uint64(val.(uint))) - case reflect.Uintptr: - if ptrSize == 32 { - return WrapUint32(uint32(val.(uintptr))) - } - return WrapUint64(uint64(val.(uintptr))) - case reflect.Uint8: - return WrapUint32(uint32(val.(uint8))) - case reflect.Uint16: - return WrapUint32(uint32(val.(uint16))) - case reflect.Uint32: - return WrapUint32(uint32(val.(uint32))) - case reflect.Uint64: - return WrapUint64(val.(uint64)) - case reflect.Float32: - return WrapFloat64(float64(val.(float32))) - case reflect.Float64: - return WrapFloat64(val.(float64)) - case reflect.Bool: - if val.(bool) == true { - return &trueAny{} - } - return &falseAny{} - } - return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)} -} - -// ReadAny read next JSON element as an Any object. It is a better json.RawMessage. -func (iter *Iterator) ReadAny() Any { - return iter.readAny() -} - -func (iter *Iterator) readAny() Any { - c := iter.nextToken() - switch c { - case '"': - iter.unreadByte() - return &stringAny{baseAny{}, iter.ReadString()} - case 'n': - iter.skipThreeBytes('u', 'l', 'l') // null - return &nilAny{} - case 't': - iter.skipThreeBytes('r', 'u', 'e') // true - return &trueAny{} - case 'f': - iter.skipFourBytes('a', 'l', 's', 'e') // false - return &falseAny{} - case '{': - return iter.readObjectAny() - case '[': - return iter.readArrayAny() - case '-': - return iter.readNumberAny(false) - case 0: - return &invalidAny{baseAny{}, errors.New("input is empty")} - default: - return iter.readNumberAny(true) - } -} - -func (iter *Iterator) readNumberAny(positive bool) Any { - iter.startCapture(iter.head - 1) - iter.skipNumber() - lazyBuf := iter.stopCapture() - return &numberLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} -} - -func (iter *Iterator) readObjectAny() Any { - iter.startCapture(iter.head - 1) - iter.skipObject() - lazyBuf := iter.stopCapture() - return &objectLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} -} - -func (iter *Iterator) readArrayAny() Any { - iter.startCapture(iter.head - 1) - iter.skipArray() - lazyBuf := iter.stopCapture() - return &arrayLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} -} - -func locateObjectField(iter *Iterator, target string) []byte { - var found []byte - iter.ReadObjectCB(func(iter *Iterator, field string) bool { - if field == target { - found = iter.SkipAndReturnBytes() - return false - } - iter.Skip() - return true - }) - return found -} - -func locateArrayElement(iter *Iterator, target int) []byte { - var found []byte - n := 0 - iter.ReadArrayCB(func(iter *Iterator) bool { - if n == target { - found = iter.SkipAndReturnBytes() - return false - } - iter.Skip() - n++ - return true - }) - return found -} - -func locatePath(iter *Iterator, path []interface{}) Any { - for i, pathKeyObj := range path { - switch pathKey := pathKeyObj.(type) { - case string: - valueBytes := locateObjectField(iter, pathKey) - if valueBytes == nil { - return newInvalidAny(path[i:]) - } - iter.ResetBytes(valueBytes) - case int: - valueBytes := locateArrayElement(iter, pathKey) - if valueBytes == nil { - return newInvalidAny(path[i:]) - } - iter.ResetBytes(valueBytes) - case int32: - if '*' == pathKey { - return iter.readAny().Get(path[i:]...) - } - return newInvalidAny(path[i:]) - default: - return newInvalidAny(path[i:]) - } - } - if iter.Error != nil && iter.Error != io.EOF { - return &invalidAny{baseAny{}, iter.Error} - } - return iter.readAny() -} - -var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem() - -func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ == anyType { - return &directAnyCodec{} - } - if typ.Implements(anyType) { - return &anyCodec{ - valType: typ, - } - } - return nil -} - -func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ == anyType { - return &directAnyCodec{} - } - if typ.Implements(anyType) { - return &anyCodec{ - valType: typ, - } - } - return nil -} - -type anyCodec struct { - valType reflect2.Type -} - -func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - panic("not implemented") -} - -func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := codec.valType.UnsafeIndirect(ptr) - any := obj.(Any) - any.WriteTo(stream) -} - -func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool { - obj := codec.valType.UnsafeIndirect(ptr) - any := obj.(Any) - return any.Size() == 0 -} - -type directAnyCodec struct { -} - -func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *(*Any)(ptr) = iter.readAny() -} - -func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - any := *(*Any)(ptr) - if any == nil { - stream.WriteNil() - return - } - any.WriteTo(stream) -} - -func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool { - any := *(*Any)(ptr) - return any.Size() == 0 -} diff --git a/vendor/github.com/json-iterator/go/any_array.go b/vendor/github.com/json-iterator/go/any_array.go deleted file mode 100644 index 0449e9aa..00000000 --- a/vendor/github.com/json-iterator/go/any_array.go +++ /dev/null @@ -1,278 +0,0 @@ -package jsoniter - -import ( - "reflect" - "unsafe" -) - -type arrayLazyAny struct { - baseAny - cfg *frozenConfig - buf []byte - err error -} - -func (any *arrayLazyAny) ValueType() ValueType { - return ArrayValue -} - -func (any *arrayLazyAny) MustBeValid() Any { - return any -} - -func (any *arrayLazyAny) LastError() error { - return any.err -} - -func (any *arrayLazyAny) ToBool() bool { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.ReadArray() -} - -func (any *arrayLazyAny) ToInt() int { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToInt32() int32 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToInt64() int64 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToUint() uint { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToUint32() uint32 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToUint64() uint64 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToFloat32() float32 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToFloat64() float64 { - if any.ToBool() { - return 1 - } - return 0 -} - -func (any *arrayLazyAny) ToString() string { - return *(*string)(unsafe.Pointer(&any.buf)) -} - -func (any *arrayLazyAny) ToVal(val interface{}) { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadVal(val) -} - -func (any *arrayLazyAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case int: - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - valueBytes := locateArrayElement(iter, firstPath) - if valueBytes == nil { - return newInvalidAny(path) - } - iter.ResetBytes(valueBytes) - return locatePath(iter, path[1:]) - case int32: - if '*' == firstPath { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - arr := make([]Any, 0) - iter.ReadArrayCB(func(iter *Iterator) bool { - found := iter.readAny().Get(path[1:]...) - if found.ValueType() != InvalidValue { - arr = append(arr, found) - } - return true - }) - return wrapArray(arr) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *arrayLazyAny) Size() int { - size := 0 - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadArrayCB(func(iter *Iterator) bool { - size++ - iter.Skip() - return true - }) - return size -} - -func (any *arrayLazyAny) WriteTo(stream *Stream) { - stream.Write(any.buf) -} - -func (any *arrayLazyAny) GetInterface() interface{} { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.Read() -} - -type arrayAny struct { - baseAny - val reflect.Value -} - -func wrapArray(val interface{}) *arrayAny { - return &arrayAny{baseAny{}, reflect.ValueOf(val)} -} - -func (any *arrayAny) ValueType() ValueType { - return ArrayValue -} - -func (any *arrayAny) MustBeValid() Any { - return any -} - -func (any *arrayAny) LastError() error { - return nil -} - -func (any *arrayAny) ToBool() bool { - return any.val.Len() != 0 -} - -func (any *arrayAny) ToInt() int { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToInt32() int32 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToInt64() int64 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToUint() uint { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToUint32() uint32 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToUint64() uint64 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToFloat32() float32 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToFloat64() float64 { - if any.val.Len() == 0 { - return 0 - } - return 1 -} - -func (any *arrayAny) ToString() string { - str, _ := MarshalToString(any.val.Interface()) - return str -} - -func (any *arrayAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case int: - if firstPath < 0 || firstPath >= any.val.Len() { - return newInvalidAny(path) - } - return Wrap(any.val.Index(firstPath).Interface()) - case int32: - if '*' == firstPath { - mappedAll := make([]Any, 0) - for i := 0; i < any.val.Len(); i++ { - mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...) - if mapped.ValueType() != InvalidValue { - mappedAll = append(mappedAll, mapped) - } - } - return wrapArray(mappedAll) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *arrayAny) Size() int { - return any.val.Len() -} - -func (any *arrayAny) WriteTo(stream *Stream) { - stream.WriteVal(any.val) -} - -func (any *arrayAny) GetInterface() interface{} { - return any.val.Interface() -} diff --git a/vendor/github.com/json-iterator/go/any_bool.go b/vendor/github.com/json-iterator/go/any_bool.go deleted file mode 100644 index 9452324a..00000000 --- a/vendor/github.com/json-iterator/go/any_bool.go +++ /dev/null @@ -1,137 +0,0 @@ -package jsoniter - -type trueAny struct { - baseAny -} - -func (any *trueAny) LastError() error { - return nil -} - -func (any *trueAny) ToBool() bool { - return true -} - -func (any *trueAny) ToInt() int { - return 1 -} - -func (any *trueAny) ToInt32() int32 { - return 1 -} - -func (any *trueAny) ToInt64() int64 { - return 1 -} - -func (any *trueAny) ToUint() uint { - return 1 -} - -func (any *trueAny) ToUint32() uint32 { - return 1 -} - -func (any *trueAny) ToUint64() uint64 { - return 1 -} - -func (any *trueAny) ToFloat32() float32 { - return 1 -} - -func (any *trueAny) ToFloat64() float64 { - return 1 -} - -func (any *trueAny) ToString() string { - return "true" -} - -func (any *trueAny) WriteTo(stream *Stream) { - stream.WriteTrue() -} - -func (any *trueAny) Parse() *Iterator { - return nil -} - -func (any *trueAny) GetInterface() interface{} { - return true -} - -func (any *trueAny) ValueType() ValueType { - return BoolValue -} - -func (any *trueAny) MustBeValid() Any { - return any -} - -type falseAny struct { - baseAny -} - -func (any *falseAny) LastError() error { - return nil -} - -func (any *falseAny) ToBool() bool { - return false -} - -func (any *falseAny) ToInt() int { - return 0 -} - -func (any *falseAny) ToInt32() int32 { - return 0 -} - -func (any *falseAny) ToInt64() int64 { - return 0 -} - -func (any *falseAny) ToUint() uint { - return 0 -} - -func (any *falseAny) ToUint32() uint32 { - return 0 -} - -func (any *falseAny) ToUint64() uint64 { - return 0 -} - -func (any *falseAny) ToFloat32() float32 { - return 0 -} - -func (any *falseAny) ToFloat64() float64 { - return 0 -} - -func (any *falseAny) ToString() string { - return "false" -} - -func (any *falseAny) WriteTo(stream *Stream) { - stream.WriteFalse() -} - -func (any *falseAny) Parse() *Iterator { - return nil -} - -func (any *falseAny) GetInterface() interface{} { - return false -} - -func (any *falseAny) ValueType() ValueType { - return BoolValue -} - -func (any *falseAny) MustBeValid() Any { - return any -} diff --git a/vendor/github.com/json-iterator/go/any_float.go b/vendor/github.com/json-iterator/go/any_float.go deleted file mode 100644 index 35fdb094..00000000 --- a/vendor/github.com/json-iterator/go/any_float.go +++ /dev/null @@ -1,83 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type floatAny struct { - baseAny - val float64 -} - -func (any *floatAny) Parse() *Iterator { - return nil -} - -func (any *floatAny) ValueType() ValueType { - return NumberValue -} - -func (any *floatAny) MustBeValid() Any { - return any -} - -func (any *floatAny) LastError() error { - return nil -} - -func (any *floatAny) ToBool() bool { - return any.ToFloat64() != 0 -} - -func (any *floatAny) ToInt() int { - return int(any.val) -} - -func (any *floatAny) ToInt32() int32 { - return int32(any.val) -} - -func (any *floatAny) ToInt64() int64 { - return int64(any.val) -} - -func (any *floatAny) ToUint() uint { - if any.val > 0 { - return uint(any.val) - } - return 0 -} - -func (any *floatAny) ToUint32() uint32 { - if any.val > 0 { - return uint32(any.val) - } - return 0 -} - -func (any *floatAny) ToUint64() uint64 { - if any.val > 0 { - return uint64(any.val) - } - return 0 -} - -func (any *floatAny) ToFloat32() float32 { - return float32(any.val) -} - -func (any *floatAny) ToFloat64() float64 { - return any.val -} - -func (any *floatAny) ToString() string { - return strconv.FormatFloat(any.val, 'E', -1, 64) -} - -func (any *floatAny) WriteTo(stream *Stream) { - stream.WriteFloat64(any.val) -} - -func (any *floatAny) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/json-iterator/go/any_int32.go b/vendor/github.com/json-iterator/go/any_int32.go deleted file mode 100644 index 1b56f399..00000000 --- a/vendor/github.com/json-iterator/go/any_int32.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type int32Any struct { - baseAny - val int32 -} - -func (any *int32Any) LastError() error { - return nil -} - -func (any *int32Any) ValueType() ValueType { - return NumberValue -} - -func (any *int32Any) MustBeValid() Any { - return any -} - -func (any *int32Any) ToBool() bool { - return any.val != 0 -} - -func (any *int32Any) ToInt() int { - return int(any.val) -} - -func (any *int32Any) ToInt32() int32 { - return any.val -} - -func (any *int32Any) ToInt64() int64 { - return int64(any.val) -} - -func (any *int32Any) ToUint() uint { - return uint(any.val) -} - -func (any *int32Any) ToUint32() uint32 { - return uint32(any.val) -} - -func (any *int32Any) ToUint64() uint64 { - return uint64(any.val) -} - -func (any *int32Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *int32Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *int32Any) ToString() string { - return strconv.FormatInt(int64(any.val), 10) -} - -func (any *int32Any) WriteTo(stream *Stream) { - stream.WriteInt32(any.val) -} - -func (any *int32Any) Parse() *Iterator { - return nil -} - -func (any *int32Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/json-iterator/go/any_int64.go b/vendor/github.com/json-iterator/go/any_int64.go deleted file mode 100644 index c440d72b..00000000 --- a/vendor/github.com/json-iterator/go/any_int64.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type int64Any struct { - baseAny - val int64 -} - -func (any *int64Any) LastError() error { - return nil -} - -func (any *int64Any) ValueType() ValueType { - return NumberValue -} - -func (any *int64Any) MustBeValid() Any { - return any -} - -func (any *int64Any) ToBool() bool { - return any.val != 0 -} - -func (any *int64Any) ToInt() int { - return int(any.val) -} - -func (any *int64Any) ToInt32() int32 { - return int32(any.val) -} - -func (any *int64Any) ToInt64() int64 { - return any.val -} - -func (any *int64Any) ToUint() uint { - return uint(any.val) -} - -func (any *int64Any) ToUint32() uint32 { - return uint32(any.val) -} - -func (any *int64Any) ToUint64() uint64 { - return uint64(any.val) -} - -func (any *int64Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *int64Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *int64Any) ToString() string { - return strconv.FormatInt(any.val, 10) -} - -func (any *int64Any) WriteTo(stream *Stream) { - stream.WriteInt64(any.val) -} - -func (any *int64Any) Parse() *Iterator { - return nil -} - -func (any *int64Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/json-iterator/go/any_invalid.go b/vendor/github.com/json-iterator/go/any_invalid.go deleted file mode 100644 index 1d859eac..00000000 --- a/vendor/github.com/json-iterator/go/any_invalid.go +++ /dev/null @@ -1,82 +0,0 @@ -package jsoniter - -import "fmt" - -type invalidAny struct { - baseAny - err error -} - -func newInvalidAny(path []interface{}) *invalidAny { - return &invalidAny{baseAny{}, fmt.Errorf("%v not found", path)} -} - -func (any *invalidAny) LastError() error { - return any.err -} - -func (any *invalidAny) ValueType() ValueType { - return InvalidValue -} - -func (any *invalidAny) MustBeValid() Any { - panic(any.err) -} - -func (any *invalidAny) ToBool() bool { - return false -} - -func (any *invalidAny) ToInt() int { - return 0 -} - -func (any *invalidAny) ToInt32() int32 { - return 0 -} - -func (any *invalidAny) ToInt64() int64 { - return 0 -} - -func (any *invalidAny) ToUint() uint { - return 0 -} - -func (any *invalidAny) ToUint32() uint32 { - return 0 -} - -func (any *invalidAny) ToUint64() uint64 { - return 0 -} - -func (any *invalidAny) ToFloat32() float32 { - return 0 -} - -func (any *invalidAny) ToFloat64() float64 { - return 0 -} - -func (any *invalidAny) ToString() string { - return "" -} - -func (any *invalidAny) WriteTo(stream *Stream) { -} - -func (any *invalidAny) Get(path ...interface{}) Any { - if any.err == nil { - return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)} - } - return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)} -} - -func (any *invalidAny) Parse() *Iterator { - return nil -} - -func (any *invalidAny) GetInterface() interface{} { - return nil -} diff --git a/vendor/github.com/json-iterator/go/any_nil.go b/vendor/github.com/json-iterator/go/any_nil.go deleted file mode 100644 index d04cb54c..00000000 --- a/vendor/github.com/json-iterator/go/any_nil.go +++ /dev/null @@ -1,69 +0,0 @@ -package jsoniter - -type nilAny struct { - baseAny -} - -func (any *nilAny) LastError() error { - return nil -} - -func (any *nilAny) ValueType() ValueType { - return NilValue -} - -func (any *nilAny) MustBeValid() Any { - return any -} - -func (any *nilAny) ToBool() bool { - return false -} - -func (any *nilAny) ToInt() int { - return 0 -} - -func (any *nilAny) ToInt32() int32 { - return 0 -} - -func (any *nilAny) ToInt64() int64 { - return 0 -} - -func (any *nilAny) ToUint() uint { - return 0 -} - -func (any *nilAny) ToUint32() uint32 { - return 0 -} - -func (any *nilAny) ToUint64() uint64 { - return 0 -} - -func (any *nilAny) ToFloat32() float32 { - return 0 -} - -func (any *nilAny) ToFloat64() float64 { - return 0 -} - -func (any *nilAny) ToString() string { - return "" -} - -func (any *nilAny) WriteTo(stream *Stream) { - stream.WriteNil() -} - -func (any *nilAny) Parse() *Iterator { - return nil -} - -func (any *nilAny) GetInterface() interface{} { - return nil -} diff --git a/vendor/github.com/json-iterator/go/any_number.go b/vendor/github.com/json-iterator/go/any_number.go deleted file mode 100644 index 9d1e901a..00000000 --- a/vendor/github.com/json-iterator/go/any_number.go +++ /dev/null @@ -1,123 +0,0 @@ -package jsoniter - -import ( - "io" - "unsafe" -) - -type numberLazyAny struct { - baseAny - cfg *frozenConfig - buf []byte - err error -} - -func (any *numberLazyAny) ValueType() ValueType { - return NumberValue -} - -func (any *numberLazyAny) MustBeValid() Any { - return any -} - -func (any *numberLazyAny) LastError() error { - return any.err -} - -func (any *numberLazyAny) ToBool() bool { - return any.ToFloat64() != 0 -} - -func (any *numberLazyAny) ToInt() int { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadInt() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToInt32() int32 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadInt32() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToInt64() int64 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadInt64() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToUint() uint { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadUint() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToUint32() uint32 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadUint32() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToUint64() uint64 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadUint64() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToFloat32() float32 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadFloat32() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToFloat64() float64 { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - val := iter.ReadFloat64() - if iter.Error != nil && iter.Error != io.EOF { - any.err = iter.Error - } - return val -} - -func (any *numberLazyAny) ToString() string { - return *(*string)(unsafe.Pointer(&any.buf)) -} - -func (any *numberLazyAny) WriteTo(stream *Stream) { - stream.Write(any.buf) -} - -func (any *numberLazyAny) GetInterface() interface{} { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.Read() -} diff --git a/vendor/github.com/json-iterator/go/any_object.go b/vendor/github.com/json-iterator/go/any_object.go deleted file mode 100644 index c44ef5c9..00000000 --- a/vendor/github.com/json-iterator/go/any_object.go +++ /dev/null @@ -1,374 +0,0 @@ -package jsoniter - -import ( - "reflect" - "unsafe" -) - -type objectLazyAny struct { - baseAny - cfg *frozenConfig - buf []byte - err error -} - -func (any *objectLazyAny) ValueType() ValueType { - return ObjectValue -} - -func (any *objectLazyAny) MustBeValid() Any { - return any -} - -func (any *objectLazyAny) LastError() error { - return any.err -} - -func (any *objectLazyAny) ToBool() bool { - return true -} - -func (any *objectLazyAny) ToInt() int { - return 0 -} - -func (any *objectLazyAny) ToInt32() int32 { - return 0 -} - -func (any *objectLazyAny) ToInt64() int64 { - return 0 -} - -func (any *objectLazyAny) ToUint() uint { - return 0 -} - -func (any *objectLazyAny) ToUint32() uint32 { - return 0 -} - -func (any *objectLazyAny) ToUint64() uint64 { - return 0 -} - -func (any *objectLazyAny) ToFloat32() float32 { - return 0 -} - -func (any *objectLazyAny) ToFloat64() float64 { - return 0 -} - -func (any *objectLazyAny) ToString() string { - return *(*string)(unsafe.Pointer(&any.buf)) -} - -func (any *objectLazyAny) ToVal(obj interface{}) { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadVal(obj) -} - -func (any *objectLazyAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case string: - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - valueBytes := locateObjectField(iter, firstPath) - if valueBytes == nil { - return newInvalidAny(path) - } - iter.ResetBytes(valueBytes) - return locatePath(iter, path[1:]) - case int32: - if '*' == firstPath { - mappedAll := map[string]Any{} - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadMapCB(func(iter *Iterator, field string) bool { - mapped := locatePath(iter, path[1:]) - if mapped.ValueType() != InvalidValue { - mappedAll[field] = mapped - } - return true - }) - return wrapMap(mappedAll) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *objectLazyAny) Keys() []string { - keys := []string{} - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadMapCB(func(iter *Iterator, field string) bool { - iter.Skip() - keys = append(keys, field) - return true - }) - return keys -} - -func (any *objectLazyAny) Size() int { - size := 0 - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - iter.ReadObjectCB(func(iter *Iterator, field string) bool { - iter.Skip() - size++ - return true - }) - return size -} - -func (any *objectLazyAny) WriteTo(stream *Stream) { - stream.Write(any.buf) -} - -func (any *objectLazyAny) GetInterface() interface{} { - iter := any.cfg.BorrowIterator(any.buf) - defer any.cfg.ReturnIterator(iter) - return iter.Read() -} - -type objectAny struct { - baseAny - err error - val reflect.Value -} - -func wrapStruct(val interface{}) *objectAny { - return &objectAny{baseAny{}, nil, reflect.ValueOf(val)} -} - -func (any *objectAny) ValueType() ValueType { - return ObjectValue -} - -func (any *objectAny) MustBeValid() Any { - return any -} - -func (any *objectAny) Parse() *Iterator { - return nil -} - -func (any *objectAny) LastError() error { - return any.err -} - -func (any *objectAny) ToBool() bool { - return any.val.NumField() != 0 -} - -func (any *objectAny) ToInt() int { - return 0 -} - -func (any *objectAny) ToInt32() int32 { - return 0 -} - -func (any *objectAny) ToInt64() int64 { - return 0 -} - -func (any *objectAny) ToUint() uint { - return 0 -} - -func (any *objectAny) ToUint32() uint32 { - return 0 -} - -func (any *objectAny) ToUint64() uint64 { - return 0 -} - -func (any *objectAny) ToFloat32() float32 { - return 0 -} - -func (any *objectAny) ToFloat64() float64 { - return 0 -} - -func (any *objectAny) ToString() string { - str, err := MarshalToString(any.val.Interface()) - any.err = err - return str -} - -func (any *objectAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case string: - field := any.val.FieldByName(firstPath) - if !field.IsValid() { - return newInvalidAny(path) - } - return Wrap(field.Interface()) - case int32: - if '*' == firstPath { - mappedAll := map[string]Any{} - for i := 0; i < any.val.NumField(); i++ { - field := any.val.Field(i) - if field.CanInterface() { - mapped := Wrap(field.Interface()).Get(path[1:]...) - if mapped.ValueType() != InvalidValue { - mappedAll[any.val.Type().Field(i).Name] = mapped - } - } - } - return wrapMap(mappedAll) - } - return newInvalidAny(path) - default: - return newInvalidAny(path) - } -} - -func (any *objectAny) Keys() []string { - keys := make([]string, 0, any.val.NumField()) - for i := 0; i < any.val.NumField(); i++ { - keys = append(keys, any.val.Type().Field(i).Name) - } - return keys -} - -func (any *objectAny) Size() int { - return any.val.NumField() -} - -func (any *objectAny) WriteTo(stream *Stream) { - stream.WriteVal(any.val) -} - -func (any *objectAny) GetInterface() interface{} { - return any.val.Interface() -} - -type mapAny struct { - baseAny - err error - val reflect.Value -} - -func wrapMap(val interface{}) *mapAny { - return &mapAny{baseAny{}, nil, reflect.ValueOf(val)} -} - -func (any *mapAny) ValueType() ValueType { - return ObjectValue -} - -func (any *mapAny) MustBeValid() Any { - return any -} - -func (any *mapAny) Parse() *Iterator { - return nil -} - -func (any *mapAny) LastError() error { - return any.err -} - -func (any *mapAny) ToBool() bool { - return true -} - -func (any *mapAny) ToInt() int { - return 0 -} - -func (any *mapAny) ToInt32() int32 { - return 0 -} - -func (any *mapAny) ToInt64() int64 { - return 0 -} - -func (any *mapAny) ToUint() uint { - return 0 -} - -func (any *mapAny) ToUint32() uint32 { - return 0 -} - -func (any *mapAny) ToUint64() uint64 { - return 0 -} - -func (any *mapAny) ToFloat32() float32 { - return 0 -} - -func (any *mapAny) ToFloat64() float64 { - return 0 -} - -func (any *mapAny) ToString() string { - str, err := MarshalToString(any.val.Interface()) - any.err = err - return str -} - -func (any *mapAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - switch firstPath := path[0].(type) { - case int32: - if '*' == firstPath { - mappedAll := map[string]Any{} - for _, key := range any.val.MapKeys() { - keyAsStr := key.String() - element := Wrap(any.val.MapIndex(key).Interface()) - mapped := element.Get(path[1:]...) - if mapped.ValueType() != InvalidValue { - mappedAll[keyAsStr] = mapped - } - } - return wrapMap(mappedAll) - } - return newInvalidAny(path) - default: - value := any.val.MapIndex(reflect.ValueOf(firstPath)) - if !value.IsValid() { - return newInvalidAny(path) - } - return Wrap(value.Interface()) - } -} - -func (any *mapAny) Keys() []string { - keys := make([]string, 0, any.val.Len()) - for _, key := range any.val.MapKeys() { - keys = append(keys, key.String()) - } - return keys -} - -func (any *mapAny) Size() int { - return any.val.Len() -} - -func (any *mapAny) WriteTo(stream *Stream) { - stream.WriteVal(any.val) -} - -func (any *mapAny) GetInterface() interface{} { - return any.val.Interface() -} diff --git a/vendor/github.com/json-iterator/go/any_str.go b/vendor/github.com/json-iterator/go/any_str.go deleted file mode 100644 index 1f12f661..00000000 --- a/vendor/github.com/json-iterator/go/any_str.go +++ /dev/null @@ -1,166 +0,0 @@ -package jsoniter - -import ( - "fmt" - "strconv" -) - -type stringAny struct { - baseAny - val string -} - -func (any *stringAny) Get(path ...interface{}) Any { - if len(path) == 0 { - return any - } - return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} -} - -func (any *stringAny) Parse() *Iterator { - return nil -} - -func (any *stringAny) ValueType() ValueType { - return StringValue -} - -func (any *stringAny) MustBeValid() Any { - return any -} - -func (any *stringAny) LastError() error { - return nil -} - -func (any *stringAny) ToBool() bool { - str := any.ToString() - if str == "0" { - return false - } - for _, c := range str { - switch c { - case ' ', '\n', '\r', '\t': - default: - return true - } - } - return false -} - -func (any *stringAny) ToInt() int { - return int(any.ToInt64()) - -} - -func (any *stringAny) ToInt32() int32 { - return int32(any.ToInt64()) -} - -func (any *stringAny) ToInt64() int64 { - if any.val == "" { - return 0 - } - - flag := 1 - startPos := 0 - if any.val[0] == '+' || any.val[0] == '-' { - startPos = 1 - } - - if any.val[0] == '-' { - flag = -1 - } - - endPos := startPos - for i := startPos; i < len(any.val); i++ { - if any.val[i] >= '0' && any.val[i] <= '9' { - endPos = i + 1 - } else { - break - } - } - parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64) - return int64(flag) * parsed -} - -func (any *stringAny) ToUint() uint { - return uint(any.ToUint64()) -} - -func (any *stringAny) ToUint32() uint32 { - return uint32(any.ToUint64()) -} - -func (any *stringAny) ToUint64() uint64 { - if any.val == "" { - return 0 - } - - startPos := 0 - - if any.val[0] == '-' { - return 0 - } - if any.val[0] == '+' { - startPos = 1 - } - - endPos := startPos - for i := startPos; i < len(any.val); i++ { - if any.val[i] >= '0' && any.val[i] <= '9' { - endPos = i + 1 - } else { - break - } - } - parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64) - return parsed -} - -func (any *stringAny) ToFloat32() float32 { - return float32(any.ToFloat64()) -} - -func (any *stringAny) ToFloat64() float64 { - if len(any.val) == 0 { - return 0 - } - - // first char invalid - if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') { - return 0 - } - - // extract valid num expression from string - // eg 123true => 123, -12.12xxa => -12.12 - endPos := 1 - for i := 1; i < len(any.val); i++ { - if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' { - endPos = i + 1 - continue - } - - // end position is the first char which is not digit - if any.val[i] >= '0' && any.val[i] <= '9' { - endPos = i + 1 - } else { - endPos = i - break - } - } - parsed, _ := strconv.ParseFloat(any.val[:endPos], 64) - return parsed -} - -func (any *stringAny) ToString() string { - return any.val -} - -func (any *stringAny) WriteTo(stream *Stream) { - stream.WriteString(any.val) -} - -func (any *stringAny) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/json-iterator/go/any_uint32.go b/vendor/github.com/json-iterator/go/any_uint32.go deleted file mode 100644 index 656bbd33..00000000 --- a/vendor/github.com/json-iterator/go/any_uint32.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type uint32Any struct { - baseAny - val uint32 -} - -func (any *uint32Any) LastError() error { - return nil -} - -func (any *uint32Any) ValueType() ValueType { - return NumberValue -} - -func (any *uint32Any) MustBeValid() Any { - return any -} - -func (any *uint32Any) ToBool() bool { - return any.val != 0 -} - -func (any *uint32Any) ToInt() int { - return int(any.val) -} - -func (any *uint32Any) ToInt32() int32 { - return int32(any.val) -} - -func (any *uint32Any) ToInt64() int64 { - return int64(any.val) -} - -func (any *uint32Any) ToUint() uint { - return uint(any.val) -} - -func (any *uint32Any) ToUint32() uint32 { - return any.val -} - -func (any *uint32Any) ToUint64() uint64 { - return uint64(any.val) -} - -func (any *uint32Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *uint32Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *uint32Any) ToString() string { - return strconv.FormatInt(int64(any.val), 10) -} - -func (any *uint32Any) WriteTo(stream *Stream) { - stream.WriteUint32(any.val) -} - -func (any *uint32Any) Parse() *Iterator { - return nil -} - -func (any *uint32Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/json-iterator/go/any_uint64.go b/vendor/github.com/json-iterator/go/any_uint64.go deleted file mode 100644 index 7df2fce3..00000000 --- a/vendor/github.com/json-iterator/go/any_uint64.go +++ /dev/null @@ -1,74 +0,0 @@ -package jsoniter - -import ( - "strconv" -) - -type uint64Any struct { - baseAny - val uint64 -} - -func (any *uint64Any) LastError() error { - return nil -} - -func (any *uint64Any) ValueType() ValueType { - return NumberValue -} - -func (any *uint64Any) MustBeValid() Any { - return any -} - -func (any *uint64Any) ToBool() bool { - return any.val != 0 -} - -func (any *uint64Any) ToInt() int { - return int(any.val) -} - -func (any *uint64Any) ToInt32() int32 { - return int32(any.val) -} - -func (any *uint64Any) ToInt64() int64 { - return int64(any.val) -} - -func (any *uint64Any) ToUint() uint { - return uint(any.val) -} - -func (any *uint64Any) ToUint32() uint32 { - return uint32(any.val) -} - -func (any *uint64Any) ToUint64() uint64 { - return any.val -} - -func (any *uint64Any) ToFloat32() float32 { - return float32(any.val) -} - -func (any *uint64Any) ToFloat64() float64 { - return float64(any.val) -} - -func (any *uint64Any) ToString() string { - return strconv.FormatUint(any.val, 10) -} - -func (any *uint64Any) WriteTo(stream *Stream) { - stream.WriteUint64(any.val) -} - -func (any *uint64Any) Parse() *Iterator { - return nil -} - -func (any *uint64Any) GetInterface() interface{} { - return any.val -} diff --git a/vendor/github.com/json-iterator/go/build.sh b/vendor/github.com/json-iterator/go/build.sh deleted file mode 100644 index b45ef688..00000000 --- a/vendor/github.com/json-iterator/go/build.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -set -e -set -x - -if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then - mkdir -p /tmp/build-golang/src/github.com/json-iterator - ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go -fi -export GOPATH=/tmp/build-golang -go get -u github.com/golang/dep/cmd/dep -cd /tmp/build-golang/src/github.com/json-iterator/go -exec $GOPATH/bin/dep ensure -update diff --git a/vendor/github.com/json-iterator/go/config.go b/vendor/github.com/json-iterator/go/config.go deleted file mode 100644 index 2adcdc3b..00000000 --- a/vendor/github.com/json-iterator/go/config.go +++ /dev/null @@ -1,375 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "io" - "reflect" - "sync" - "unsafe" - - "github.com/modern-go/concurrent" - "github.com/modern-go/reflect2" -) - -// Config customize how the API should behave. -// The API is created from Config by Froze. -type Config struct { - IndentionStep int - MarshalFloatWith6Digits bool - EscapeHTML bool - SortMapKeys bool - UseNumber bool - DisallowUnknownFields bool - TagKey string - OnlyTaggedField bool - ValidateJsonRawMessage bool - ObjectFieldMustBeSimpleString bool - CaseSensitive bool -} - -// API the public interface of this package. -// Primary Marshal and Unmarshal. -type API interface { - IteratorPool - StreamPool - MarshalToString(v interface{}) (string, error) - Marshal(v interface{}) ([]byte, error) - MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) - UnmarshalFromString(str string, v interface{}) error - Unmarshal(data []byte, v interface{}) error - Get(data []byte, path ...interface{}) Any - NewEncoder(writer io.Writer) *Encoder - NewDecoder(reader io.Reader) *Decoder - Valid(data []byte) bool - RegisterExtension(extension Extension) - DecoderOf(typ reflect2.Type) ValDecoder - EncoderOf(typ reflect2.Type) ValEncoder -} - -// ConfigDefault the default API -var ConfigDefault = Config{ - EscapeHTML: true, -}.Froze() - -// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior -var ConfigCompatibleWithStandardLibrary = Config{ - EscapeHTML: true, - SortMapKeys: true, - ValidateJsonRawMessage: true, -}.Froze() - -// ConfigFastest marshals float with only 6 digits precision -var ConfigFastest = Config{ - EscapeHTML: false, - MarshalFloatWith6Digits: true, // will lose precession - ObjectFieldMustBeSimpleString: true, // do not unescape object field -}.Froze() - -type frozenConfig struct { - configBeforeFrozen Config - sortMapKeys bool - indentionStep int - objectFieldMustBeSimpleString bool - onlyTaggedField bool - disallowUnknownFields bool - decoderCache *concurrent.Map - encoderCache *concurrent.Map - encoderExtension Extension - decoderExtension Extension - extraExtensions []Extension - streamPool *sync.Pool - iteratorPool *sync.Pool - caseSensitive bool -} - -func (cfg *frozenConfig) initCache() { - cfg.decoderCache = concurrent.NewMap() - cfg.encoderCache = concurrent.NewMap() -} - -func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { - cfg.decoderCache.Store(cacheKey, decoder) -} - -func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { - cfg.encoderCache.Store(cacheKey, encoder) -} - -func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { - decoder, found := cfg.decoderCache.Load(cacheKey) - if found { - return decoder.(ValDecoder) - } - return nil -} - -func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { - encoder, found := cfg.encoderCache.Load(cacheKey) - if found { - return encoder.(ValEncoder) - } - return nil -} - -var cfgCache = concurrent.NewMap() - -func getFrozenConfigFromCache(cfg Config) *frozenConfig { - obj, found := cfgCache.Load(cfg) - if found { - return obj.(*frozenConfig) - } - return nil -} - -func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { - cfgCache.Store(cfg, frozenConfig) -} - -// Froze forge API from config -func (cfg Config) Froze() API { - api := &frozenConfig{ - sortMapKeys: cfg.SortMapKeys, - indentionStep: cfg.IndentionStep, - objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, - onlyTaggedField: cfg.OnlyTaggedField, - disallowUnknownFields: cfg.DisallowUnknownFields, - caseSensitive: cfg.CaseSensitive, - } - api.streamPool = &sync.Pool{ - New: func() interface{} { - return NewStream(api, nil, 512) - }, - } - api.iteratorPool = &sync.Pool{ - New: func() interface{} { - return NewIterator(api) - }, - } - api.initCache() - encoderExtension := EncoderExtension{} - decoderExtension := DecoderExtension{} - if cfg.MarshalFloatWith6Digits { - api.marshalFloatWith6Digits(encoderExtension) - } - if cfg.EscapeHTML { - api.escapeHTML(encoderExtension) - } - if cfg.UseNumber { - api.useNumber(decoderExtension) - } - if cfg.ValidateJsonRawMessage { - api.validateJsonRawMessage(encoderExtension) - } - api.encoderExtension = encoderExtension - api.decoderExtension = decoderExtension - api.configBeforeFrozen = cfg - return api -} - -func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { - api := getFrozenConfigFromCache(cfg) - if api != nil { - return api - } - api = cfg.Froze().(*frozenConfig) - for _, extension := range extraExtensions { - api.RegisterExtension(extension) - } - addFrozenConfigToCache(cfg, api) - return api -} - -func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { - encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { - rawMessage := *(*json.RawMessage)(ptr) - iter := cfg.BorrowIterator([]byte(rawMessage)) - defer cfg.ReturnIterator(iter) - iter.Read() - if iter.Error != nil && iter.Error != io.EOF { - stream.WriteRaw("null") - } else { - stream.WriteRaw(string(rawMessage)) - } - }, func(ptr unsafe.Pointer) bool { - return len(*((*json.RawMessage)(ptr))) == 0 - }} - extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder - extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder -} - -func (cfg *frozenConfig) useNumber(extension DecoderExtension) { - extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { - exitingValue := *((*interface{})(ptr)) - if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { - iter.ReadVal(exitingValue) - return - } - if iter.WhatIsNext() == NumberValue { - *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) - } else { - *((*interface{})(ptr)) = iter.Read() - } - }} -} -func (cfg *frozenConfig) getTagKey() string { - tagKey := cfg.configBeforeFrozen.TagKey - if tagKey == "" { - return "json" - } - return tagKey -} - -func (cfg *frozenConfig) RegisterExtension(extension Extension) { - cfg.extraExtensions = append(cfg.extraExtensions, extension) - copied := cfg.configBeforeFrozen - cfg.configBeforeFrozen = copied -} - -type lossyFloat32Encoder struct { -} - -func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat32Lossy(*((*float32)(ptr))) -} - -func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float32)(ptr)) == 0 -} - -type lossyFloat64Encoder struct { -} - -func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat64Lossy(*((*float64)(ptr))) -} - -func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float64)(ptr)) == 0 -} - -// EnableLossyFloatMarshalling keeps 10**(-6) precision -// for float variables for better performance. -func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { - // for better performance - extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} - extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} -} - -type htmlEscapedStringEncoder struct { -} - -func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - str := *((*string)(ptr)) - stream.WriteStringWithHTMLEscaped(str) -} - -func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*string)(ptr)) == "" -} - -func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { - encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} -} - -func (cfg *frozenConfig) cleanDecoders() { - typeDecoders = map[string]ValDecoder{} - fieldDecoders = map[string]ValDecoder{} - *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) -} - -func (cfg *frozenConfig) cleanEncoders() { - typeEncoders = map[string]ValEncoder{} - fieldEncoders = map[string]ValEncoder{} - *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) -} - -func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { - stream := cfg.BorrowStream(nil) - defer cfg.ReturnStream(stream) - stream.WriteVal(v) - if stream.Error != nil { - return "", stream.Error - } - return string(stream.Buffer()), nil -} - -func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { - stream := cfg.BorrowStream(nil) - defer cfg.ReturnStream(stream) - stream.WriteVal(v) - if stream.Error != nil { - return nil, stream.Error - } - result := stream.Buffer() - copied := make([]byte, len(result)) - copy(copied, result) - return copied, nil -} - -func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - if prefix != "" { - panic("prefix is not supported") - } - for _, r := range indent { - if r != ' ' { - panic("indent can only be space") - } - } - newCfg := cfg.configBeforeFrozen - newCfg.IndentionStep = len(indent) - return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) -} - -func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { - data := []byte(str) - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - iter.ReadVal(v) - c := iter.nextToken() - if c == 0 { - if iter.Error == io.EOF { - return nil - } - return iter.Error - } - iter.ReportError("Unmarshal", "there are bytes left after unmarshal") - return iter.Error -} - -func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - return locatePath(iter, path) -} - -func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - iter.ReadVal(v) - c := iter.nextToken() - if c == 0 { - if iter.Error == io.EOF { - return nil - } - return iter.Error - } - iter.ReportError("Unmarshal", "there are bytes left after unmarshal") - return iter.Error -} - -func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { - stream := NewStream(cfg, writer, 512) - return &Encoder{stream} -} - -func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { - iter := Parse(cfg, reader, 512) - return &Decoder{iter} -} - -func (cfg *frozenConfig) Valid(data []byte) bool { - iter := cfg.BorrowIterator(data) - defer cfg.ReturnIterator(iter) - iter.Skip() - return iter.Error == nil -} diff --git a/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md b/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md deleted file mode 100644 index 3095662b..00000000 --- a/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md +++ /dev/null @@ -1,7 +0,0 @@ -| json type \ dest type | bool | int | uint | float |string| -| --- | --- | --- | --- |--|--| -| number | positive => true
negative => true
zero => false| 23.2 => 23
-32.1 => -32| 12.1 => 12
-12.1 => 0|as normal|same as origin| -| string | empty string => false
string "0" => false
other strings => true | "123.32" => 123
"-123.4" => -123
"123.23xxxw" => 123
"abcde12" => 0
"-32.1" => -32| 13.2 => 13
-1.1 => 0 |12.1 => 12.1
-12.3 => -12.3
12.4xxa => 12.4
+1.1e2 =>110 |same as origin| -| bool | true => true
false => false| true => 1
false => 0 | true => 1
false => 0 |true => 1
false => 0|true => "true"
false => "false"| -| object | true | 0 | 0 |0|originnal json| -| array | empty array => false
nonempty array => true| [] => 0
[1,2] => 1 | [] => 0
[1,2] => 1 |[] => 0
[1,2] => 1|original json| \ No newline at end of file diff --git a/vendor/github.com/json-iterator/go/go.mod b/vendor/github.com/json-iterator/go/go.mod deleted file mode 100644 index e817cccb..00000000 --- a/vendor/github.com/json-iterator/go/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/json-iterator/go - -go 1.12 - -require ( - github.com/davecgh/go-spew v1.1.1 - github.com/google/gofuzz v1.0.0 - github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 - github.com/modern-go/reflect2 v1.0.2 - github.com/stretchr/testify v1.3.0 -) diff --git a/vendor/github.com/json-iterator/go/go.sum b/vendor/github.com/json-iterator/go/go.sum deleted file mode 100644 index 4b7bb8a2..00000000 --- a/vendor/github.com/json-iterator/go/go.sum +++ /dev/null @@ -1,14 +0,0 @@ -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= diff --git a/vendor/github.com/json-iterator/go/iter.go b/vendor/github.com/json-iterator/go/iter.go deleted file mode 100644 index 29b31cf7..00000000 --- a/vendor/github.com/json-iterator/go/iter.go +++ /dev/null @@ -1,349 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "fmt" - "io" -) - -// ValueType the type for JSON element -type ValueType int - -const ( - // InvalidValue invalid JSON element - InvalidValue ValueType = iota - // StringValue JSON element "string" - StringValue - // NumberValue JSON element 100 or 0.10 - NumberValue - // NilValue JSON element null - NilValue - // BoolValue JSON element true or false - BoolValue - // ArrayValue JSON element [] - ArrayValue - // ObjectValue JSON element {} - ObjectValue -) - -var hexDigits []byte -var valueTypes []ValueType - -func init() { - hexDigits = make([]byte, 256) - for i := 0; i < len(hexDigits); i++ { - hexDigits[i] = 255 - } - for i := '0'; i <= '9'; i++ { - hexDigits[i] = byte(i - '0') - } - for i := 'a'; i <= 'f'; i++ { - hexDigits[i] = byte((i - 'a') + 10) - } - for i := 'A'; i <= 'F'; i++ { - hexDigits[i] = byte((i - 'A') + 10) - } - valueTypes = make([]ValueType, 256) - for i := 0; i < len(valueTypes); i++ { - valueTypes[i] = InvalidValue - } - valueTypes['"'] = StringValue - valueTypes['-'] = NumberValue - valueTypes['0'] = NumberValue - valueTypes['1'] = NumberValue - valueTypes['2'] = NumberValue - valueTypes['3'] = NumberValue - valueTypes['4'] = NumberValue - valueTypes['5'] = NumberValue - valueTypes['6'] = NumberValue - valueTypes['7'] = NumberValue - valueTypes['8'] = NumberValue - valueTypes['9'] = NumberValue - valueTypes['t'] = BoolValue - valueTypes['f'] = BoolValue - valueTypes['n'] = NilValue - valueTypes['['] = ArrayValue - valueTypes['{'] = ObjectValue -} - -// Iterator is a io.Reader like object, with JSON specific read functions. -// Error is not returned as return value, but stored as Error member on this iterator instance. -type Iterator struct { - cfg *frozenConfig - reader io.Reader - buf []byte - head int - tail int - depth int - captureStartedAt int - captured []byte - Error error - Attachment interface{} // open for customized decoder -} - -// NewIterator creates an empty Iterator instance -func NewIterator(cfg API) *Iterator { - return &Iterator{ - cfg: cfg.(*frozenConfig), - reader: nil, - buf: nil, - head: 0, - tail: 0, - depth: 0, - } -} - -// Parse creates an Iterator instance from io.Reader -func Parse(cfg API, reader io.Reader, bufSize int) *Iterator { - return &Iterator{ - cfg: cfg.(*frozenConfig), - reader: reader, - buf: make([]byte, bufSize), - head: 0, - tail: 0, - depth: 0, - } -} - -// ParseBytes creates an Iterator instance from byte array -func ParseBytes(cfg API, input []byte) *Iterator { - return &Iterator{ - cfg: cfg.(*frozenConfig), - reader: nil, - buf: input, - head: 0, - tail: len(input), - depth: 0, - } -} - -// ParseString creates an Iterator instance from string -func ParseString(cfg API, input string) *Iterator { - return ParseBytes(cfg, []byte(input)) -} - -// Pool returns a pool can provide more iterator with same configuration -func (iter *Iterator) Pool() IteratorPool { - return iter.cfg -} - -// Reset reuse iterator instance by specifying another reader -func (iter *Iterator) Reset(reader io.Reader) *Iterator { - iter.reader = reader - iter.head = 0 - iter.tail = 0 - iter.depth = 0 - return iter -} - -// ResetBytes reuse iterator instance by specifying another byte array as input -func (iter *Iterator) ResetBytes(input []byte) *Iterator { - iter.reader = nil - iter.buf = input - iter.head = 0 - iter.tail = len(input) - iter.depth = 0 - return iter -} - -// WhatIsNext gets ValueType of relatively next json element -func (iter *Iterator) WhatIsNext() ValueType { - valueType := valueTypes[iter.nextToken()] - iter.unreadByte() - return valueType -} - -func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case ' ', '\n', '\t', '\r': - continue - } - iter.head = i - return false - } - return true -} - -func (iter *Iterator) isObjectEnd() bool { - c := iter.nextToken() - if c == ',' { - return false - } - if c == '}' { - return true - } - iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c})) - return true -} - -func (iter *Iterator) nextToken() byte { - // a variation of skip whitespaces, returning the next non-whitespace token - for { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case ' ', '\n', '\t', '\r': - continue - } - iter.head = i + 1 - return c - } - if !iter.loadMore() { - return 0 - } - } -} - -// ReportError record a error in iterator instance with current position. -func (iter *Iterator) ReportError(operation string, msg string) { - if iter.Error != nil { - if iter.Error != io.EOF { - return - } - } - peekStart := iter.head - 10 - if peekStart < 0 { - peekStart = 0 - } - peekEnd := iter.head + 10 - if peekEnd > iter.tail { - peekEnd = iter.tail - } - parsing := string(iter.buf[peekStart:peekEnd]) - contextStart := iter.head - 50 - if contextStart < 0 { - contextStart = 0 - } - contextEnd := iter.head + 50 - if contextEnd > iter.tail { - contextEnd = iter.tail - } - context := string(iter.buf[contextStart:contextEnd]) - iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...", - operation, msg, iter.head-peekStart, parsing, context) -} - -// CurrentBuffer gets current buffer as string for debugging purpose -func (iter *Iterator) CurrentBuffer() string { - peekStart := iter.head - 10 - if peekStart < 0 { - peekStart = 0 - } - return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head, - string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail])) -} - -func (iter *Iterator) readByte() (ret byte) { - if iter.head == iter.tail { - if iter.loadMore() { - ret = iter.buf[iter.head] - iter.head++ - return ret - } - return 0 - } - ret = iter.buf[iter.head] - iter.head++ - return ret -} - -func (iter *Iterator) loadMore() bool { - if iter.reader == nil { - if iter.Error == nil { - iter.head = iter.tail - iter.Error = io.EOF - } - return false - } - if iter.captured != nil { - iter.captured = append(iter.captured, - iter.buf[iter.captureStartedAt:iter.tail]...) - iter.captureStartedAt = 0 - } - for { - n, err := iter.reader.Read(iter.buf) - if n == 0 { - if err != nil { - if iter.Error == nil { - iter.Error = err - } - return false - } - } else { - iter.head = 0 - iter.tail = n - return true - } - } -} - -func (iter *Iterator) unreadByte() { - if iter.Error != nil { - return - } - iter.head-- - return -} - -// Read read the next JSON element as generic interface{}. -func (iter *Iterator) Read() interface{} { - valueType := iter.WhatIsNext() - switch valueType { - case StringValue: - return iter.ReadString() - case NumberValue: - if iter.cfg.configBeforeFrozen.UseNumber { - return json.Number(iter.readNumberAsString()) - } - return iter.ReadFloat64() - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - return nil - case BoolValue: - return iter.ReadBool() - case ArrayValue: - arr := []interface{}{} - iter.ReadArrayCB(func(iter *Iterator) bool { - var elem interface{} - iter.ReadVal(&elem) - arr = append(arr, elem) - return true - }) - return arr - case ObjectValue: - obj := map[string]interface{}{} - iter.ReadMapCB(func(Iter *Iterator, field string) bool { - var elem interface{} - iter.ReadVal(&elem) - obj[field] = elem - return true - }) - return obj - default: - iter.ReportError("Read", fmt.Sprintf("unexpected value type: %v", valueType)) - return nil - } -} - -// limit maximum depth of nesting, as allowed by https://tools.ietf.org/html/rfc7159#section-9 -const maxDepth = 10000 - -func (iter *Iterator) incrementDepth() (success bool) { - iter.depth++ - if iter.depth <= maxDepth { - return true - } - iter.ReportError("incrementDepth", "exceeded max depth") - return false -} - -func (iter *Iterator) decrementDepth() (success bool) { - iter.depth-- - if iter.depth >= 0 { - return true - } - iter.ReportError("decrementDepth", "unexpected negative nesting") - return false -} diff --git a/vendor/github.com/json-iterator/go/iter_array.go b/vendor/github.com/json-iterator/go/iter_array.go deleted file mode 100644 index 204fe0e0..00000000 --- a/vendor/github.com/json-iterator/go/iter_array.go +++ /dev/null @@ -1,64 +0,0 @@ -package jsoniter - -// ReadArray read array element, tells if the array has more element to read. -func (iter *Iterator) ReadArray() (ret bool) { - c := iter.nextToken() - switch c { - case 'n': - iter.skipThreeBytes('u', 'l', 'l') - return false // null - case '[': - c = iter.nextToken() - if c != ']' { - iter.unreadByte() - return true - } - return false - case ']': - return false - case ',': - return true - default: - iter.ReportError("ReadArray", "expect [ or , or ] or n, but found "+string([]byte{c})) - return - } -} - -// ReadArrayCB read array with callback -func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) { - c := iter.nextToken() - if c == '[' { - if !iter.incrementDepth() { - return false - } - c = iter.nextToken() - if c != ']' { - iter.unreadByte() - if !callback(iter) { - iter.decrementDepth() - return false - } - c = iter.nextToken() - for c == ',' { - if !callback(iter) { - iter.decrementDepth() - return false - } - c = iter.nextToken() - } - if c != ']' { - iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c})) - iter.decrementDepth() - return false - } - return iter.decrementDepth() - } - return iter.decrementDepth() - } - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return true // null - } - iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c})) - return false -} diff --git a/vendor/github.com/json-iterator/go/iter_float.go b/vendor/github.com/json-iterator/go/iter_float.go deleted file mode 100644 index 8a3d8b6f..00000000 --- a/vendor/github.com/json-iterator/go/iter_float.go +++ /dev/null @@ -1,342 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "io" - "math/big" - "strconv" - "strings" - "unsafe" -) - -var floatDigits []int8 - -const invalidCharForNumber = int8(-1) -const endOfNumber = int8(-2) -const dotInNumber = int8(-3) - -func init() { - floatDigits = make([]int8, 256) - for i := 0; i < len(floatDigits); i++ { - floatDigits[i] = invalidCharForNumber - } - for i := int8('0'); i <= int8('9'); i++ { - floatDigits[i] = i - int8('0') - } - floatDigits[','] = endOfNumber - floatDigits[']'] = endOfNumber - floatDigits['}'] = endOfNumber - floatDigits[' '] = endOfNumber - floatDigits['\t'] = endOfNumber - floatDigits['\n'] = endOfNumber - floatDigits['.'] = dotInNumber -} - -// ReadBigFloat read big.Float -func (iter *Iterator) ReadBigFloat() (ret *big.Float) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return nil - } - prec := 64 - if len(str) > prec { - prec = len(str) - } - val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero) - if err != nil { - iter.Error = err - return nil - } - return val -} - -// ReadBigInt read big.Int -func (iter *Iterator) ReadBigInt() (ret *big.Int) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return nil - } - ret = big.NewInt(0) - var success bool - ret, success = ret.SetString(str, 10) - if !success { - iter.ReportError("ReadBigInt", "invalid big int") - return nil - } - return ret -} - -//ReadFloat32 read float32 -func (iter *Iterator) ReadFloat32() (ret float32) { - c := iter.nextToken() - if c == '-' { - return -iter.readPositiveFloat32() - } - iter.unreadByte() - return iter.readPositiveFloat32() -} - -func (iter *Iterator) readPositiveFloat32() (ret float32) { - i := iter.head - // first char - if i == iter.tail { - return iter.readFloat32SlowPath() - } - c := iter.buf[i] - i++ - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat32SlowPath() - case endOfNumber: - iter.ReportError("readFloat32", "empty number") - return - case dotInNumber: - iter.ReportError("readFloat32", "leading dot is invalid") - return - case 0: - if i == iter.tail { - return iter.readFloat32SlowPath() - } - c = iter.buf[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - iter.ReportError("readFloat32", "leading zero is invalid") - return - } - } - value := uint64(ind) - // chars before dot -non_decimal_loop: - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat32SlowPath() - case endOfNumber: - iter.head = i - return float32(value) - case dotInNumber: - break non_decimal_loop - } - if value > uint64SafeToMultiple10 { - return iter.readFloat32SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; - } - // chars after dot - if c == '.' { - i++ - decimalPlaces := 0 - if i == iter.tail { - return iter.readFloat32SlowPath() - } - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case endOfNumber: - if decimalPlaces > 0 && decimalPlaces < len(pow10) { - iter.head = i - return float32(float64(value) / float64(pow10[decimalPlaces])) - } - // too many decimal places - return iter.readFloat32SlowPath() - case invalidCharForNumber, dotInNumber: - return iter.readFloat32SlowPath() - } - decimalPlaces++ - if value > uint64SafeToMultiple10 { - return iter.readFloat32SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) - } - } - return iter.readFloat32SlowPath() -} - -func (iter *Iterator) readNumberAsString() (ret string) { - strBuf := [16]byte{} - str := strBuf[0:0] -load_loop: - for { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case '+', '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - str = append(str, c) - continue - default: - iter.head = i - break load_loop - } - } - if !iter.loadMore() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF { - return - } - if len(str) == 0 { - iter.ReportError("readNumberAsString", "invalid number") - } - return *(*string)(unsafe.Pointer(&str)) -} - -func (iter *Iterator) readFloat32SlowPath() (ret float32) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return - } - errMsg := validateFloat(str) - if errMsg != "" { - iter.ReportError("readFloat32SlowPath", errMsg) - return - } - val, err := strconv.ParseFloat(str, 32) - if err != nil { - iter.Error = err - return - } - return float32(val) -} - -// ReadFloat64 read float64 -func (iter *Iterator) ReadFloat64() (ret float64) { - c := iter.nextToken() - if c == '-' { - return -iter.readPositiveFloat64() - } - iter.unreadByte() - return iter.readPositiveFloat64() -} - -func (iter *Iterator) readPositiveFloat64() (ret float64) { - i := iter.head - // first char - if i == iter.tail { - return iter.readFloat64SlowPath() - } - c := iter.buf[i] - i++ - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat64SlowPath() - case endOfNumber: - iter.ReportError("readFloat64", "empty number") - return - case dotInNumber: - iter.ReportError("readFloat64", "leading dot is invalid") - return - case 0: - if i == iter.tail { - return iter.readFloat64SlowPath() - } - c = iter.buf[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - iter.ReportError("readFloat64", "leading zero is invalid") - return - } - } - value := uint64(ind) - // chars before dot -non_decimal_loop: - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case invalidCharForNumber: - return iter.readFloat64SlowPath() - case endOfNumber: - iter.head = i - return float64(value) - case dotInNumber: - break non_decimal_loop - } - if value > uint64SafeToMultiple10 { - return iter.readFloat64SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; - } - // chars after dot - if c == '.' { - i++ - decimalPlaces := 0 - if i == iter.tail { - return iter.readFloat64SlowPath() - } - for ; i < iter.tail; i++ { - c = iter.buf[i] - ind := floatDigits[c] - switch ind { - case endOfNumber: - if decimalPlaces > 0 && decimalPlaces < len(pow10) { - iter.head = i - return float64(value) / float64(pow10[decimalPlaces]) - } - // too many decimal places - return iter.readFloat64SlowPath() - case invalidCharForNumber, dotInNumber: - return iter.readFloat64SlowPath() - } - decimalPlaces++ - if value > uint64SafeToMultiple10 { - return iter.readFloat64SlowPath() - } - value = (value << 3) + (value << 1) + uint64(ind) - if value > maxFloat64 { - return iter.readFloat64SlowPath() - } - } - } - return iter.readFloat64SlowPath() -} - -func (iter *Iterator) readFloat64SlowPath() (ret float64) { - str := iter.readNumberAsString() - if iter.Error != nil && iter.Error != io.EOF { - return - } - errMsg := validateFloat(str) - if errMsg != "" { - iter.ReportError("readFloat64SlowPath", errMsg) - return - } - val, err := strconv.ParseFloat(str, 64) - if err != nil { - iter.Error = err - return - } - return val -} - -func validateFloat(str string) string { - // strconv.ParseFloat is not validating `1.` or `1.e1` - if len(str) == 0 { - return "empty number" - } - if str[0] == '-' { - return "-- is not valid" - } - dotPos := strings.IndexByte(str, '.') - if dotPos != -1 { - if dotPos == len(str)-1 { - return "dot can not be last character" - } - switch str[dotPos+1] { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - default: - return "missing digit after dot" - } - } - return "" -} - -// ReadNumber read json.Number -func (iter *Iterator) ReadNumber() (ret json.Number) { - return json.Number(iter.readNumberAsString()) -} diff --git a/vendor/github.com/json-iterator/go/iter_int.go b/vendor/github.com/json-iterator/go/iter_int.go deleted file mode 100644 index d786a89f..00000000 --- a/vendor/github.com/json-iterator/go/iter_int.go +++ /dev/null @@ -1,346 +0,0 @@ -package jsoniter - -import ( - "math" - "strconv" -) - -var intDigits []int8 - -const uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1 -const uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1 -const maxFloat64 = 1<<53 - 1 - -func init() { - intDigits = make([]int8, 256) - for i := 0; i < len(intDigits); i++ { - intDigits[i] = invalidCharForNumber - } - for i := int8('0'); i <= int8('9'); i++ { - intDigits[i] = i - int8('0') - } -} - -// ReadUint read uint -func (iter *Iterator) ReadUint() uint { - if strconv.IntSize == 32 { - return uint(iter.ReadUint32()) - } - return uint(iter.ReadUint64()) -} - -// ReadInt read int -func (iter *Iterator) ReadInt() int { - if strconv.IntSize == 32 { - return int(iter.ReadInt32()) - } - return int(iter.ReadInt64()) -} - -// ReadInt8 read int8 -func (iter *Iterator) ReadInt8() (ret int8) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint32(iter.readByte()) - if val > math.MaxInt8+1 { - iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return -int8(val) - } - val := iter.readUint32(c) - if val > math.MaxInt8 { - iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return int8(val) -} - -// ReadUint8 read uint8 -func (iter *Iterator) ReadUint8() (ret uint8) { - val := iter.readUint32(iter.nextToken()) - if val > math.MaxUint8 { - iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return uint8(val) -} - -// ReadInt16 read int16 -func (iter *Iterator) ReadInt16() (ret int16) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint32(iter.readByte()) - if val > math.MaxInt16+1 { - iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return -int16(val) - } - val := iter.readUint32(c) - if val > math.MaxInt16 { - iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return int16(val) -} - -// ReadUint16 read uint16 -func (iter *Iterator) ReadUint16() (ret uint16) { - val := iter.readUint32(iter.nextToken()) - if val > math.MaxUint16 { - iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return uint16(val) -} - -// ReadInt32 read int32 -func (iter *Iterator) ReadInt32() (ret int32) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint32(iter.readByte()) - if val > math.MaxInt32+1 { - iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return -int32(val) - } - val := iter.readUint32(c) - if val > math.MaxInt32 { - iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) - return - } - return int32(val) -} - -// ReadUint32 read uint32 -func (iter *Iterator) ReadUint32() (ret uint32) { - return iter.readUint32(iter.nextToken()) -} - -func (iter *Iterator) readUint32(c byte) (ret uint32) { - ind := intDigits[c] - if ind == 0 { - iter.assertInteger() - return 0 // single zero - } - if ind == invalidCharForNumber { - iter.ReportError("readUint32", "unexpected character: "+string([]byte{byte(ind)})) - return - } - value := uint32(ind) - if iter.tail-iter.head > 10 { - i := iter.head - ind2 := intDigits[iter.buf[i]] - if ind2 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - i++ - ind3 := intDigits[iter.buf[i]] - if ind3 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10 + uint32(ind2) - } - //iter.head = i + 1 - //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) - i++ - ind4 := intDigits[iter.buf[i]] - if ind4 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100 + uint32(ind2)*10 + uint32(ind3) - } - i++ - ind5 := intDigits[iter.buf[i]] - if ind5 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000 + uint32(ind2)*100 + uint32(ind3)*10 + uint32(ind4) - } - i++ - ind6 := intDigits[iter.buf[i]] - if ind6 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10000 + uint32(ind2)*1000 + uint32(ind3)*100 + uint32(ind4)*10 + uint32(ind5) - } - i++ - ind7 := intDigits[iter.buf[i]] - if ind7 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100000 + uint32(ind2)*10000 + uint32(ind3)*1000 + uint32(ind4)*100 + uint32(ind5)*10 + uint32(ind6) - } - i++ - ind8 := intDigits[iter.buf[i]] - if ind8 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000000 + uint32(ind2)*100000 + uint32(ind3)*10000 + uint32(ind4)*1000 + uint32(ind5)*100 + uint32(ind6)*10 + uint32(ind7) - } - i++ - ind9 := intDigits[iter.buf[i]] - value = value*10000000 + uint32(ind2)*1000000 + uint32(ind3)*100000 + uint32(ind4)*10000 + uint32(ind5)*1000 + uint32(ind6)*100 + uint32(ind7)*10 + uint32(ind8) - iter.head = i - if ind9 == invalidCharForNumber { - iter.assertInteger() - return value - } - } - for { - for i := iter.head; i < iter.tail; i++ { - ind = intDigits[iter.buf[i]] - if ind == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - if value > uint32SafeToMultiply10 { - value2 := (value << 3) + (value << 1) + uint32(ind) - if value2 < value { - iter.ReportError("readUint32", "overflow") - return - } - value = value2 - continue - } - value = (value << 3) + (value << 1) + uint32(ind) - } - if !iter.loadMore() { - iter.assertInteger() - return value - } - } -} - -// ReadInt64 read int64 -func (iter *Iterator) ReadInt64() (ret int64) { - c := iter.nextToken() - if c == '-' { - val := iter.readUint64(iter.readByte()) - if val > math.MaxInt64+1 { - iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) - return - } - return -int64(val) - } - val := iter.readUint64(c) - if val > math.MaxInt64 { - iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) - return - } - return int64(val) -} - -// ReadUint64 read uint64 -func (iter *Iterator) ReadUint64() uint64 { - return iter.readUint64(iter.nextToken()) -} - -func (iter *Iterator) readUint64(c byte) (ret uint64) { - ind := intDigits[c] - if ind == 0 { - iter.assertInteger() - return 0 // single zero - } - if ind == invalidCharForNumber { - iter.ReportError("readUint64", "unexpected character: "+string([]byte{byte(ind)})) - return - } - value := uint64(ind) - if iter.tail-iter.head > 10 { - i := iter.head - ind2 := intDigits[iter.buf[i]] - if ind2 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - i++ - ind3 := intDigits[iter.buf[i]] - if ind3 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10 + uint64(ind2) - } - //iter.head = i + 1 - //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) - i++ - ind4 := intDigits[iter.buf[i]] - if ind4 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100 + uint64(ind2)*10 + uint64(ind3) - } - i++ - ind5 := intDigits[iter.buf[i]] - if ind5 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000 + uint64(ind2)*100 + uint64(ind3)*10 + uint64(ind4) - } - i++ - ind6 := intDigits[iter.buf[i]] - if ind6 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*10000 + uint64(ind2)*1000 + uint64(ind3)*100 + uint64(ind4)*10 + uint64(ind5) - } - i++ - ind7 := intDigits[iter.buf[i]] - if ind7 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*100000 + uint64(ind2)*10000 + uint64(ind3)*1000 + uint64(ind4)*100 + uint64(ind5)*10 + uint64(ind6) - } - i++ - ind8 := intDigits[iter.buf[i]] - if ind8 == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value*1000000 + uint64(ind2)*100000 + uint64(ind3)*10000 + uint64(ind4)*1000 + uint64(ind5)*100 + uint64(ind6)*10 + uint64(ind7) - } - i++ - ind9 := intDigits[iter.buf[i]] - value = value*10000000 + uint64(ind2)*1000000 + uint64(ind3)*100000 + uint64(ind4)*10000 + uint64(ind5)*1000 + uint64(ind6)*100 + uint64(ind7)*10 + uint64(ind8) - iter.head = i - if ind9 == invalidCharForNumber { - iter.assertInteger() - return value - } - } - for { - for i := iter.head; i < iter.tail; i++ { - ind = intDigits[iter.buf[i]] - if ind == invalidCharForNumber { - iter.head = i - iter.assertInteger() - return value - } - if value > uint64SafeToMultiple10 { - value2 := (value << 3) + (value << 1) + uint64(ind) - if value2 < value { - iter.ReportError("readUint64", "overflow") - return - } - value = value2 - continue - } - value = (value << 3) + (value << 1) + uint64(ind) - } - if !iter.loadMore() { - iter.assertInteger() - return value - } - } -} - -func (iter *Iterator) assertInteger() { - if iter.head < iter.tail && iter.buf[iter.head] == '.' { - iter.ReportError("assertInteger", "can not decode float as int") - } -} diff --git a/vendor/github.com/json-iterator/go/iter_object.go b/vendor/github.com/json-iterator/go/iter_object.go deleted file mode 100644 index 58ee89c8..00000000 --- a/vendor/github.com/json-iterator/go/iter_object.go +++ /dev/null @@ -1,267 +0,0 @@ -package jsoniter - -import ( - "fmt" - "strings" -) - -// ReadObject read one field from object. -// If object ended, returns empty string. -// Otherwise, returns the field name. -func (iter *Iterator) ReadObject() (ret string) { - c := iter.nextToken() - switch c { - case 'n': - iter.skipThreeBytes('u', 'l', 'l') - return "" // null - case '{': - c = iter.nextToken() - if c == '"' { - iter.unreadByte() - field := iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - return field - } - if c == '}' { - return "" // end of object - } - iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) - return - case ',': - field := iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - return field - case '}': - return "" // end of object - default: - iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c}))) - return - } -} - -// CaseInsensitive -func (iter *Iterator) readFieldHash() int64 { - hash := int64(0x811c9dc5) - c := iter.nextToken() - if c != '"' { - iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c})) - return 0 - } - for { - for i := iter.head; i < iter.tail; i++ { - // require ascii string and no escape - b := iter.buf[i] - if b == '\\' { - iter.head = i - for _, b := range iter.readStringSlowPath() { - if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { - b += 'a' - 'A' - } - hash ^= int64(b) - hash *= 0x1000193 - } - c = iter.nextToken() - if c != ':' { - iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) - return 0 - } - return hash - } - if b == '"' { - iter.head = i + 1 - c = iter.nextToken() - if c != ':' { - iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) - return 0 - } - return hash - } - if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { - b += 'a' - 'A' - } - hash ^= int64(b) - hash *= 0x1000193 - } - if !iter.loadMore() { - iter.ReportError("readFieldHash", `incomplete field name`) - return 0 - } - } -} - -func calcHash(str string, caseSensitive bool) int64 { - if !caseSensitive { - str = strings.ToLower(str) - } - hash := int64(0x811c9dc5) - for _, b := range []byte(str) { - hash ^= int64(b) - hash *= 0x1000193 - } - return int64(hash) -} - -// ReadObjectCB read object with callback, the key is ascii only and field name not copied -func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { - c := iter.nextToken() - var field string - if c == '{' { - if !iter.incrementDepth() { - return false - } - c = iter.nextToken() - if c == '"' { - iter.unreadByte() - field = iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - if !callback(iter, field) { - iter.decrementDepth() - return false - } - c = iter.nextToken() - for c == ',' { - field = iter.ReadString() - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - if !callback(iter, field) { - iter.decrementDepth() - return false - } - c = iter.nextToken() - } - if c != '}' { - iter.ReportError("ReadObjectCB", `object not ended with }`) - iter.decrementDepth() - return false - } - return iter.decrementDepth() - } - if c == '}' { - return iter.decrementDepth() - } - iter.ReportError("ReadObjectCB", `expect " after {, but found `+string([]byte{c})) - iter.decrementDepth() - return false - } - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return true // null - } - iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c})) - return false -} - -// ReadMapCB read map with callback, the key can be any string -func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool { - c := iter.nextToken() - if c == '{' { - if !iter.incrementDepth() { - return false - } - c = iter.nextToken() - if c == '"' { - iter.unreadByte() - field := iter.ReadString() - if iter.nextToken() != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - iter.decrementDepth() - return false - } - if !callback(iter, field) { - iter.decrementDepth() - return false - } - c = iter.nextToken() - for c == ',' { - field = iter.ReadString() - if iter.nextToken() != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - iter.decrementDepth() - return false - } - if !callback(iter, field) { - iter.decrementDepth() - return false - } - c = iter.nextToken() - } - if c != '}' { - iter.ReportError("ReadMapCB", `object not ended with }`) - iter.decrementDepth() - return false - } - return iter.decrementDepth() - } - if c == '}' { - return iter.decrementDepth() - } - iter.ReportError("ReadMapCB", `expect " after {, but found `+string([]byte{c})) - iter.decrementDepth() - return false - } - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return true // null - } - iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) - return false -} - -func (iter *Iterator) readObjectStart() bool { - c := iter.nextToken() - if c == '{' { - c = iter.nextToken() - if c == '}' { - return false - } - iter.unreadByte() - return true - } else if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return false - } - iter.ReportError("readObjectStart", "expect { or n, but found "+string([]byte{c})) - return false -} - -func (iter *Iterator) readObjectFieldAsBytes() (ret []byte) { - str := iter.ReadStringAsSlice() - if iter.skipWhitespacesWithoutLoadMore() { - if ret == nil { - ret = make([]byte, len(str)) - copy(ret, str) - } - if !iter.loadMore() { - return - } - } - if iter.buf[iter.head] != ':' { - iter.ReportError("readObjectFieldAsBytes", "expect : after object field, but found "+string([]byte{iter.buf[iter.head]})) - return - } - iter.head++ - if iter.skipWhitespacesWithoutLoadMore() { - if ret == nil { - ret = make([]byte, len(str)) - copy(ret, str) - } - if !iter.loadMore() { - return - } - } - if ret == nil { - return str - } - return ret -} diff --git a/vendor/github.com/json-iterator/go/iter_skip.go b/vendor/github.com/json-iterator/go/iter_skip.go deleted file mode 100644 index e91eefb1..00000000 --- a/vendor/github.com/json-iterator/go/iter_skip.go +++ /dev/null @@ -1,130 +0,0 @@ -package jsoniter - -import "fmt" - -// ReadNil reads a json object as nil and -// returns whether it's a nil or not -func (iter *Iterator) ReadNil() (ret bool) { - c := iter.nextToken() - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') // null - return true - } - iter.unreadByte() - return false -} - -// ReadBool reads a json object as BoolValue -func (iter *Iterator) ReadBool() (ret bool) { - c := iter.nextToken() - if c == 't' { - iter.skipThreeBytes('r', 'u', 'e') - return true - } - if c == 'f' { - iter.skipFourBytes('a', 'l', 's', 'e') - return false - } - iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c})) - return -} - -// SkipAndReturnBytes skip next JSON element, and return its content as []byte. -// The []byte can be kept, it is a copy of data. -func (iter *Iterator) SkipAndReturnBytes() []byte { - iter.startCapture(iter.head) - iter.Skip() - return iter.stopCapture() -} - -// SkipAndAppendBytes skips next JSON element and appends its content to -// buffer, returning the result. -func (iter *Iterator) SkipAndAppendBytes(buf []byte) []byte { - iter.startCaptureTo(buf, iter.head) - iter.Skip() - return iter.stopCapture() -} - -func (iter *Iterator) startCaptureTo(buf []byte, captureStartedAt int) { - if iter.captured != nil { - panic("already in capture mode") - } - iter.captureStartedAt = captureStartedAt - iter.captured = buf -} - -func (iter *Iterator) startCapture(captureStartedAt int) { - iter.startCaptureTo(make([]byte, 0, 32), captureStartedAt) -} - -func (iter *Iterator) stopCapture() []byte { - if iter.captured == nil { - panic("not in capture mode") - } - captured := iter.captured - remaining := iter.buf[iter.captureStartedAt:iter.head] - iter.captureStartedAt = -1 - iter.captured = nil - return append(captured, remaining...) -} - -// Skip skips a json object and positions to relatively the next json object -func (iter *Iterator) Skip() { - c := iter.nextToken() - switch c { - case '"': - iter.skipString() - case 'n': - iter.skipThreeBytes('u', 'l', 'l') // null - case 't': - iter.skipThreeBytes('r', 'u', 'e') // true - case 'f': - iter.skipFourBytes('a', 'l', 's', 'e') // false - case '0': - iter.unreadByte() - iter.ReadFloat32() - case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': - iter.skipNumber() - case '[': - iter.skipArray() - case '{': - iter.skipObject() - default: - iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) - return - } -} - -func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) { - if iter.readByte() != b1 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } - if iter.readByte() != b2 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } - if iter.readByte() != b3 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } - if iter.readByte() != b4 { - iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) - return - } -} - -func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) { - if iter.readByte() != b1 { - iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) - return - } - if iter.readByte() != b2 { - iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) - return - } - if iter.readByte() != b3 { - iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) - return - } -} diff --git a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go deleted file mode 100644 index 9303de41..00000000 --- a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go +++ /dev/null @@ -1,163 +0,0 @@ -//+build jsoniter_sloppy - -package jsoniter - -// sloppy but faster implementation, do not validate the input json - -func (iter *Iterator) skipNumber() { - for { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case ' ', '\n', '\r', '\t', ',', '}', ']': - iter.head = i - return - } - } - if !iter.loadMore() { - return - } - } -} - -func (iter *Iterator) skipArray() { - level := 1 - if !iter.incrementDepth() { - return - } - for { - for i := iter.head; i < iter.tail; i++ { - switch iter.buf[i] { - case '"': // If inside string, skip it - iter.head = i + 1 - iter.skipString() - i = iter.head - 1 // it will be i++ soon - case '[': // If open symbol, increase level - level++ - if !iter.incrementDepth() { - return - } - case ']': // If close symbol, increase level - level-- - if !iter.decrementDepth() { - return - } - - // If we have returned to the original level, we're done - if level == 0 { - iter.head = i + 1 - return - } - } - } - if !iter.loadMore() { - iter.ReportError("skipObject", "incomplete array") - return - } - } -} - -func (iter *Iterator) skipObject() { - level := 1 - if !iter.incrementDepth() { - return - } - - for { - for i := iter.head; i < iter.tail; i++ { - switch iter.buf[i] { - case '"': // If inside string, skip it - iter.head = i + 1 - iter.skipString() - i = iter.head - 1 // it will be i++ soon - case '{': // If open symbol, increase level - level++ - if !iter.incrementDepth() { - return - } - case '}': // If close symbol, increase level - level-- - if !iter.decrementDepth() { - return - } - - // If we have returned to the original level, we're done - if level == 0 { - iter.head = i + 1 - return - } - } - } - if !iter.loadMore() { - iter.ReportError("skipObject", "incomplete object") - return - } - } -} - -func (iter *Iterator) skipString() { - for { - end, escaped := iter.findStringEnd() - if end == -1 { - if !iter.loadMore() { - iter.ReportError("skipString", "incomplete string") - return - } - if escaped { - iter.head = 1 // skip the first char as last char read is \ - } - } else { - iter.head = end - return - } - } -} - -// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go -// Tries to find the end of string -// Support if string contains escaped quote symbols. -func (iter *Iterator) findStringEnd() (int, bool) { - escaped := false - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - if c == '"' { - if !escaped { - return i + 1, false - } - j := i - 1 - for { - if j < iter.head || iter.buf[j] != '\\' { - // even number of backslashes - // either end of buffer, or " found - return i + 1, true - } - j-- - if j < iter.head || iter.buf[j] != '\\' { - // odd number of backslashes - // it is \" or \\\" - break - } - j-- - } - } else if c == '\\' { - escaped = true - } - } - j := iter.tail - 1 - for { - if j < iter.head || iter.buf[j] != '\\' { - // even number of backslashes - // either end of buffer, or " found - return -1, false // do not end with \ - } - j-- - if j < iter.head || iter.buf[j] != '\\' { - // odd number of backslashes - // it is \" or \\\" - break - } - j-- - - } - return -1, true // end with \ -} diff --git a/vendor/github.com/json-iterator/go/iter_skip_strict.go b/vendor/github.com/json-iterator/go/iter_skip_strict.go deleted file mode 100644 index 6cf66d04..00000000 --- a/vendor/github.com/json-iterator/go/iter_skip_strict.go +++ /dev/null @@ -1,99 +0,0 @@ -//+build !jsoniter_sloppy - -package jsoniter - -import ( - "fmt" - "io" -) - -func (iter *Iterator) skipNumber() { - if !iter.trySkipNumber() { - iter.unreadByte() - if iter.Error != nil && iter.Error != io.EOF { - return - } - iter.ReadFloat64() - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = nil - iter.ReadBigFloat() - } - } -} - -func (iter *Iterator) trySkipNumber() bool { - dotFound := false - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - case '.': - if dotFound { - iter.ReportError("validateNumber", `more than one dot found in number`) - return true // already failed - } - if i+1 == iter.tail { - return false - } - c = iter.buf[i+1] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - default: - iter.ReportError("validateNumber", `missing digit after dot`) - return true // already failed - } - dotFound = true - default: - switch c { - case ',', ']', '}', ' ', '\t', '\n', '\r': - if iter.head == i { - return false // if - without following digits - } - iter.head = i - return true // must be valid - } - return false // may be invalid - } - } - return false -} - -func (iter *Iterator) skipString() { - if !iter.trySkipString() { - iter.unreadByte() - iter.ReadString() - } -} - -func (iter *Iterator) trySkipString() bool { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - if c == '"' { - iter.head = i + 1 - return true // valid - } else if c == '\\' { - return false - } else if c < ' ' { - iter.ReportError("trySkipString", - fmt.Sprintf(`invalid control character found: %d`, c)) - return true // already failed - } - } - return false -} - -func (iter *Iterator) skipObject() { - iter.unreadByte() - iter.ReadObjectCB(func(iter *Iterator, field string) bool { - iter.Skip() - return true - }) -} - -func (iter *Iterator) skipArray() { - iter.unreadByte() - iter.ReadArrayCB(func(iter *Iterator) bool { - iter.Skip() - return true - }) -} diff --git a/vendor/github.com/json-iterator/go/iter_str.go b/vendor/github.com/json-iterator/go/iter_str.go deleted file mode 100644 index adc487ea..00000000 --- a/vendor/github.com/json-iterator/go/iter_str.go +++ /dev/null @@ -1,215 +0,0 @@ -package jsoniter - -import ( - "fmt" - "unicode/utf16" -) - -// ReadString read string from iterator -func (iter *Iterator) ReadString() (ret string) { - c := iter.nextToken() - if c == '"' { - for i := iter.head; i < iter.tail; i++ { - c := iter.buf[i] - if c == '"' { - ret = string(iter.buf[iter.head:i]) - iter.head = i + 1 - return ret - } else if c == '\\' { - break - } else if c < ' ' { - iter.ReportError("ReadString", - fmt.Sprintf(`invalid control character found: %d`, c)) - return - } - } - return iter.readStringSlowPath() - } else if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return "" - } - iter.ReportError("ReadString", `expects " or n, but found `+string([]byte{c})) - return -} - -func (iter *Iterator) readStringSlowPath() (ret string) { - var str []byte - var c byte - for iter.Error == nil { - c = iter.readByte() - if c == '"' { - return string(str) - } - if c == '\\' { - c = iter.readByte() - str = iter.readEscapedChar(c, str) - } else { - str = append(str, c) - } - } - iter.ReportError("readStringSlowPath", "unexpected end of input") - return -} - -func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte { - switch c { - case 'u': - r := iter.readU4() - if utf16.IsSurrogate(r) { - c = iter.readByte() - if iter.Error != nil { - return nil - } - if c != '\\' { - iter.unreadByte() - str = appendRune(str, r) - return str - } - c = iter.readByte() - if iter.Error != nil { - return nil - } - if c != 'u' { - str = appendRune(str, r) - return iter.readEscapedChar(c, str) - } - r2 := iter.readU4() - if iter.Error != nil { - return nil - } - combined := utf16.DecodeRune(r, r2) - if combined == '\uFFFD' { - str = appendRune(str, r) - str = appendRune(str, r2) - } else { - str = appendRune(str, combined) - } - } else { - str = appendRune(str, r) - } - case '"': - str = append(str, '"') - case '\\': - str = append(str, '\\') - case '/': - str = append(str, '/') - case 'b': - str = append(str, '\b') - case 'f': - str = append(str, '\f') - case 'n': - str = append(str, '\n') - case 'r': - str = append(str, '\r') - case 't': - str = append(str, '\t') - default: - iter.ReportError("readEscapedChar", - `invalid escape char after \`) - return nil - } - return str -} - -// ReadStringAsSlice read string from iterator without copying into string form. -// The []byte can not be kept, as it will change after next iterator call. -func (iter *Iterator) ReadStringAsSlice() (ret []byte) { - c := iter.nextToken() - if c == '"' { - for i := iter.head; i < iter.tail; i++ { - // require ascii string and no escape - // for: field name, base64, number - if iter.buf[i] == '"' { - // fast path: reuse the underlying buffer - ret = iter.buf[iter.head:i] - iter.head = i + 1 - return ret - } - } - readLen := iter.tail - iter.head - copied := make([]byte, readLen, readLen*2) - copy(copied, iter.buf[iter.head:iter.tail]) - iter.head = iter.tail - for iter.Error == nil { - c := iter.readByte() - if c == '"' { - return copied - } - copied = append(copied, c) - } - return copied - } - iter.ReportError("ReadStringAsSlice", `expects " or n, but found `+string([]byte{c})) - return -} - -func (iter *Iterator) readU4() (ret rune) { - for i := 0; i < 4; i++ { - c := iter.readByte() - if iter.Error != nil { - return - } - if c >= '0' && c <= '9' { - ret = ret*16 + rune(c-'0') - } else if c >= 'a' && c <= 'f' { - ret = ret*16 + rune(c-'a'+10) - } else if c >= 'A' && c <= 'F' { - ret = ret*16 + rune(c-'A'+10) - } else { - iter.ReportError("readU4", "expects 0~9 or a~f, but found "+string([]byte{c})) - return - } - } - return ret -} - -const ( - t1 = 0x00 // 0000 0000 - tx = 0x80 // 1000 0000 - t2 = 0xC0 // 1100 0000 - t3 = 0xE0 // 1110 0000 - t4 = 0xF0 // 1111 0000 - t5 = 0xF8 // 1111 1000 - - maskx = 0x3F // 0011 1111 - mask2 = 0x1F // 0001 1111 - mask3 = 0x0F // 0000 1111 - mask4 = 0x07 // 0000 0111 - - rune1Max = 1<<7 - 1 - rune2Max = 1<<11 - 1 - rune3Max = 1<<16 - 1 - - surrogateMin = 0xD800 - surrogateMax = 0xDFFF - - maxRune = '\U0010FFFF' // Maximum valid Unicode code point. - runeError = '\uFFFD' // the "error" Rune or "Unicode replacement character" -) - -func appendRune(p []byte, r rune) []byte { - // Negative values are erroneous. Making it unsigned addresses the problem. - switch i := uint32(r); { - case i <= rune1Max: - p = append(p, byte(r)) - return p - case i <= rune2Max: - p = append(p, t2|byte(r>>6)) - p = append(p, tx|byte(r)&maskx) - return p - case i > maxRune, surrogateMin <= i && i <= surrogateMax: - r = runeError - fallthrough - case i <= rune3Max: - p = append(p, t3|byte(r>>12)) - p = append(p, tx|byte(r>>6)&maskx) - p = append(p, tx|byte(r)&maskx) - return p - default: - p = append(p, t4|byte(r>>18)) - p = append(p, tx|byte(r>>12)&maskx) - p = append(p, tx|byte(r>>6)&maskx) - p = append(p, tx|byte(r)&maskx) - return p - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter.go b/vendor/github.com/json-iterator/go/jsoniter.go deleted file mode 100644 index c2934f91..00000000 --- a/vendor/github.com/json-iterator/go/jsoniter.go +++ /dev/null @@ -1,18 +0,0 @@ -// Package jsoniter implements encoding and decoding of JSON as defined in -// RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json. -// Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter -// and variable type declarations (if any). -// jsoniter interfaces gives 100% compatibility with code using standard lib. -// -// "JSON and Go" -// (https://golang.org/doc/articles/json_and_go.html) -// gives a description of how Marshal/Unmarshal operate -// between arbitrary or predefined json objects and bytes, -// and it applies to jsoniter.Marshal/Unmarshal as well. -// -// Besides, jsoniter.Iterator provides a different set of interfaces -// iterating given bytes/string/reader -// and yielding parsed elements one by one. -// This set of interfaces reads input as required and gives -// better performance. -package jsoniter diff --git a/vendor/github.com/json-iterator/go/pool.go b/vendor/github.com/json-iterator/go/pool.go deleted file mode 100644 index e2389b56..00000000 --- a/vendor/github.com/json-iterator/go/pool.go +++ /dev/null @@ -1,42 +0,0 @@ -package jsoniter - -import ( - "io" -) - -// IteratorPool a thread safe pool of iterators with same configuration -type IteratorPool interface { - BorrowIterator(data []byte) *Iterator - ReturnIterator(iter *Iterator) -} - -// StreamPool a thread safe pool of streams with same configuration -type StreamPool interface { - BorrowStream(writer io.Writer) *Stream - ReturnStream(stream *Stream) -} - -func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream { - stream := cfg.streamPool.Get().(*Stream) - stream.Reset(writer) - return stream -} - -func (cfg *frozenConfig) ReturnStream(stream *Stream) { - stream.out = nil - stream.Error = nil - stream.Attachment = nil - cfg.streamPool.Put(stream) -} - -func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator { - iter := cfg.iteratorPool.Get().(*Iterator) - iter.ResetBytes(data) - return iter -} - -func (cfg *frozenConfig) ReturnIterator(iter *Iterator) { - iter.Error = nil - iter.Attachment = nil - cfg.iteratorPool.Put(iter) -} diff --git a/vendor/github.com/json-iterator/go/reflect.go b/vendor/github.com/json-iterator/go/reflect.go deleted file mode 100644 index 39acb320..00000000 --- a/vendor/github.com/json-iterator/go/reflect.go +++ /dev/null @@ -1,337 +0,0 @@ -package jsoniter - -import ( - "fmt" - "reflect" - "unsafe" - - "github.com/modern-go/reflect2" -) - -// ValDecoder is an internal type registered to cache as needed. -// Don't confuse jsoniter.ValDecoder with json.Decoder. -// For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). -// -// Reflection on type to create decoders, which is then cached -// Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions -// 1. create instance of new value, for example *int will need a int to be allocated -// 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New -// 3. assignment to map, both key and value will be reflect.Value -// For a simple struct binding, it will be reflect.Value free and allocation free -type ValDecoder interface { - Decode(ptr unsafe.Pointer, iter *Iterator) -} - -// ValEncoder is an internal type registered to cache as needed. -// Don't confuse jsoniter.ValEncoder with json.Encoder. -// For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). -type ValEncoder interface { - IsEmpty(ptr unsafe.Pointer) bool - Encode(ptr unsafe.Pointer, stream *Stream) -} - -type checkIsEmpty interface { - IsEmpty(ptr unsafe.Pointer) bool -} - -type ctx struct { - *frozenConfig - prefix string - encoders map[reflect2.Type]ValEncoder - decoders map[reflect2.Type]ValDecoder -} - -func (b *ctx) caseSensitive() bool { - if b.frozenConfig == nil { - // default is case-insensitive - return false - } - return b.frozenConfig.caseSensitive -} - -func (b *ctx) append(prefix string) *ctx { - return &ctx{ - frozenConfig: b.frozenConfig, - prefix: b.prefix + " " + prefix, - encoders: b.encoders, - decoders: b.decoders, - } -} - -// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal -func (iter *Iterator) ReadVal(obj interface{}) { - depth := iter.depth - cacheKey := reflect2.RTypeOf(obj) - decoder := iter.cfg.getDecoderFromCache(cacheKey) - if decoder == nil { - typ := reflect2.TypeOf(obj) - if typ == nil || typ.Kind() != reflect.Ptr { - iter.ReportError("ReadVal", "can only unmarshal into pointer") - return - } - decoder = iter.cfg.DecoderOf(typ) - } - ptr := reflect2.PtrOf(obj) - if ptr == nil { - iter.ReportError("ReadVal", "can not read into nil pointer") - return - } - decoder.Decode(ptr, iter) - if iter.depth != depth { - iter.ReportError("ReadVal", "unexpected mismatched nesting") - return - } -} - -// WriteVal copy the go interface into underlying JSON, same as json.Marshal -func (stream *Stream) WriteVal(val interface{}) { - if nil == val { - stream.WriteNil() - return - } - cacheKey := reflect2.RTypeOf(val) - encoder := stream.cfg.getEncoderFromCache(cacheKey) - if encoder == nil { - typ := reflect2.TypeOf(val) - encoder = stream.cfg.EncoderOf(typ) - } - encoder.Encode(reflect2.PtrOf(val), stream) -} - -func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder { - cacheKey := typ.RType() - decoder := cfg.getDecoderFromCache(cacheKey) - if decoder != nil { - return decoder - } - ctx := &ctx{ - frozenConfig: cfg, - prefix: "", - decoders: map[reflect2.Type]ValDecoder{}, - encoders: map[reflect2.Type]ValEncoder{}, - } - ptrType := typ.(*reflect2.UnsafePtrType) - decoder = decoderOfType(ctx, ptrType.Elem()) - cfg.addDecoderToCache(cacheKey, decoder) - return decoder -} - -func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := getTypeDecoderFromExtension(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfType(ctx, typ) - for _, extension := range extensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) - for _, extension := range ctx.extraExtensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - return decoder -} - -func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := ctx.decoders[typ] - if decoder != nil { - return decoder - } - placeholder := &placeholderDecoder{} - ctx.decoders[typ] = placeholder - decoder = _createDecoderOfType(ctx, typ) - placeholder.decoder = decoder - return decoder -} - -func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := createDecoderOfJsonRawMessage(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfJsonNumber(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfMarshaler(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfAny(ctx, typ) - if decoder != nil { - return decoder - } - decoder = createDecoderOfNative(ctx, typ) - if decoder != nil { - return decoder - } - switch typ.Kind() { - case reflect.Interface: - ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType) - if isIFace { - return &ifaceDecoder{valType: ifaceType} - } - return &efaceDecoder{} - case reflect.Struct: - return decoderOfStruct(ctx, typ) - case reflect.Array: - return decoderOfArray(ctx, typ) - case reflect.Slice: - return decoderOfSlice(ctx, typ) - case reflect.Map: - return decoderOfMap(ctx, typ) - case reflect.Ptr: - return decoderOfOptional(ctx, typ) - default: - return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} - } -} - -func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder { - cacheKey := typ.RType() - encoder := cfg.getEncoderFromCache(cacheKey) - if encoder != nil { - return encoder - } - ctx := &ctx{ - frozenConfig: cfg, - prefix: "", - decoders: map[reflect2.Type]ValDecoder{}, - encoders: map[reflect2.Type]ValEncoder{}, - } - encoder = encoderOfType(ctx, typ) - if typ.LikePtr() { - encoder = &onePtrEncoder{encoder} - } - cfg.addEncoderToCache(cacheKey, encoder) - return encoder -} - -type onePtrEncoder struct { - encoder ValEncoder -} - -func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) -} - -func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) -} - -func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := getTypeEncoderFromExtension(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfType(ctx, typ) - for _, extension := range extensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) - for _, extension := range ctx.extraExtensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - return encoder -} - -func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := ctx.encoders[typ] - if encoder != nil { - return encoder - } - placeholder := &placeholderEncoder{} - ctx.encoders[typ] = placeholder - encoder = _createEncoderOfType(ctx, typ) - placeholder.encoder = encoder - return encoder -} -func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := createEncoderOfJsonRawMessage(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfJsonNumber(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfMarshaler(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfAny(ctx, typ) - if encoder != nil { - return encoder - } - encoder = createEncoderOfNative(ctx, typ) - if encoder != nil { - return encoder - } - kind := typ.Kind() - switch kind { - case reflect.Interface: - return &dynamicEncoder{typ} - case reflect.Struct: - return encoderOfStruct(ctx, typ) - case reflect.Array: - return encoderOfArray(ctx, typ) - case reflect.Slice: - return encoderOfSlice(ctx, typ) - case reflect.Map: - return encoderOfMap(ctx, typ) - case reflect.Ptr: - return encoderOfOptional(ctx, typ) - default: - return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} - } -} - -type lazyErrorDecoder struct { - err error -} - -func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.WhatIsNext() != NilValue { - if iter.Error == nil { - iter.Error = decoder.err - } - } else { - iter.Skip() - } -} - -type lazyErrorEncoder struct { - err error -} - -func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if ptr == nil { - stream.WriteNil() - } else if stream.Error == nil { - stream.Error = encoder.err - } -} - -func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type placeholderDecoder struct { - decoder ValDecoder -} - -func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.decoder.Decode(ptr, iter) -} - -type placeholderEncoder struct { - encoder ValEncoder -} - -func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.encoder.Encode(ptr, stream) -} - -func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.encoder.IsEmpty(ptr) -} diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go deleted file mode 100644 index 13a0b7b0..00000000 --- a/vendor/github.com/json-iterator/go/reflect_array.go +++ /dev/null @@ -1,104 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "unsafe" -) - -func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { - arrayType := typ.(*reflect2.UnsafeArrayType) - decoder := decoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) - return &arrayDecoder{arrayType, decoder} -} - -func encoderOfArray(ctx *ctx, typ reflect2.Type) ValEncoder { - arrayType := typ.(*reflect2.UnsafeArrayType) - if arrayType.Len() == 0 { - return emptyArrayEncoder{} - } - encoder := encoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) - return &arrayEncoder{arrayType, encoder} -} - -type emptyArrayEncoder struct{} - -func (encoder emptyArrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteEmptyArray() -} - -func (encoder emptyArrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return true -} - -type arrayEncoder struct { - arrayType *reflect2.UnsafeArrayType - elemEncoder ValEncoder -} - -func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteArrayStart() - elemPtr := unsafe.Pointer(ptr) - encoder.elemEncoder.Encode(elemPtr, stream) - for i := 1; i < encoder.arrayType.Len(); i++ { - stream.WriteMore() - elemPtr = encoder.arrayType.UnsafeGetIndex(ptr, i) - encoder.elemEncoder.Encode(elemPtr, stream) - } - stream.WriteArrayEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v: %s", encoder.arrayType, stream.Error.Error()) - } -} - -func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type arrayDecoder struct { - arrayType *reflect2.UnsafeArrayType - elemDecoder ValDecoder -} - -func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.doDecode(ptr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.arrayType, iter.Error.Error()) - } -} - -func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - arrayType := decoder.arrayType - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - return - } - if c != '[' { - iter.ReportError("decode array", "expect [ or n, but found "+string([]byte{c})) - return - } - c = iter.nextToken() - if c == ']' { - return - } - iter.unreadByte() - elemPtr := arrayType.UnsafeGetIndex(ptr, 0) - decoder.elemDecoder.Decode(elemPtr, iter) - length := 1 - for c = iter.nextToken(); c == ','; c = iter.nextToken() { - if length >= arrayType.Len() { - iter.Skip() - continue - } - idx := length - length += 1 - elemPtr = arrayType.UnsafeGetIndex(ptr, idx) - decoder.elemDecoder.Decode(elemPtr, iter) - } - if c != ']' { - iter.ReportError("decode array", "expect ], but found "+string([]byte{c})) - return - } -} diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go deleted file mode 100644 index 8b6bc8b4..00000000 --- a/vendor/github.com/json-iterator/go/reflect_dynamic.go +++ /dev/null @@ -1,70 +0,0 @@ -package jsoniter - -import ( - "github.com/modern-go/reflect2" - "reflect" - "unsafe" -) - -type dynamicEncoder struct { - valType reflect2.Type -} - -func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - stream.WriteVal(obj) -} - -func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.valType.UnsafeIndirect(ptr) == nil -} - -type efaceDecoder struct { -} - -func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - pObj := (*interface{})(ptr) - obj := *pObj - if obj == nil { - *pObj = iter.Read() - return - } - typ := reflect2.TypeOf(obj) - if typ.Kind() != reflect.Ptr { - *pObj = iter.Read() - return - } - ptrType := typ.(*reflect2.UnsafePtrType) - ptrElemType := ptrType.Elem() - if iter.WhatIsNext() == NilValue { - if ptrElemType.Kind() != reflect.Ptr { - iter.skipFourBytes('n', 'u', 'l', 'l') - *pObj = nil - return - } - } - if reflect2.IsNil(obj) { - obj := ptrElemType.New() - iter.ReadVal(obj) - *pObj = obj - return - } - iter.ReadVal(obj) -} - -type ifaceDecoder struct { - valType *reflect2.UnsafeIFaceType -} - -func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - decoder.valType.UnsafeSet(ptr, decoder.valType.UnsafeNew()) - return - } - obj := decoder.valType.UnsafeIndirect(ptr) - if reflect2.IsNil(obj) { - iter.ReportError("decode non empty interface", "can not unmarshal into nil") - return - } - iter.ReadVal(obj) -} diff --git a/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go deleted file mode 100644 index 74a97bfe..00000000 --- a/vendor/github.com/json-iterator/go/reflect_extension.go +++ /dev/null @@ -1,483 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "reflect" - "sort" - "strings" - "unicode" - "unsafe" -) - -var typeDecoders = map[string]ValDecoder{} -var fieldDecoders = map[string]ValDecoder{} -var typeEncoders = map[string]ValEncoder{} -var fieldEncoders = map[string]ValEncoder{} -var extensions = []Extension{} - -// StructDescriptor describe how should we encode/decode the struct -type StructDescriptor struct { - Type reflect2.Type - Fields []*Binding -} - -// GetField get one field from the descriptor by its name. -// Can not use map here to keep field orders. -func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { - for _, binding := range structDescriptor.Fields { - if binding.Field.Name() == fieldName { - return binding - } - } - return nil -} - -// Binding describe how should we encode/decode the struct field -type Binding struct { - levels []int - Field reflect2.StructField - FromNames []string - ToNames []string - Encoder ValEncoder - Decoder ValDecoder -} - -// Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder. -// Can also rename fields by UpdateStructDescriptor. -type Extension interface { - UpdateStructDescriptor(structDescriptor *StructDescriptor) - CreateMapKeyDecoder(typ reflect2.Type) ValDecoder - CreateMapKeyEncoder(typ reflect2.Type) ValEncoder - CreateDecoder(typ reflect2.Type) ValDecoder - CreateEncoder(typ reflect2.Type) ValEncoder - DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder - DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder -} - -// DummyExtension embed this type get dummy implementation for all methods of Extension -type DummyExtension struct { -} - -// UpdateStructDescriptor No-op -func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { -} - -// CreateMapKeyDecoder No-op -func (extension *DummyExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateMapKeyEncoder No-op -func (extension *DummyExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// CreateDecoder No-op -func (extension *DummyExtension) CreateDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateEncoder No-op -func (extension *DummyExtension) CreateEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// DecorateDecoder No-op -func (extension *DummyExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { - return decoder -} - -// DecorateEncoder No-op -func (extension *DummyExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { - return encoder -} - -type EncoderExtension map[reflect2.Type]ValEncoder - -// UpdateStructDescriptor No-op -func (extension EncoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { -} - -// CreateDecoder No-op -func (extension EncoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateEncoder get encoder from map -func (extension EncoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { - return extension[typ] -} - -// CreateMapKeyDecoder No-op -func (extension EncoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateMapKeyEncoder No-op -func (extension EncoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// DecorateDecoder No-op -func (extension EncoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { - return decoder -} - -// DecorateEncoder No-op -func (extension EncoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { - return encoder -} - -type DecoderExtension map[reflect2.Type]ValDecoder - -// UpdateStructDescriptor No-op -func (extension DecoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { -} - -// CreateMapKeyDecoder No-op -func (extension DecoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { - return nil -} - -// CreateMapKeyEncoder No-op -func (extension DecoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// CreateDecoder get decoder from map -func (extension DecoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { - return extension[typ] -} - -// CreateEncoder No-op -func (extension DecoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { - return nil -} - -// DecorateDecoder No-op -func (extension DecoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { - return decoder -} - -// DecorateEncoder No-op -func (extension DecoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { - return encoder -} - -type funcDecoder struct { - fun DecoderFunc -} - -func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.fun(ptr, iter) -} - -type funcEncoder struct { - fun EncoderFunc - isEmptyFunc func(ptr unsafe.Pointer) bool -} - -func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.fun(ptr, stream) -} - -func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool { - if encoder.isEmptyFunc == nil { - return false - } - return encoder.isEmptyFunc(ptr) -} - -// DecoderFunc the function form of TypeDecoder -type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator) - -// EncoderFunc the function form of TypeEncoder -type EncoderFunc func(ptr unsafe.Pointer, stream *Stream) - -// RegisterTypeDecoderFunc register TypeDecoder for a type with function -func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) { - typeDecoders[typ] = &funcDecoder{fun} -} - -// RegisterTypeDecoder register TypeDecoder for a typ -func RegisterTypeDecoder(typ string, decoder ValDecoder) { - typeDecoders[typ] = decoder -} - -// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function -func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) { - RegisterFieldDecoder(typ, field, &funcDecoder{fun}) -} - -// RegisterFieldDecoder register TypeDecoder for a struct field -func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) { - fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder -} - -// RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function -func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { - typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc} -} - -// RegisterTypeEncoder register TypeEncoder for a type -func RegisterTypeEncoder(typ string, encoder ValEncoder) { - typeEncoders[typ] = encoder -} - -// RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function -func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { - RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc}) -} - -// RegisterFieldEncoder register TypeEncoder for a struct field -func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) { - fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder -} - -// RegisterExtension register extension -func RegisterExtension(extension Extension) { - extensions = append(extensions, extension) -} - -func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := _getTypeDecoderFromExtension(ctx, typ) - if decoder != nil { - for _, extension := range extensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) - for _, extension := range ctx.extraExtensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - } - return decoder -} -func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { - for _, extension := range extensions { - decoder := extension.CreateDecoder(typ) - if decoder != nil { - return decoder - } - } - decoder := ctx.decoderExtension.CreateDecoder(typ) - if decoder != nil { - return decoder - } - for _, extension := range ctx.extraExtensions { - decoder := extension.CreateDecoder(typ) - if decoder != nil { - return decoder - } - } - typeName := typ.String() - decoder = typeDecoders[typeName] - if decoder != nil { - return decoder - } - if typ.Kind() == reflect.Ptr { - ptrType := typ.(*reflect2.UnsafePtrType) - decoder := typeDecoders[ptrType.Elem().String()] - if decoder != nil { - return &OptionalDecoder{ptrType.Elem(), decoder} - } - } - return nil -} - -func getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := _getTypeEncoderFromExtension(ctx, typ) - if encoder != nil { - for _, extension := range extensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) - for _, extension := range ctx.extraExtensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - } - return encoder -} - -func _getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { - for _, extension := range extensions { - encoder := extension.CreateEncoder(typ) - if encoder != nil { - return encoder - } - } - encoder := ctx.encoderExtension.CreateEncoder(typ) - if encoder != nil { - return encoder - } - for _, extension := range ctx.extraExtensions { - encoder := extension.CreateEncoder(typ) - if encoder != nil { - return encoder - } - } - typeName := typ.String() - encoder = typeEncoders[typeName] - if encoder != nil { - return encoder - } - if typ.Kind() == reflect.Ptr { - typePtr := typ.(*reflect2.UnsafePtrType) - encoder := typeEncoders[typePtr.Elem().String()] - if encoder != nil { - return &OptionalEncoder{encoder} - } - } - return nil -} - -func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor { - structType := typ.(*reflect2.UnsafeStructType) - embeddedBindings := []*Binding{} - bindings := []*Binding{} - for i := 0; i < structType.NumField(); i++ { - field := structType.Field(i) - tag, hastag := field.Tag().Lookup(ctx.getTagKey()) - if ctx.onlyTaggedField && !hastag && !field.Anonymous() { - continue - } - if tag == "-" || field.Name() == "_" { - continue - } - tagParts := strings.Split(tag, ",") - if field.Anonymous() && (tag == "" || tagParts[0] == "") { - if field.Type().Kind() == reflect.Struct { - structDescriptor := describeStruct(ctx, field.Type()) - for _, binding := range structDescriptor.Fields { - binding.levels = append([]int{i}, binding.levels...) - omitempty := binding.Encoder.(*structFieldEncoder).omitempty - binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} - binding.Decoder = &structFieldDecoder{field, binding.Decoder} - embeddedBindings = append(embeddedBindings, binding) - } - continue - } else if field.Type().Kind() == reflect.Ptr { - ptrType := field.Type().(*reflect2.UnsafePtrType) - if ptrType.Elem().Kind() == reflect.Struct { - structDescriptor := describeStruct(ctx, ptrType.Elem()) - for _, binding := range structDescriptor.Fields { - binding.levels = append([]int{i}, binding.levels...) - omitempty := binding.Encoder.(*structFieldEncoder).omitempty - binding.Encoder = &dereferenceEncoder{binding.Encoder} - binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} - binding.Decoder = &dereferenceDecoder{ptrType.Elem(), binding.Decoder} - binding.Decoder = &structFieldDecoder{field, binding.Decoder} - embeddedBindings = append(embeddedBindings, binding) - } - continue - } - } - } - fieldNames := calcFieldNames(field.Name(), tagParts[0], tag) - fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name()) - decoder := fieldDecoders[fieldCacheKey] - if decoder == nil { - decoder = decoderOfType(ctx.append(field.Name()), field.Type()) - } - encoder := fieldEncoders[fieldCacheKey] - if encoder == nil { - encoder = encoderOfType(ctx.append(field.Name()), field.Type()) - } - binding := &Binding{ - Field: field, - FromNames: fieldNames, - ToNames: fieldNames, - Decoder: decoder, - Encoder: encoder, - } - binding.levels = []int{i} - bindings = append(bindings, binding) - } - return createStructDescriptor(ctx, typ, bindings, embeddedBindings) -} -func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { - structDescriptor := &StructDescriptor{ - Type: typ, - Fields: bindings, - } - for _, extension := range extensions { - extension.UpdateStructDescriptor(structDescriptor) - } - ctx.encoderExtension.UpdateStructDescriptor(structDescriptor) - ctx.decoderExtension.UpdateStructDescriptor(structDescriptor) - for _, extension := range ctx.extraExtensions { - extension.UpdateStructDescriptor(structDescriptor) - } - processTags(structDescriptor, ctx.frozenConfig) - // merge normal & embedded bindings & sort with original order - allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...)) - sort.Sort(allBindings) - structDescriptor.Fields = allBindings - return structDescriptor -} - -type sortableBindings []*Binding - -func (bindings sortableBindings) Len() int { - return len(bindings) -} - -func (bindings sortableBindings) Less(i, j int) bool { - left := bindings[i].levels - right := bindings[j].levels - k := 0 - for { - if left[k] < right[k] { - return true - } else if left[k] > right[k] { - return false - } - k++ - } -} - -func (bindings sortableBindings) Swap(i, j int) { - bindings[i], bindings[j] = bindings[j], bindings[i] -} - -func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) { - for _, binding := range structDescriptor.Fields { - shouldOmitEmpty := false - tagParts := strings.Split(binding.Field.Tag().Get(cfg.getTagKey()), ",") - for _, tagPart := range tagParts[1:] { - if tagPart == "omitempty" { - shouldOmitEmpty = true - } else if tagPart == "string" { - if binding.Field.Type().Kind() == reflect.String { - binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg} - binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg} - } else { - binding.Decoder = &stringModeNumberDecoder{binding.Decoder} - binding.Encoder = &stringModeNumberEncoder{binding.Encoder} - } - } - } - binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder} - binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty} - } -} - -func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string { - // ignore? - if wholeTag == "-" { - return []string{} - } - // rename? - var fieldNames []string - if tagProvidedFieldName == "" { - fieldNames = []string{originalFieldName} - } else { - fieldNames = []string{tagProvidedFieldName} - } - // private? - isNotExported := unicode.IsLower(rune(originalFieldName[0])) || originalFieldName[0] == '_' - if isNotExported { - fieldNames = []string{} - } - return fieldNames -} diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go deleted file mode 100644 index 98d45c1e..00000000 --- a/vendor/github.com/json-iterator/go/reflect_json_number.go +++ /dev/null @@ -1,112 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "github.com/modern-go/reflect2" - "strconv" - "unsafe" -) - -type Number string - -// String returns the literal text of the number. -func (n Number) String() string { return string(n) } - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return strconv.ParseFloat(string(n), 64) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return strconv.ParseInt(string(n), 10, 64) -} - -func CastJsonNumber(val interface{}) (string, bool) { - switch typedVal := val.(type) { - case json.Number: - return string(typedVal), true - case Number: - return string(typedVal), true - } - return "", false -} - -var jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() -var jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() - -func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ.AssignableTo(jsonNumberType) { - return &jsonNumberCodec{} - } - if typ.AssignableTo(jsoniterNumberType) { - return &jsoniterNumberCodec{} - } - return nil -} - -func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ.AssignableTo(jsonNumberType) { - return &jsonNumberCodec{} - } - if typ.AssignableTo(jsoniterNumberType) { - return &jsoniterNumberCodec{} - } - return nil -} - -type jsonNumberCodec struct { -} - -func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - switch iter.WhatIsNext() { - case StringValue: - *((*json.Number)(ptr)) = json.Number(iter.ReadString()) - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - *((*json.Number)(ptr)) = "" - default: - *((*json.Number)(ptr)) = json.Number([]byte(iter.readNumberAsString())) - } -} - -func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - number := *((*json.Number)(ptr)) - if len(number) == 0 { - stream.writeByte('0') - } else { - stream.WriteRaw(string(number)) - } -} - -func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*json.Number)(ptr))) == 0 -} - -type jsoniterNumberCodec struct { -} - -func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - switch iter.WhatIsNext() { - case StringValue: - *((*Number)(ptr)) = Number(iter.ReadString()) - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - *((*Number)(ptr)) = "" - default: - *((*Number)(ptr)) = Number([]byte(iter.readNumberAsString())) - } -} - -func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - number := *((*Number)(ptr)) - if len(number) == 0 { - stream.writeByte('0') - } else { - stream.WriteRaw(string(number)) - } -} - -func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*Number)(ptr))) == 0 -} diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go deleted file mode 100644 index eba434f2..00000000 --- a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go +++ /dev/null @@ -1,76 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "github.com/modern-go/reflect2" - "unsafe" -) - -var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() -var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() - -func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ == jsonRawMessageType { - return &jsonRawMessageCodec{} - } - if typ == jsoniterRawMessageType { - return &jsoniterRawMessageCodec{} - } - return nil -} - -func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ == jsonRawMessageType { - return &jsonRawMessageCodec{} - } - if typ == jsoniterRawMessageType { - return &jsoniterRawMessageCodec{} - } - return nil -} - -type jsonRawMessageCodec struct { -} - -func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - *((*json.RawMessage)(ptr)) = nil - } else { - *((*json.RawMessage)(ptr)) = iter.SkipAndReturnBytes() - } -} - -func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - if *((*json.RawMessage)(ptr)) == nil { - stream.WriteNil() - } else { - stream.WriteRaw(string(*((*json.RawMessage)(ptr)))) - } -} - -func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*json.RawMessage)(ptr))) == 0 -} - -type jsoniterRawMessageCodec struct { -} - -func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - *((*RawMessage)(ptr)) = nil - } else { - *((*RawMessage)(ptr)) = iter.SkipAndReturnBytes() - } -} - -func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - if *((*RawMessage)(ptr)) == nil { - stream.WriteNil() - } else { - stream.WriteRaw(string(*((*RawMessage)(ptr)))) - } -} - -func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*RawMessage)(ptr))) == 0 -} diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go deleted file mode 100644 index 58296713..00000000 --- a/vendor/github.com/json-iterator/go/reflect_map.go +++ /dev/null @@ -1,346 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "reflect" - "sort" - "unsafe" -) - -func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { - mapType := typ.(*reflect2.UnsafeMapType) - keyDecoder := decoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()) - elemDecoder := decoderOfType(ctx.append("[mapElem]"), mapType.Elem()) - return &mapDecoder{ - mapType: mapType, - keyType: mapType.Key(), - elemType: mapType.Elem(), - keyDecoder: keyDecoder, - elemDecoder: elemDecoder, - } -} - -func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder { - mapType := typ.(*reflect2.UnsafeMapType) - if ctx.sortMapKeys { - return &sortKeysMapEncoder{ - mapType: mapType, - keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), - elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), - } - } - return &mapEncoder{ - mapType: mapType, - keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), - elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), - } -} - -func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder { - decoder := ctx.decoderExtension.CreateMapKeyDecoder(typ) - if decoder != nil { - return decoder - } - for _, extension := range ctx.extraExtensions { - decoder := extension.CreateMapKeyDecoder(typ) - if decoder != nil { - return decoder - } - } - - ptrType := reflect2.PtrTo(typ) - if ptrType.Implements(unmarshalerType) { - return &referenceDecoder{ - &unmarshalerDecoder{ - valType: ptrType, - }, - } - } - if typ.Implements(unmarshalerType) { - return &unmarshalerDecoder{ - valType: typ, - } - } - if ptrType.Implements(textUnmarshalerType) { - return &referenceDecoder{ - &textUnmarshalerDecoder{ - valType: ptrType, - }, - } - } - if typ.Implements(textUnmarshalerType) { - return &textUnmarshalerDecoder{ - valType: typ, - } - } - - switch typ.Kind() { - case reflect.String: - return decoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) - case reflect.Bool, - reflect.Uint8, reflect.Int8, - reflect.Uint16, reflect.Int16, - reflect.Uint32, reflect.Int32, - reflect.Uint64, reflect.Int64, - reflect.Uint, reflect.Int, - reflect.Float32, reflect.Float64, - reflect.Uintptr: - typ = reflect2.DefaultTypeOfKind(typ.Kind()) - return &numericMapKeyDecoder{decoderOfType(ctx, typ)} - default: - return &lazyErrorDecoder{err: fmt.Errorf("unsupported map key type: %v", typ)} - } -} - -func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder { - encoder := ctx.encoderExtension.CreateMapKeyEncoder(typ) - if encoder != nil { - return encoder - } - for _, extension := range ctx.extraExtensions { - encoder := extension.CreateMapKeyEncoder(typ) - if encoder != nil { - return encoder - } - } - - if typ == textMarshalerType { - return &directTextMarshalerEncoder{ - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - } - } - if typ.Implements(textMarshalerType) { - return &textMarshalerEncoder{ - valType: typ, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - } - } - - switch typ.Kind() { - case reflect.String: - return encoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) - case reflect.Bool, - reflect.Uint8, reflect.Int8, - reflect.Uint16, reflect.Int16, - reflect.Uint32, reflect.Int32, - reflect.Uint64, reflect.Int64, - reflect.Uint, reflect.Int, - reflect.Float32, reflect.Float64, - reflect.Uintptr: - typ = reflect2.DefaultTypeOfKind(typ.Kind()) - return &numericMapKeyEncoder{encoderOfType(ctx, typ)} - default: - if typ.Kind() == reflect.Interface { - return &dynamicMapKeyEncoder{ctx, typ} - } - return &lazyErrorEncoder{err: fmt.Errorf("unsupported map key type: %v", typ)} - } -} - -type mapDecoder struct { - mapType *reflect2.UnsafeMapType - keyType reflect2.Type - elemType reflect2.Type - keyDecoder ValDecoder - elemDecoder ValDecoder -} - -func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - mapType := decoder.mapType - c := iter.nextToken() - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - *(*unsafe.Pointer)(ptr) = nil - mapType.UnsafeSet(ptr, mapType.UnsafeNew()) - return - } - if mapType.UnsafeIsNil(ptr) { - mapType.UnsafeSet(ptr, mapType.UnsafeMakeMap(0)) - } - if c != '{' { - iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) - return - } - c = iter.nextToken() - if c == '}' { - return - } - iter.unreadByte() - key := decoder.keyType.UnsafeNew() - decoder.keyDecoder.Decode(key, iter) - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - return - } - elem := decoder.elemType.UnsafeNew() - decoder.elemDecoder.Decode(elem, iter) - decoder.mapType.UnsafeSetIndex(ptr, key, elem) - for c = iter.nextToken(); c == ','; c = iter.nextToken() { - key := decoder.keyType.UnsafeNew() - decoder.keyDecoder.Decode(key, iter) - c = iter.nextToken() - if c != ':' { - iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) - return - } - elem := decoder.elemType.UnsafeNew() - decoder.elemDecoder.Decode(elem, iter) - decoder.mapType.UnsafeSetIndex(ptr, key, elem) - } - if c != '}' { - iter.ReportError("ReadMapCB", `expect }, but found `+string([]byte{c})) - } -} - -type numericMapKeyDecoder struct { - decoder ValDecoder -} - -func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - if c != '"' { - iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) - return - } - decoder.decoder.Decode(ptr, iter) - c = iter.nextToken() - if c != '"' { - iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) - return - } -} - -type numericMapKeyEncoder struct { - encoder ValEncoder -} - -func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.writeByte('"') - encoder.encoder.Encode(ptr, stream) - stream.writeByte('"') -} - -func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type dynamicMapKeyEncoder struct { - ctx *ctx - valType reflect2.Type -} - -func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).Encode(reflect2.PtrOf(obj), stream) -} - -func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { - obj := encoder.valType.UnsafeIndirect(ptr) - return encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).IsEmpty(reflect2.PtrOf(obj)) -} - -type mapEncoder struct { - mapType *reflect2.UnsafeMapType - keyEncoder ValEncoder - elemEncoder ValEncoder -} - -func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *(*unsafe.Pointer)(ptr) == nil { - stream.WriteNil() - return - } - stream.WriteObjectStart() - iter := encoder.mapType.UnsafeIterate(ptr) - for i := 0; iter.HasNext(); i++ { - if i != 0 { - stream.WriteMore() - } - key, elem := iter.UnsafeNext() - encoder.keyEncoder.Encode(key, stream) - if stream.indention > 0 { - stream.writeTwoBytes(byte(':'), byte(' ')) - } else { - stream.writeByte(':') - } - encoder.elemEncoder.Encode(elem, stream) - } - stream.WriteObjectEnd() -} - -func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool { - iter := encoder.mapType.UnsafeIterate(ptr) - return !iter.HasNext() -} - -type sortKeysMapEncoder struct { - mapType *reflect2.UnsafeMapType - keyEncoder ValEncoder - elemEncoder ValEncoder -} - -func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *(*unsafe.Pointer)(ptr) == nil { - stream.WriteNil() - return - } - stream.WriteObjectStart() - mapIter := encoder.mapType.UnsafeIterate(ptr) - subStream := stream.cfg.BorrowStream(nil) - subStream.Attachment = stream.Attachment - subIter := stream.cfg.BorrowIterator(nil) - keyValues := encodedKeyValues{} - for mapIter.HasNext() { - key, elem := mapIter.UnsafeNext() - subStreamIndex := subStream.Buffered() - encoder.keyEncoder.Encode(key, subStream) - if subStream.Error != nil && subStream.Error != io.EOF && stream.Error == nil { - stream.Error = subStream.Error - } - encodedKey := subStream.Buffer()[subStreamIndex:] - subIter.ResetBytes(encodedKey) - decodedKey := subIter.ReadString() - if stream.indention > 0 { - subStream.writeTwoBytes(byte(':'), byte(' ')) - } else { - subStream.writeByte(':') - } - encoder.elemEncoder.Encode(elem, subStream) - keyValues = append(keyValues, encodedKV{ - key: decodedKey, - keyValue: subStream.Buffer()[subStreamIndex:], - }) - } - sort.Sort(keyValues) - for i, keyValue := range keyValues { - if i != 0 { - stream.WriteMore() - } - stream.Write(keyValue.keyValue) - } - if subStream.Error != nil && stream.Error == nil { - stream.Error = subStream.Error - } - stream.WriteObjectEnd() - stream.cfg.ReturnStream(subStream) - stream.cfg.ReturnIterator(subIter) -} - -func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool { - iter := encoder.mapType.UnsafeIterate(ptr) - return !iter.HasNext() -} - -type encodedKeyValues []encodedKV - -type encodedKV struct { - key string - keyValue []byte -} - -func (sv encodedKeyValues) Len() int { return len(sv) } -func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv[j].key } diff --git a/vendor/github.com/json-iterator/go/reflect_marshaler.go b/vendor/github.com/json-iterator/go/reflect_marshaler.go deleted file mode 100644 index 3e21f375..00000000 --- a/vendor/github.com/json-iterator/go/reflect_marshaler.go +++ /dev/null @@ -1,225 +0,0 @@ -package jsoniter - -import ( - "encoding" - "encoding/json" - "unsafe" - - "github.com/modern-go/reflect2" -) - -var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() -var unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() -var textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() -var textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() - -func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder { - ptrType := reflect2.PtrTo(typ) - if ptrType.Implements(unmarshalerType) { - return &referenceDecoder{ - &unmarshalerDecoder{ptrType}, - } - } - if ptrType.Implements(textUnmarshalerType) { - return &referenceDecoder{ - &textUnmarshalerDecoder{ptrType}, - } - } - return nil -} - -func createEncoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ == marshalerType { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &directMarshalerEncoder{ - checkIsEmpty: checkIsEmpty, - } - return encoder - } - if typ.Implements(marshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &marshalerEncoder{ - valType: typ, - checkIsEmpty: checkIsEmpty, - } - return encoder - } - ptrType := reflect2.PtrTo(typ) - if ctx.prefix != "" && ptrType.Implements(marshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, ptrType) - var encoder ValEncoder = &marshalerEncoder{ - valType: ptrType, - checkIsEmpty: checkIsEmpty, - } - return &referenceEncoder{encoder} - } - if typ == textMarshalerType { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &directTextMarshalerEncoder{ - checkIsEmpty: checkIsEmpty, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - } - return encoder - } - if typ.Implements(textMarshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, typ) - var encoder ValEncoder = &textMarshalerEncoder{ - valType: typ, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - checkIsEmpty: checkIsEmpty, - } - return encoder - } - // if prefix is empty, the type is the root type - if ctx.prefix != "" && ptrType.Implements(textMarshalerType) { - checkIsEmpty := createCheckIsEmpty(ctx, ptrType) - var encoder ValEncoder = &textMarshalerEncoder{ - valType: ptrType, - stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), - checkIsEmpty: checkIsEmpty, - } - return &referenceEncoder{encoder} - } - return nil -} - -type marshalerEncoder struct { - checkIsEmpty checkIsEmpty - valType reflect2.Type -} - -func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - if encoder.valType.IsNullable() && reflect2.IsNil(obj) { - stream.WriteNil() - return - } - marshaler := obj.(json.Marshaler) - bytes, err := marshaler.MarshalJSON() - if err != nil { - stream.Error = err - } else { - // html escape was already done by jsoniter - // but the extra '\n' should be trimed - l := len(bytes) - if l > 0 && bytes[l-1] == '\n' { - bytes = bytes[:l-1] - } - stream.Write(bytes) - } -} - -func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type directMarshalerEncoder struct { - checkIsEmpty checkIsEmpty -} - -func (encoder *directMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - marshaler := *(*json.Marshaler)(ptr) - if marshaler == nil { - stream.WriteNil() - return - } - bytes, err := marshaler.MarshalJSON() - if err != nil { - stream.Error = err - } else { - stream.Write(bytes) - } -} - -func (encoder *directMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type textMarshalerEncoder struct { - valType reflect2.Type - stringEncoder ValEncoder - checkIsEmpty checkIsEmpty -} - -func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - obj := encoder.valType.UnsafeIndirect(ptr) - if encoder.valType.IsNullable() && reflect2.IsNil(obj) { - stream.WriteNil() - return - } - marshaler := (obj).(encoding.TextMarshaler) - bytes, err := marshaler.MarshalText() - if err != nil { - stream.Error = err - } else { - str := string(bytes) - encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) - } -} - -func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type directTextMarshalerEncoder struct { - stringEncoder ValEncoder - checkIsEmpty checkIsEmpty -} - -func (encoder *directTextMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - marshaler := *(*encoding.TextMarshaler)(ptr) - if marshaler == nil { - stream.WriteNil() - return - } - bytes, err := marshaler.MarshalText() - if err != nil { - stream.Error = err - } else { - str := string(bytes) - encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) - } -} - -func (encoder *directTextMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type unmarshalerDecoder struct { - valType reflect2.Type -} - -func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - valType := decoder.valType - obj := valType.UnsafeIndirect(ptr) - unmarshaler := obj.(json.Unmarshaler) - iter.nextToken() - iter.unreadByte() // skip spaces - bytes := iter.SkipAndReturnBytes() - err := unmarshaler.UnmarshalJSON(bytes) - if err != nil { - iter.ReportError("unmarshalerDecoder", err.Error()) - } -} - -type textUnmarshalerDecoder struct { - valType reflect2.Type -} - -func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - valType := decoder.valType - obj := valType.UnsafeIndirect(ptr) - if reflect2.IsNil(obj) { - ptrType := valType.(*reflect2.UnsafePtrType) - elemType := ptrType.Elem() - elem := elemType.UnsafeNew() - ptrType.UnsafeSet(ptr, unsafe.Pointer(&elem)) - obj = valType.UnsafeIndirect(ptr) - } - unmarshaler := (obj).(encoding.TextUnmarshaler) - str := iter.ReadString() - err := unmarshaler.UnmarshalText([]byte(str)) - if err != nil { - iter.ReportError("textUnmarshalerDecoder", err.Error()) - } -} diff --git a/vendor/github.com/json-iterator/go/reflect_native.go b/vendor/github.com/json-iterator/go/reflect_native.go deleted file mode 100644 index f88722d1..00000000 --- a/vendor/github.com/json-iterator/go/reflect_native.go +++ /dev/null @@ -1,453 +0,0 @@ -package jsoniter - -import ( - "encoding/base64" - "reflect" - "strconv" - "unsafe" - - "github.com/modern-go/reflect2" -) - -const ptrSize = 32 << uintptr(^uintptr(0)>>63) - -func createEncoderOfNative(ctx *ctx, typ reflect2.Type) ValEncoder { - if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { - sliceDecoder := decoderOfSlice(ctx, typ) - return &base64Codec{sliceDecoder: sliceDecoder} - } - typeName := typ.String() - kind := typ.Kind() - switch kind { - case reflect.String: - if typeName != "string" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) - } - return &stringCodec{} - case reflect.Int: - if typeName != "int" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &int32Codec{} - } - return &int64Codec{} - case reflect.Int8: - if typeName != "int8" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) - } - return &int8Codec{} - case reflect.Int16: - if typeName != "int16" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) - } - return &int16Codec{} - case reflect.Int32: - if typeName != "int32" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) - } - return &int32Codec{} - case reflect.Int64: - if typeName != "int64" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) - } - return &int64Codec{} - case reflect.Uint: - if typeName != "uint" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint8: - if typeName != "uint8" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) - } - return &uint8Codec{} - case reflect.Uint16: - if typeName != "uint16" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) - } - return &uint16Codec{} - case reflect.Uint32: - if typeName != "uint32" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) - } - return &uint32Codec{} - case reflect.Uintptr: - if typeName != "uintptr" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) - } - if ptrSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint64: - if typeName != "uint64" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) - } - return &uint64Codec{} - case reflect.Float32: - if typeName != "float32" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) - } - return &float32Codec{} - case reflect.Float64: - if typeName != "float64" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) - } - return &float64Codec{} - case reflect.Bool: - if typeName != "bool" { - return encoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) - } - return &boolCodec{} - } - return nil -} - -func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder { - if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { - sliceDecoder := decoderOfSlice(ctx, typ) - return &base64Codec{sliceDecoder: sliceDecoder} - } - typeName := typ.String() - switch typ.Kind() { - case reflect.String: - if typeName != "string" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) - } - return &stringCodec{} - case reflect.Int: - if typeName != "int" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &int32Codec{} - } - return &int64Codec{} - case reflect.Int8: - if typeName != "int8" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) - } - return &int8Codec{} - case reflect.Int16: - if typeName != "int16" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) - } - return &int16Codec{} - case reflect.Int32: - if typeName != "int32" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) - } - return &int32Codec{} - case reflect.Int64: - if typeName != "int64" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) - } - return &int64Codec{} - case reflect.Uint: - if typeName != "uint" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) - } - if strconv.IntSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint8: - if typeName != "uint8" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) - } - return &uint8Codec{} - case reflect.Uint16: - if typeName != "uint16" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) - } - return &uint16Codec{} - case reflect.Uint32: - if typeName != "uint32" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) - } - return &uint32Codec{} - case reflect.Uintptr: - if typeName != "uintptr" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) - } - if ptrSize == 32 { - return &uint32Codec{} - } - return &uint64Codec{} - case reflect.Uint64: - if typeName != "uint64" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) - } - return &uint64Codec{} - case reflect.Float32: - if typeName != "float32" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) - } - return &float32Codec{} - case reflect.Float64: - if typeName != "float64" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) - } - return &float64Codec{} - case reflect.Bool: - if typeName != "bool" { - return decoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) - } - return &boolCodec{} - } - return nil -} - -type stringCodec struct { -} - -func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*string)(ptr)) = iter.ReadString() -} - -func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - str := *((*string)(ptr)) - stream.WriteString(str) -} - -func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*string)(ptr)) == "" -} - -type int8Codec struct { -} - -func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int8)(ptr)) = iter.ReadInt8() - } -} - -func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt8(*((*int8)(ptr))) -} - -func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int8)(ptr)) == 0 -} - -type int16Codec struct { -} - -func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int16)(ptr)) = iter.ReadInt16() - } -} - -func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt16(*((*int16)(ptr))) -} - -func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int16)(ptr)) == 0 -} - -type int32Codec struct { -} - -func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int32)(ptr)) = iter.ReadInt32() - } -} - -func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt32(*((*int32)(ptr))) -} - -func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int32)(ptr)) == 0 -} - -type int64Codec struct { -} - -func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int64)(ptr)) = iter.ReadInt64() - } -} - -func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt64(*((*int64)(ptr))) -} - -func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int64)(ptr)) == 0 -} - -type uint8Codec struct { -} - -func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint8)(ptr)) = iter.ReadUint8() - } -} - -func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint8(*((*uint8)(ptr))) -} - -func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint8)(ptr)) == 0 -} - -type uint16Codec struct { -} - -func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint16)(ptr)) = iter.ReadUint16() - } -} - -func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint16(*((*uint16)(ptr))) -} - -func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint16)(ptr)) == 0 -} - -type uint32Codec struct { -} - -func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint32)(ptr)) = iter.ReadUint32() - } -} - -func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint32(*((*uint32)(ptr))) -} - -func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint32)(ptr)) == 0 -} - -type uint64Codec struct { -} - -func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint64)(ptr)) = iter.ReadUint64() - } -} - -func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint64(*((*uint64)(ptr))) -} - -func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint64)(ptr)) == 0 -} - -type float32Codec struct { -} - -func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*float32)(ptr)) = iter.ReadFloat32() - } -} - -func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat32(*((*float32)(ptr))) -} - -func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float32)(ptr)) == 0 -} - -type float64Codec struct { -} - -func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*float64)(ptr)) = iter.ReadFloat64() - } -} - -func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat64(*((*float64)(ptr))) -} - -func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float64)(ptr)) == 0 -} - -type boolCodec struct { -} - -func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*bool)(ptr)) = iter.ReadBool() - } -} - -func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteBool(*((*bool)(ptr))) -} - -func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool { - return !(*((*bool)(ptr))) -} - -type base64Codec struct { - sliceType *reflect2.UnsafeSliceType - sliceDecoder ValDecoder -} - -func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - codec.sliceType.UnsafeSetNil(ptr) - return - } - switch iter.WhatIsNext() { - case StringValue: - src := iter.ReadString() - dst, err := base64.StdEncoding.DecodeString(src) - if err != nil { - iter.ReportError("decode base64", err.Error()) - } else { - codec.sliceType.UnsafeSet(ptr, unsafe.Pointer(&dst)) - } - case ArrayValue: - codec.sliceDecoder.Decode(ptr, iter) - default: - iter.ReportError("base64Codec", "invalid input") - } -} - -func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - if codec.sliceType.UnsafeIsNil(ptr) { - stream.WriteNil() - return - } - src := *((*[]byte)(ptr)) - encoding := base64.StdEncoding - stream.writeByte('"') - if len(src) != 0 { - size := encoding.EncodedLen(len(src)) - buf := make([]byte, size) - encoding.Encode(buf, src) - stream.buf = append(stream.buf, buf...) - } - stream.writeByte('"') -} - -func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*[]byte)(ptr))) == 0 -} diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go deleted file mode 100644 index fa71f474..00000000 --- a/vendor/github.com/json-iterator/go/reflect_optional.go +++ /dev/null @@ -1,129 +0,0 @@ -package jsoniter - -import ( - "github.com/modern-go/reflect2" - "unsafe" -) - -func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { - ptrType := typ.(*reflect2.UnsafePtrType) - elemType := ptrType.Elem() - decoder := decoderOfType(ctx, elemType) - return &OptionalDecoder{elemType, decoder} -} - -func encoderOfOptional(ctx *ctx, typ reflect2.Type) ValEncoder { - ptrType := typ.(*reflect2.UnsafePtrType) - elemType := ptrType.Elem() - elemEncoder := encoderOfType(ctx, elemType) - encoder := &OptionalEncoder{elemEncoder} - return encoder -} - -type OptionalDecoder struct { - ValueType reflect2.Type - ValueDecoder ValDecoder -} - -func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - *((*unsafe.Pointer)(ptr)) = nil - } else { - if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value - newPtr := decoder.ValueType.UnsafeNew() - decoder.ValueDecoder.Decode(newPtr, iter) - *((*unsafe.Pointer)(ptr)) = newPtr - } else { - //reuse existing instance - decoder.ValueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) - } - } -} - -type dereferenceDecoder struct { - // only to deference a pointer - valueType reflect2.Type - valueDecoder ValDecoder -} - -func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value - newPtr := decoder.valueType.UnsafeNew() - decoder.valueDecoder.Decode(newPtr, iter) - *((*unsafe.Pointer)(ptr)) = newPtr - } else { - //reuse existing instance - decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) - } -} - -type OptionalEncoder struct { - ValueEncoder ValEncoder -} - -func (encoder *OptionalEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *((*unsafe.Pointer)(ptr)) == nil { - stream.WriteNil() - } else { - encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) - } -} - -func (encoder *OptionalEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return *((*unsafe.Pointer)(ptr)) == nil -} - -type dereferenceEncoder struct { - ValueEncoder ValEncoder -} - -func (encoder *dereferenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *((*unsafe.Pointer)(ptr)) == nil { - stream.WriteNil() - } else { - encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) - } -} - -func (encoder *dereferenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { - dePtr := *((*unsafe.Pointer)(ptr)) - if dePtr == nil { - return true - } - return encoder.ValueEncoder.IsEmpty(dePtr) -} - -func (encoder *dereferenceEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { - deReferenced := *((*unsafe.Pointer)(ptr)) - if deReferenced == nil { - return true - } - isEmbeddedPtrNil, converted := encoder.ValueEncoder.(IsEmbeddedPtrNil) - if !converted { - return false - } - fieldPtr := unsafe.Pointer(deReferenced) - return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) -} - -type referenceEncoder struct { - encoder ValEncoder -} - -func (encoder *referenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) -} - -func (encoder *referenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) -} - -type referenceDecoder struct { - decoder ValDecoder -} - -func (decoder *referenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.decoder.Decode(unsafe.Pointer(&ptr), iter) -} diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go deleted file mode 100644 index 9441d79d..00000000 --- a/vendor/github.com/json-iterator/go/reflect_slice.go +++ /dev/null @@ -1,99 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "unsafe" -) - -func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { - sliceType := typ.(*reflect2.UnsafeSliceType) - decoder := decoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) - return &sliceDecoder{sliceType, decoder} -} - -func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder { - sliceType := typ.(*reflect2.UnsafeSliceType) - encoder := encoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) - return &sliceEncoder{sliceType, encoder} -} - -type sliceEncoder struct { - sliceType *reflect2.UnsafeSliceType - elemEncoder ValEncoder -} - -func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if encoder.sliceType.UnsafeIsNil(ptr) { - stream.WriteNil() - return - } - length := encoder.sliceType.UnsafeLengthOf(ptr) - if length == 0 { - stream.WriteEmptyArray() - return - } - stream.WriteArrayStart() - encoder.elemEncoder.Encode(encoder.sliceType.UnsafeGetIndex(ptr, 0), stream) - for i := 1; i < length; i++ { - stream.WriteMore() - elemPtr := encoder.sliceType.UnsafeGetIndex(ptr, i) - encoder.elemEncoder.Encode(elemPtr, stream) - } - stream.WriteArrayEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v: %s", encoder.sliceType, stream.Error.Error()) - } -} - -func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.sliceType.UnsafeLengthOf(ptr) == 0 -} - -type sliceDecoder struct { - sliceType *reflect2.UnsafeSliceType - elemDecoder ValDecoder -} - -func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.doDecode(ptr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.sliceType, iter.Error.Error()) - } -} - -func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - sliceType := decoder.sliceType - if c == 'n' { - iter.skipThreeBytes('u', 'l', 'l') - sliceType.UnsafeSetNil(ptr) - return - } - if c != '[' { - iter.ReportError("decode slice", "expect [ or n, but found "+string([]byte{c})) - return - } - c = iter.nextToken() - if c == ']' { - sliceType.UnsafeSet(ptr, sliceType.UnsafeMakeSlice(0, 0)) - return - } - iter.unreadByte() - sliceType.UnsafeGrow(ptr, 1) - elemPtr := sliceType.UnsafeGetIndex(ptr, 0) - decoder.elemDecoder.Decode(elemPtr, iter) - length := 1 - for c = iter.nextToken(); c == ','; c = iter.nextToken() { - idx := length - length += 1 - sliceType.UnsafeGrow(ptr, length) - elemPtr = sliceType.UnsafeGetIndex(ptr, idx) - decoder.elemDecoder.Decode(elemPtr, iter) - } - if c != ']' { - iter.ReportError("decode slice", "expect ], but found "+string([]byte{c})) - return - } -} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_decoder.go b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go deleted file mode 100644 index 92ae912d..00000000 --- a/vendor/github.com/json-iterator/go/reflect_struct_decoder.go +++ /dev/null @@ -1,1097 +0,0 @@ -package jsoniter - -import ( - "fmt" - "io" - "strings" - "unsafe" - - "github.com/modern-go/reflect2" -) - -func decoderOfStruct(ctx *ctx, typ reflect2.Type) ValDecoder { - bindings := map[string]*Binding{} - structDescriptor := describeStruct(ctx, typ) - for _, binding := range structDescriptor.Fields { - for _, fromName := range binding.FromNames { - old := bindings[fromName] - if old == nil { - bindings[fromName] = binding - continue - } - ignoreOld, ignoreNew := resolveConflictBinding(ctx.frozenConfig, old, binding) - if ignoreOld { - delete(bindings, fromName) - } - if !ignoreNew { - bindings[fromName] = binding - } - } - } - fields := map[string]*structFieldDecoder{} - for k, binding := range bindings { - fields[k] = binding.Decoder.(*structFieldDecoder) - } - - if !ctx.caseSensitive() { - for k, binding := range bindings { - if _, found := fields[strings.ToLower(k)]; !found { - fields[strings.ToLower(k)] = binding.Decoder.(*structFieldDecoder) - } - } - } - - return createStructDecoder(ctx, typ, fields) -} - -func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structFieldDecoder) ValDecoder { - if ctx.disallowUnknownFields { - return &generalStructDecoder{typ: typ, fields: fields, disallowUnknownFields: true} - } - knownHash := map[int64]struct{}{ - 0: {}, - } - - switch len(fields) { - case 0: - return &skipObjectDecoder{typ} - case 1: - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder} - } - case 2: - var fieldHash1 int64 - var fieldHash2 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldHash1 == 0 { - fieldHash1 = fieldHash - fieldDecoder1 = fieldDecoder - } else { - fieldHash2 = fieldHash - fieldDecoder2 = fieldDecoder - } - } - return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2} - case 3: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } - } - return &threeFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3} - case 4: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } - } - return &fourFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4} - case 5: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } - } - return &fiveFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5} - case 6: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } - } - return &sixFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6} - case 7: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } - } - return &sevenFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7} - case 8: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldName8 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - var fieldDecoder8 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else if fieldName7 == 0 { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } else { - fieldName8 = fieldHash - fieldDecoder8 = fieldDecoder - } - } - return &eightFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, - fieldName8, fieldDecoder8} - case 9: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldName8 int64 - var fieldName9 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - var fieldDecoder8 *structFieldDecoder - var fieldDecoder9 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else if fieldName7 == 0 { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } else if fieldName8 == 0 { - fieldName8 = fieldHash - fieldDecoder8 = fieldDecoder - } else { - fieldName9 = fieldHash - fieldDecoder9 = fieldDecoder - } - } - return &nineFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, - fieldName8, fieldDecoder8, - fieldName9, fieldDecoder9} - case 10: - var fieldName1 int64 - var fieldName2 int64 - var fieldName3 int64 - var fieldName4 int64 - var fieldName5 int64 - var fieldName6 int64 - var fieldName7 int64 - var fieldName8 int64 - var fieldName9 int64 - var fieldName10 int64 - var fieldDecoder1 *structFieldDecoder - var fieldDecoder2 *structFieldDecoder - var fieldDecoder3 *structFieldDecoder - var fieldDecoder4 *structFieldDecoder - var fieldDecoder5 *structFieldDecoder - var fieldDecoder6 *structFieldDecoder - var fieldDecoder7 *structFieldDecoder - var fieldDecoder8 *structFieldDecoder - var fieldDecoder9 *structFieldDecoder - var fieldDecoder10 *structFieldDecoder - for fieldName, fieldDecoder := range fields { - fieldHash := calcHash(fieldName, ctx.caseSensitive()) - _, known := knownHash[fieldHash] - if known { - return &generalStructDecoder{typ, fields, false} - } - knownHash[fieldHash] = struct{}{} - if fieldName1 == 0 { - fieldName1 = fieldHash - fieldDecoder1 = fieldDecoder - } else if fieldName2 == 0 { - fieldName2 = fieldHash - fieldDecoder2 = fieldDecoder - } else if fieldName3 == 0 { - fieldName3 = fieldHash - fieldDecoder3 = fieldDecoder - } else if fieldName4 == 0 { - fieldName4 = fieldHash - fieldDecoder4 = fieldDecoder - } else if fieldName5 == 0 { - fieldName5 = fieldHash - fieldDecoder5 = fieldDecoder - } else if fieldName6 == 0 { - fieldName6 = fieldHash - fieldDecoder6 = fieldDecoder - } else if fieldName7 == 0 { - fieldName7 = fieldHash - fieldDecoder7 = fieldDecoder - } else if fieldName8 == 0 { - fieldName8 = fieldHash - fieldDecoder8 = fieldDecoder - } else if fieldName9 == 0 { - fieldName9 = fieldHash - fieldDecoder9 = fieldDecoder - } else { - fieldName10 = fieldHash - fieldDecoder10 = fieldDecoder - } - } - return &tenFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, - fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, - fieldName8, fieldDecoder8, - fieldName9, fieldDecoder9, - fieldName10, fieldDecoder10} - } - return &generalStructDecoder{typ, fields, false} -} - -type generalStructDecoder struct { - typ reflect2.Type - fields map[string]*structFieldDecoder - disallowUnknownFields bool -} - -func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - var c byte - for c = ','; c == ','; c = iter.nextToken() { - decoder.decodeOneField(ptr, iter) - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - if c != '}' { - iter.ReportError("struct Decode", `expect }, but found `+string([]byte{c})) - } - iter.decrementDepth() -} - -func (decoder *generalStructDecoder) decodeOneField(ptr unsafe.Pointer, iter *Iterator) { - var field string - var fieldDecoder *structFieldDecoder - if iter.cfg.objectFieldMustBeSimpleString { - fieldBytes := iter.ReadStringAsSlice() - field = *(*string)(unsafe.Pointer(&fieldBytes)) - fieldDecoder = decoder.fields[field] - if fieldDecoder == nil && !iter.cfg.caseSensitive { - fieldDecoder = decoder.fields[strings.ToLower(field)] - } - } else { - field = iter.ReadString() - fieldDecoder = decoder.fields[field] - if fieldDecoder == nil && !iter.cfg.caseSensitive { - fieldDecoder = decoder.fields[strings.ToLower(field)] - } - } - if fieldDecoder == nil { - if decoder.disallowUnknownFields { - msg := "found unknown field: " + field - iter.ReportError("ReadObject", msg) - } - c := iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - iter.Skip() - return - } - c := iter.nextToken() - if c != ':' { - iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) - } - fieldDecoder.Decode(ptr, iter) -} - -type skipObjectDecoder struct { - typ reflect2.Type -} - -func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - valueType := iter.WhatIsNext() - if valueType != ObjectValue && valueType != NilValue { - iter.ReportError("skipObjectDecoder", "expect object or null") - return - } - iter.Skip() -} - -type oneFieldStructDecoder struct { - typ reflect2.Type - fieldHash int64 - fieldDecoder *structFieldDecoder -} - -func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - if iter.readFieldHash() == decoder.fieldHash { - decoder.fieldDecoder.Decode(ptr, iter) - } else { - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type twoFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder -} - -func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type threeFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder -} - -func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type fourFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder -} - -func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type fiveFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder -} - -func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type sixFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder -} - -func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type sevenFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder -} - -func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type eightFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder - fieldHash8 int64 - fieldDecoder8 *structFieldDecoder -} - -func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - case decoder.fieldHash8: - decoder.fieldDecoder8.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type nineFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder - fieldHash8 int64 - fieldDecoder8 *structFieldDecoder - fieldHash9 int64 - fieldDecoder9 *structFieldDecoder -} - -func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - case decoder.fieldHash8: - decoder.fieldDecoder8.Decode(ptr, iter) - case decoder.fieldHash9: - decoder.fieldDecoder9.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type tenFieldsStructDecoder struct { - typ reflect2.Type - fieldHash1 int64 - fieldDecoder1 *structFieldDecoder - fieldHash2 int64 - fieldDecoder2 *structFieldDecoder - fieldHash3 int64 - fieldDecoder3 *structFieldDecoder - fieldHash4 int64 - fieldDecoder4 *structFieldDecoder - fieldHash5 int64 - fieldDecoder5 *structFieldDecoder - fieldHash6 int64 - fieldDecoder6 *structFieldDecoder - fieldHash7 int64 - fieldDecoder7 *structFieldDecoder - fieldHash8 int64 - fieldDecoder8 *structFieldDecoder - fieldHash9 int64 - fieldDecoder9 *structFieldDecoder - fieldHash10 int64 - fieldDecoder10 *structFieldDecoder -} - -func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.readObjectStart() { - return - } - if !iter.incrementDepth() { - return - } - for { - switch iter.readFieldHash() { - case decoder.fieldHash1: - decoder.fieldDecoder1.Decode(ptr, iter) - case decoder.fieldHash2: - decoder.fieldDecoder2.Decode(ptr, iter) - case decoder.fieldHash3: - decoder.fieldDecoder3.Decode(ptr, iter) - case decoder.fieldHash4: - decoder.fieldDecoder4.Decode(ptr, iter) - case decoder.fieldHash5: - decoder.fieldDecoder5.Decode(ptr, iter) - case decoder.fieldHash6: - decoder.fieldDecoder6.Decode(ptr, iter) - case decoder.fieldHash7: - decoder.fieldDecoder7.Decode(ptr, iter) - case decoder.fieldHash8: - decoder.fieldDecoder8.Decode(ptr, iter) - case decoder.fieldHash9: - decoder.fieldDecoder9.Decode(ptr, iter) - case decoder.fieldHash10: - decoder.fieldDecoder10.Decode(ptr, iter) - default: - iter.Skip() - } - if iter.isObjectEnd() { - break - } - } - if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { - iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) - } - iter.decrementDepth() -} - -type structFieldDecoder struct { - field reflect2.StructField - fieldDecoder ValDecoder -} - -func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - fieldPtr := decoder.field.UnsafeGet(ptr) - decoder.fieldDecoder.Decode(fieldPtr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%s: %s", decoder.field.Name(), iter.Error.Error()) - } -} - -type stringModeStringDecoder struct { - elemDecoder ValDecoder - cfg *frozenConfig -} - -func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.elemDecoder.Decode(ptr, iter) - str := *((*string)(ptr)) - tempIter := decoder.cfg.BorrowIterator([]byte(str)) - defer decoder.cfg.ReturnIterator(tempIter) - *((*string)(ptr)) = tempIter.ReadString() -} - -type stringModeNumberDecoder struct { - elemDecoder ValDecoder -} - -func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.WhatIsNext() == NilValue { - decoder.elemDecoder.Decode(ptr, iter) - return - } - - c := iter.nextToken() - if c != '"' { - iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) - return - } - decoder.elemDecoder.Decode(ptr, iter) - if iter.Error != nil { - return - } - c = iter.readByte() - if c != '"' { - iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) - return - } -} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go deleted file mode 100644 index 152e3ef5..00000000 --- a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go +++ /dev/null @@ -1,211 +0,0 @@ -package jsoniter - -import ( - "fmt" - "github.com/modern-go/reflect2" - "io" - "reflect" - "unsafe" -) - -func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { - type bindingTo struct { - binding *Binding - toName string - ignored bool - } - orderedBindings := []*bindingTo{} - structDescriptor := describeStruct(ctx, typ) - for _, binding := range structDescriptor.Fields { - for _, toName := range binding.ToNames { - new := &bindingTo{ - binding: binding, - toName: toName, - } - for _, old := range orderedBindings { - if old.toName != toName { - continue - } - old.ignored, new.ignored = resolveConflictBinding(ctx.frozenConfig, old.binding, new.binding) - } - orderedBindings = append(orderedBindings, new) - } - } - if len(orderedBindings) == 0 { - return &emptyStructEncoder{} - } - finalOrderedFields := []structFieldTo{} - for _, bindingTo := range orderedBindings { - if !bindingTo.ignored { - finalOrderedFields = append(finalOrderedFields, structFieldTo{ - encoder: bindingTo.binding.Encoder.(*structFieldEncoder), - toName: bindingTo.toName, - }) - } - } - return &structEncoder{typ, finalOrderedFields} -} - -func createCheckIsEmpty(ctx *ctx, typ reflect2.Type) checkIsEmpty { - encoder := createEncoderOfNative(ctx, typ) - if encoder != nil { - return encoder - } - kind := typ.Kind() - switch kind { - case reflect.Interface: - return &dynamicEncoder{typ} - case reflect.Struct: - return &structEncoder{typ: typ} - case reflect.Array: - return &arrayEncoder{} - case reflect.Slice: - return &sliceEncoder{} - case reflect.Map: - return encoderOfMap(ctx, typ) - case reflect.Ptr: - return &OptionalEncoder{} - default: - return &lazyErrorEncoder{err: fmt.Errorf("unsupported type: %v", typ)} - } -} - -func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ignoreNew bool) { - newTagged := new.Field.Tag().Get(cfg.getTagKey()) != "" - oldTagged := old.Field.Tag().Get(cfg.getTagKey()) != "" - if newTagged { - if oldTagged { - if len(old.levels) > len(new.levels) { - return true, false - } else if len(new.levels) > len(old.levels) { - return false, true - } else { - return true, true - } - } else { - return true, false - } - } else { - if oldTagged { - return true, false - } - if len(old.levels) > len(new.levels) { - return true, false - } else if len(new.levels) > len(old.levels) { - return false, true - } else { - return true, true - } - } -} - -type structFieldEncoder struct { - field reflect2.StructField - fieldEncoder ValEncoder - omitempty bool -} - -func (encoder *structFieldEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - fieldPtr := encoder.field.UnsafeGet(ptr) - encoder.fieldEncoder.Encode(fieldPtr, stream) - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%s: %s", encoder.field.Name(), stream.Error.Error()) - } -} - -func (encoder *structFieldEncoder) IsEmpty(ptr unsafe.Pointer) bool { - fieldPtr := encoder.field.UnsafeGet(ptr) - return encoder.fieldEncoder.IsEmpty(fieldPtr) -} - -func (encoder *structFieldEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { - isEmbeddedPtrNil, converted := encoder.fieldEncoder.(IsEmbeddedPtrNil) - if !converted { - return false - } - fieldPtr := encoder.field.UnsafeGet(ptr) - return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) -} - -type IsEmbeddedPtrNil interface { - IsEmbeddedPtrNil(ptr unsafe.Pointer) bool -} - -type structEncoder struct { - typ reflect2.Type - fields []structFieldTo -} - -type structFieldTo struct { - encoder *structFieldEncoder - toName string -} - -func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteObjectStart() - isNotFirst := false - for _, field := range encoder.fields { - if field.encoder.omitempty && field.encoder.IsEmpty(ptr) { - continue - } - if field.encoder.IsEmbeddedPtrNil(ptr) { - continue - } - if isNotFirst { - stream.WriteMore() - } - stream.WriteObjectField(field.toName) - field.encoder.Encode(ptr, stream) - isNotFirst = true - } - stream.WriteObjectEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v.%s", encoder.typ, stream.Error.Error()) - } -} - -func (encoder *structEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type emptyStructEncoder struct { -} - -func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteEmptyObject() -} - -func (encoder *emptyStructEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type stringModeNumberEncoder struct { - elemEncoder ValEncoder -} - -func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.writeByte('"') - encoder.elemEncoder.Encode(ptr, stream) - stream.writeByte('"') -} - -func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.elemEncoder.IsEmpty(ptr) -} - -type stringModeStringEncoder struct { - elemEncoder ValEncoder - cfg *frozenConfig -} - -func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - tempStream := encoder.cfg.BorrowStream(nil) - tempStream.Attachment = stream.Attachment - defer encoder.cfg.ReturnStream(tempStream) - encoder.elemEncoder.Encode(ptr, tempStream) - stream.WriteString(string(tempStream.Buffer())) -} - -func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.elemEncoder.IsEmpty(ptr) -} diff --git a/vendor/github.com/json-iterator/go/stream.go b/vendor/github.com/json-iterator/go/stream.go deleted file mode 100644 index 23d8a3ad..00000000 --- a/vendor/github.com/json-iterator/go/stream.go +++ /dev/null @@ -1,210 +0,0 @@ -package jsoniter - -import ( - "io" -) - -// stream is a io.Writer like object, with JSON specific write functions. -// Error is not returned as return value, but stored as Error member on this stream instance. -type Stream struct { - cfg *frozenConfig - out io.Writer - buf []byte - Error error - indention int - Attachment interface{} // open for customized encoder -} - -// NewStream create new stream instance. -// cfg can be jsoniter.ConfigDefault. -// out can be nil if write to internal buffer. -// bufSize is the initial size for the internal buffer in bytes. -func NewStream(cfg API, out io.Writer, bufSize int) *Stream { - return &Stream{ - cfg: cfg.(*frozenConfig), - out: out, - buf: make([]byte, 0, bufSize), - Error: nil, - indention: 0, - } -} - -// Pool returns a pool can provide more stream with same configuration -func (stream *Stream) Pool() StreamPool { - return stream.cfg -} - -// Reset reuse this stream instance by assign a new writer -func (stream *Stream) Reset(out io.Writer) { - stream.out = out - stream.buf = stream.buf[:0] -} - -// Available returns how many bytes are unused in the buffer. -func (stream *Stream) Available() int { - return cap(stream.buf) - len(stream.buf) -} - -// Buffered returns the number of bytes that have been written into the current buffer. -func (stream *Stream) Buffered() int { - return len(stream.buf) -} - -// Buffer if writer is nil, use this method to take the result -func (stream *Stream) Buffer() []byte { - return stream.buf -} - -// SetBuffer allows to append to the internal buffer directly -func (stream *Stream) SetBuffer(buf []byte) { - stream.buf = buf -} - -// Write writes the contents of p into the buffer. -// It returns the number of bytes written. -// If nn < len(p), it also returns an error explaining -// why the write is short. -func (stream *Stream) Write(p []byte) (nn int, err error) { - stream.buf = append(stream.buf, p...) - if stream.out != nil { - nn, err = stream.out.Write(stream.buf) - stream.buf = stream.buf[nn:] - return - } - return len(p), nil -} - -// WriteByte writes a single byte. -func (stream *Stream) writeByte(c byte) { - stream.buf = append(stream.buf, c) -} - -func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) { - stream.buf = append(stream.buf, c1, c2) -} - -func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) { - stream.buf = append(stream.buf, c1, c2, c3) -} - -func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) { - stream.buf = append(stream.buf, c1, c2, c3, c4) -} - -func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) { - stream.buf = append(stream.buf, c1, c2, c3, c4, c5) -} - -// Flush writes any buffered data to the underlying io.Writer. -func (stream *Stream) Flush() error { - if stream.out == nil { - return nil - } - if stream.Error != nil { - return stream.Error - } - _, err := stream.out.Write(stream.buf) - if err != nil { - if stream.Error == nil { - stream.Error = err - } - return err - } - stream.buf = stream.buf[:0] - return nil -} - -// WriteRaw write string out without quotes, just like []byte -func (stream *Stream) WriteRaw(s string) { - stream.buf = append(stream.buf, s...) -} - -// WriteNil write null to stream -func (stream *Stream) WriteNil() { - stream.writeFourBytes('n', 'u', 'l', 'l') -} - -// WriteTrue write true to stream -func (stream *Stream) WriteTrue() { - stream.writeFourBytes('t', 'r', 'u', 'e') -} - -// WriteFalse write false to stream -func (stream *Stream) WriteFalse() { - stream.writeFiveBytes('f', 'a', 'l', 's', 'e') -} - -// WriteBool write true or false into stream -func (stream *Stream) WriteBool(val bool) { - if val { - stream.WriteTrue() - } else { - stream.WriteFalse() - } -} - -// WriteObjectStart write { with possible indention -func (stream *Stream) WriteObjectStart() { - stream.indention += stream.cfg.indentionStep - stream.writeByte('{') - stream.writeIndention(0) -} - -// WriteObjectField write "field": with possible indention -func (stream *Stream) WriteObjectField(field string) { - stream.WriteString(field) - if stream.indention > 0 { - stream.writeTwoBytes(':', ' ') - } else { - stream.writeByte(':') - } -} - -// WriteObjectEnd write } with possible indention -func (stream *Stream) WriteObjectEnd() { - stream.writeIndention(stream.cfg.indentionStep) - stream.indention -= stream.cfg.indentionStep - stream.writeByte('}') -} - -// WriteEmptyObject write {} -func (stream *Stream) WriteEmptyObject() { - stream.writeByte('{') - stream.writeByte('}') -} - -// WriteMore write , with possible indention -func (stream *Stream) WriteMore() { - stream.writeByte(',') - stream.writeIndention(0) -} - -// WriteArrayStart write [ with possible indention -func (stream *Stream) WriteArrayStart() { - stream.indention += stream.cfg.indentionStep - stream.writeByte('[') - stream.writeIndention(0) -} - -// WriteEmptyArray write [] -func (stream *Stream) WriteEmptyArray() { - stream.writeTwoBytes('[', ']') -} - -// WriteArrayEnd write ] with possible indention -func (stream *Stream) WriteArrayEnd() { - stream.writeIndention(stream.cfg.indentionStep) - stream.indention -= stream.cfg.indentionStep - stream.writeByte(']') -} - -func (stream *Stream) writeIndention(delta int) { - if stream.indention == 0 { - return - } - stream.writeByte('\n') - toWrite := stream.indention - delta - for i := 0; i < toWrite; i++ { - stream.buf = append(stream.buf, ' ') - } -} diff --git a/vendor/github.com/json-iterator/go/stream_float.go b/vendor/github.com/json-iterator/go/stream_float.go deleted file mode 100644 index 826aa594..00000000 --- a/vendor/github.com/json-iterator/go/stream_float.go +++ /dev/null @@ -1,111 +0,0 @@ -package jsoniter - -import ( - "fmt" - "math" - "strconv" -) - -var pow10 []uint64 - -func init() { - pow10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000} -} - -// WriteFloat32 write float32 to stream -func (stream *Stream) WriteFloat32(val float32) { - if math.IsInf(float64(val), 0) || math.IsNaN(float64(val)) { - stream.Error = fmt.Errorf("unsupported value: %f", val) - return - } - abs := math.Abs(float64(val)) - fmt := byte('f') - // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. - if abs != 0 { - if float32(abs) < 1e-6 || float32(abs) >= 1e21 { - fmt = 'e' - } - } - stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32) -} - -// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster -func (stream *Stream) WriteFloat32Lossy(val float32) { - if math.IsInf(float64(val), 0) || math.IsNaN(float64(val)) { - stream.Error = fmt.Errorf("unsupported value: %f", val) - return - } - if val < 0 { - stream.writeByte('-') - val = -val - } - if val > 0x4ffffff { - stream.WriteFloat32(val) - return - } - precision := 6 - exp := uint64(1000000) // 6 - lval := uint64(float64(val)*float64(exp) + 0.5) - stream.WriteUint64(lval / exp) - fval := lval % exp - if fval == 0 { - return - } - stream.writeByte('.') - for p := precision - 1; p > 0 && fval < pow10[p]; p-- { - stream.writeByte('0') - } - stream.WriteUint64(fval) - for stream.buf[len(stream.buf)-1] == '0' { - stream.buf = stream.buf[:len(stream.buf)-1] - } -} - -// WriteFloat64 write float64 to stream -func (stream *Stream) WriteFloat64(val float64) { - if math.IsInf(val, 0) || math.IsNaN(val) { - stream.Error = fmt.Errorf("unsupported value: %f", val) - return - } - abs := math.Abs(val) - fmt := byte('f') - // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. - if abs != 0 { - if abs < 1e-6 || abs >= 1e21 { - fmt = 'e' - } - } - stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64) -} - -// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster -func (stream *Stream) WriteFloat64Lossy(val float64) { - if math.IsInf(val, 0) || math.IsNaN(val) { - stream.Error = fmt.Errorf("unsupported value: %f", val) - return - } - if val < 0 { - stream.writeByte('-') - val = -val - } - if val > 0x4ffffff { - stream.WriteFloat64(val) - return - } - precision := 6 - exp := uint64(1000000) // 6 - lval := uint64(val*float64(exp) + 0.5) - stream.WriteUint64(lval / exp) - fval := lval % exp - if fval == 0 { - return - } - stream.writeByte('.') - for p := precision - 1; p > 0 && fval < pow10[p]; p-- { - stream.writeByte('0') - } - stream.WriteUint64(fval) - for stream.buf[len(stream.buf)-1] == '0' { - stream.buf = stream.buf[:len(stream.buf)-1] - } -} diff --git a/vendor/github.com/json-iterator/go/stream_int.go b/vendor/github.com/json-iterator/go/stream_int.go deleted file mode 100644 index d1059ee4..00000000 --- a/vendor/github.com/json-iterator/go/stream_int.go +++ /dev/null @@ -1,190 +0,0 @@ -package jsoniter - -var digits []uint32 - -func init() { - digits = make([]uint32, 1000) - for i := uint32(0); i < 1000; i++ { - digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0' - if i < 10 { - digits[i] += 2 << 24 - } else if i < 100 { - digits[i] += 1 << 24 - } - } -} - -func writeFirstBuf(space []byte, v uint32) []byte { - start := v >> 24 - if start == 0 { - space = append(space, byte(v>>16), byte(v>>8)) - } else if start == 1 { - space = append(space, byte(v>>8)) - } - space = append(space, byte(v)) - return space -} - -func writeBuf(buf []byte, v uint32) []byte { - return append(buf, byte(v>>16), byte(v>>8), byte(v)) -} - -// WriteUint8 write uint8 to stream -func (stream *Stream) WriteUint8(val uint8) { - stream.buf = writeFirstBuf(stream.buf, digits[val]) -} - -// WriteInt8 write int8 to stream -func (stream *Stream) WriteInt8(nval int8) { - var val uint8 - if nval < 0 { - val = uint8(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint8(nval) - } - stream.buf = writeFirstBuf(stream.buf, digits[val]) -} - -// WriteUint16 write uint16 to stream -func (stream *Stream) WriteUint16(val uint16) { - q1 := val / 1000 - if q1 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[val]) - return - } - r1 := val - q1*1000 - stream.buf = writeFirstBuf(stream.buf, digits[q1]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return -} - -// WriteInt16 write int16 to stream -func (stream *Stream) WriteInt16(nval int16) { - var val uint16 - if nval < 0 { - val = uint16(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint16(nval) - } - stream.WriteUint16(val) -} - -// WriteUint32 write uint32 to stream -func (stream *Stream) WriteUint32(val uint32) { - q1 := val / 1000 - if q1 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[val]) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q1]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q2]) - } else { - r3 := q2 - q3*1000 - stream.buf = append(stream.buf, byte(q3+'0')) - stream.buf = writeBuf(stream.buf, digits[r3]) - } - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) -} - -// WriteInt32 write int32 to stream -func (stream *Stream) WriteInt32(nval int32) { - var val uint32 - if nval < 0 { - val = uint32(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint32(nval) - } - stream.WriteUint32(val) -} - -// WriteUint64 write uint64 to stream -func (stream *Stream) WriteUint64(val uint64) { - q1 := val / 1000 - if q1 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[val]) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q1]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q2]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r3 := q2 - q3*1000 - q4 := q3 / 1000 - if q4 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q3]) - stream.buf = writeBuf(stream.buf, digits[r3]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r4 := q3 - q4*1000 - q5 := q4 / 1000 - if q5 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q4]) - stream.buf = writeBuf(stream.buf, digits[r4]) - stream.buf = writeBuf(stream.buf, digits[r3]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) - return - } - r5 := q4 - q5*1000 - q6 := q5 / 1000 - if q6 == 0 { - stream.buf = writeFirstBuf(stream.buf, digits[q5]) - } else { - stream.buf = writeFirstBuf(stream.buf, digits[q6]) - r6 := q5 - q6*1000 - stream.buf = writeBuf(stream.buf, digits[r6]) - } - stream.buf = writeBuf(stream.buf, digits[r5]) - stream.buf = writeBuf(stream.buf, digits[r4]) - stream.buf = writeBuf(stream.buf, digits[r3]) - stream.buf = writeBuf(stream.buf, digits[r2]) - stream.buf = writeBuf(stream.buf, digits[r1]) -} - -// WriteInt64 write int64 to stream -func (stream *Stream) WriteInt64(nval int64) { - var val uint64 - if nval < 0 { - val = uint64(-nval) - stream.buf = append(stream.buf, '-') - } else { - val = uint64(nval) - } - stream.WriteUint64(val) -} - -// WriteInt write int to stream -func (stream *Stream) WriteInt(val int) { - stream.WriteInt64(int64(val)) -} - -// WriteUint write uint to stream -func (stream *Stream) WriteUint(val uint) { - stream.WriteUint64(uint64(val)) -} diff --git a/vendor/github.com/json-iterator/go/stream_str.go b/vendor/github.com/json-iterator/go/stream_str.go deleted file mode 100644 index 54c2ba0b..00000000 --- a/vendor/github.com/json-iterator/go/stream_str.go +++ /dev/null @@ -1,372 +0,0 @@ -package jsoniter - -import ( - "unicode/utf8" -) - -// htmlSafeSet holds the value true if the ASCII character with the given -// array position can be safely represented inside a JSON string, embedded -// inside of HTML {{template "jshtml"}} \ No newline at end of file From 4aeb8e1b5011da45a4d8b59732f116180df6baad Mon Sep 17 00:00:00 2001 From: zhang21 Date: Wed, 27 Sep 2023 16:21:13 +0800 Subject: [PATCH 09/19] =?UTF-8?q?feat:=20=E9=92=89=E9=92=89=E5=8A=A0?= =?UTF-8?q?=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.MD | 3 +- conf/app-example.conf | 3 ++ controllers/dingding.go | 57 +++++++++++++++++++++++++++++++++--- controllers/dingding_test.go | 42 ++++++++++++++++++++++++++ doc/readme/conf-dingding.md | 54 +++++++++++++++++++++++++++++----- 5 files changed, 146 insertions(+), 13 deletions(-) create mode 100644 controllers/dingding_test.go diff --git a/README.MD b/README.MD index f0bb2c20..09fe5abe 100644 --- a/README.MD +++ b/README.MD @@ -53,7 +53,7 @@ make docker/docker-push/docker-test # 本地测试运行 make clean && make build copy conf/app-example.conf conf/app.conf -build/bin/PrometheusAlert +./PrometheusAlert # 测试应用健康 curl http://localhost:8080/health @@ -136,6 +136,7 @@ feiyu563/prometheus-alert:latest - 增加支持飞书机器人应用。 - 增加告警组,可以将通知媒介写到告警组里面,便于配置和修改。 - 增加热加载配置接口 + - 增加钉钉加签 ------------------------------------- diff --git a/conf/app-example.conf b/conf/app-example.conf index fe8307a3..a7265ef5 100644 --- a/conf/app-example.conf +++ b/conf/app-example.conf @@ -69,6 +69,9 @@ open-dingding=1 ddurl=https://oapi.dingtalk.com/robot/send?access_token=xxxxx #是否开启 @所有人(0为关闭,1为开启) dd_isatall=1 +#是否开启钉钉机器人加签,0为关闭,1为开启 +# 使用方法:https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&secret=mysecret +open-dingding-secret=0 #是否开启微信告警通道,可同时开始多个通道0为关闭,1为开启 open-weixin=1 diff --git a/controllers/dingding.go b/controllers/dingding.go index ebb00239..04db30c8 100644 --- a/controllers/dingding.go +++ b/controllers/dingding.go @@ -3,14 +3,20 @@ package controllers import ( "PrometheusAlert/models" "bytes" + "crypto/hmac" + "crypto/sha256" "crypto/tls" + "encoding/base64" "encoding/json" - "github.com/astaxie/beego" - "github.com/astaxie/beego/logs" - "io/ioutil" + "io" "net/http" "net/url" + "strconv" "strings" + "time" + + "github.com/astaxie/beego" + "github.com/astaxie/beego/logs" ) type DDMessage struct { @@ -31,6 +37,11 @@ func PostToDingDing(title, text, Ddurl, AtSomeOne, logsign string) string { logs.Info(logsign, "[dingding]", "钉钉接口未配置未开启状态,请先配置open-dingding为1") return "钉钉接口未配置未开启状态,请先配置open-dingding为1" } + // dingding sign + if openSecret := beego.AppConfig.String("open-dingding-secret"); openSecret == "1" { + Ddurl = dingdingSign(Ddurl) + } + Isatall, _ := beego.AppConfig.Int("dd_isatall") Atall := true if Isatall == 0 { @@ -82,7 +93,7 @@ func PostToDingDing(title, text, Ddurl, AtSomeOne, logsign string) string { logs.Error(logsign, "[dingding]", err.Error()) } defer res.Body.Close() - result, err := ioutil.ReadAll(res.Body) + result, err := io.ReadAll(res.Body) if err != nil { logs.Error(logsign, "[dingding]", err.Error()) } @@ -91,3 +102,41 @@ func PostToDingDing(title, text, Ddurl, AtSomeOne, logsign string) string { logs.Info(logsign, "[dingding]", string(result)) return string(result) } + +// dingdingSign adds sign and timestamp parms to dingding webhook url +// docs: https://open.dingtalk.com/document/orgapp/custom-bot-creation-and-installation +func dingdingSign(ddurl string) string { + timestamp := time.Now() + timestampMs := timestamp.UnixNano() / int64(time.Millisecond) + tsMsStr := strconv.FormatInt(timestampMs, 10) + // parse ddurl parms + u, err := url.Parse(ddurl) + if err != nil { + logs.Info("[dingdingSign]", "配置文件已开启钉钉加签,钉钉机器人地址解析加签参数 secret 失败,将使用不加签的地址!") + return ddurl + } + // get parm secret + queryParams := u.Query() + secret := queryParams.Get("secret") + if len(secret) == 0 { + logs.Info("[dingdingSign]", "配置文件已开启钉钉加签,钉钉机器人地址解析加签参数 secret 为空,将使用不加签的地址!") + return ddurl + } + // sign string + signStr := tsMsStr + "\n" + secret + // HmacSHA256 + key := []byte(secret) + h := hmac.New(sha256.New, key) + h.Write([]byte(signStr)) + signature := h.Sum(nil) + // Base64 + sign := base64.StdEncoding.EncodeToString(signature) + // splice url + delete(queryParams, "secret") + queryParams.Add("timestamp", tsMsStr) + queryParams.Add("sign", sign) + u.RawQuery = queryParams.Encode() + signURL := u.String() + + return signURL +} diff --git a/controllers/dingding_test.go b/controllers/dingding_test.go new file mode 100644 index 00000000..f07f297b --- /dev/null +++ b/controllers/dingding_test.go @@ -0,0 +1,42 @@ +package controllers + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDDMesage(t *testing.T) { + // A sample dingding message json payload + payload := ` + { + "msgtype": "markdown", + "markdown": { + "title": "AlertPrometheus告警测试", + "text": "**测试告警信息**\n" + }, + "at": { + "atMobiles": ["139xxxxxxxx", "159xxxxxxxx"], + "isAtAll": false + } + }` + message := DDMessage{} + err := json.Unmarshal([]byte(payload), &message) + assert.Nil(t, err) +} + +func TestDingdingSign(t *testing.T) { + var want, result string + + // url without parm secret + withoutURL := "https://oapi.dingtalk.com/robot/send?access_token=XXX" + want = withoutURL + result = dingdingSign(withoutURL) + assert.Equal(t, want, result) + + // url with parm secret + withURL := "https://oapi.dingtalk.com/robot/send?access_token=XXX&secret=mysecret" + result = dingdingSign(withURL) + t.Logf("一个示例的加签的地址:%s", result) +} diff --git a/doc/readme/conf-dingding.md b/doc/readme/conf-dingding.md index 72cb2f11..b8870143 100644 --- a/doc/readme/conf-dingding.md +++ b/doc/readme/conf-dingding.md @@ -1,8 +1,6 @@ # PrometheusAlert全家桶钉钉配置说明 ------------------ - - **开启钉钉机器人** +## 开启钉钉机器人 打开钉钉,进入钉钉群中,选择群设置-->智能群助手-->添加机器人-->自定义,可参下图: @@ -10,6 +8,8 @@ ![ding2](../images/dingding2.png) +
+ 新版本的钉钉加了安全设置,只需选择安全设置中的 自定义关键词 即可,并将关键词设置为 Prometheus或者app.conf中设置的title值均可,参考下图 ![ding3](../images/dingding3.png) @@ -18,12 +18,15 @@ 复制图中的Webhook地址,并填入PrometheusAlert配置文件app.conf中对应配置项即可。 +
+ **PS: 钉钉机器人目前已经支持 `@某人` ,使用该功能需要取得对应用户的钉钉关联手机号码,如下图:** + ![ding4](../images/dingding5.png) 钉钉目前支持只支持markdown语法的子集,具体支持的元素如下: -``` +```md 标题 # 一级标题 ## 二级标题 @@ -54,9 +57,38 @@ 2. item2 ``` -钉钉相关配置: +
+
+ +## 钉钉加签配置 + +增加钉钉加签的配置。创建自定义机器人的时候,选择加签,并复制加签内容组装到到机器人地址参数(webhook url parm secret)。程序会获取这个 `secret` 参数,进行加签处理之后生成对应的加签地址。 + +如果配置文件中启用了钉钉加签认证,但 webhook url 并没有传递 parm secret,那么程序将返回不加签的地址。也就是说,PrometheusAlert 配置中启用钉钉加签并不会影响不加签的机器人。 + +示例如下: +```conf +# 默认的钉钉机器人地址 webhook url 格式 +https://oapi.dingtalk.com/robot/send?access_token=XXX + +# 假如机器人加签内容为:mysecret +# 带上加签参数: secret=mysecret +https://oapi.dingtalk.com/robot/send?access_token=XXX&secret=mysecret + +# 程序加签处理后生成的加签地址 +https://oapi.dingtalk.com/robot/send?access_token=XXXXXX×tamp=XXX&sign=XXX + +# 如果配置文件中启用了钉钉加签认证,但 webhook url 并没有传递 parm secret,那么程序将返回不加签的地址 +https://oapi.dingtalk.com/robot/send?access_token=XXX ``` + +
+
+ +## 钉钉相关配置 + +```ini #---------------------↓全局配置----------------------- #告警消息标题 title=PrometheusAlert @@ -72,15 +104,21 @@ open-dingding=1 ddurl=https://oapi.dingtalk.com/robot/send?access_token=xxxxx #是否开启 @所有人(0为关闭,1为开启) dd_isatall=1 +#是否开启钉钉机器人加签,0为关闭,1为开启 +# 使用方法:https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&secret=mysecret +open-dingding-secret=0 ``` -**如何使用** +
+
+ +## 如何使用 以Prometheus配合自定义模板为例: Prometheus配置参考: -``` +```yml global: resolve_timeout: 5m route: @@ -93,4 +131,4 @@ receivers: - name: 'web.hook.prometheusalert' webhook_configs: - url: 'http://[prometheusalert_url]:8080/prometheusalert?type=dd&tpl=prometheus-dd&ddurl=钉钉机器人地址,钉钉机器人地址2&at=18888888888,18888888889' -``` \ No newline at end of file +``` From 1bb813fc4c43c3023a13a3b2427f240e200cada6 Mon Sep 17 00:00:00 2001 From: YuHaoXiang <398972900@qq.com> Date: Wed, 29 Nov 2023 22:37:14 +0800 Subject: [PATCH 10/19] fix feishu api v2 can't @user with email. --- controllers/feishu.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/feishu.go b/controllers/feishu.go index 5d1e706e..f56f30d7 100644 --- a/controllers/feishu.go +++ b/controllers/feishu.go @@ -135,7 +135,7 @@ func PostToFeiShuv2(title, text, Fsurl, userOpenId, logsign string) string { OpenIds := strings.Split(userOpenId, ",") OpenIdtext := "" for _, OpenId := range OpenIds { - OpenIdtext += "" + OpenIdtext += "" } SendContent += OpenIdtext } From 23889f83aae7af59825d28f28eb5cf73da4e3994 Mon Sep 17 00:00:00 2001 From: zhang21 Date: Tue, 26 Dec 2023 12:22:21 +0800 Subject: [PATCH 11/19] =?UTF-8?q?fix:=20=E6=9B=B4=E6=96=B0=E9=92=89?= =?UTF-8?q?=E9=92=89=E5=8A=A0=E7=AD=BE=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/readme/conf-dingding.md | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/doc/readme/conf-dingding.md b/doc/readme/conf-dingding.md index b8870143..09e5a3b0 100644 --- a/doc/readme/conf-dingding.md +++ b/doc/readme/conf-dingding.md @@ -66,7 +66,15 @@ 如果配置文件中启用了钉钉加签认证,但 webhook url 并没有传递 parm secret,那么程序将返回不加签的地址。也就是说,PrometheusAlert 配置中启用钉钉加签并不会影响不加签的机器人。 -示例如下: +[issue:363](https://github.com/feiyu563/PrometheusAlert/issues/363) 关于自定义模板使用 URL 传递 ddurl 和签名报错,需要修改使用方法。 + +在自定义模板 URL 参数的 ddurl 里面可能有多个地址,有的加签,有的不加签。因此代码不太好处理,暂时没有解决。建议使用告警组或将 `&` 符号替换为 `%26` 编码。 + +默认模板、配置文件和使用告警组的钉钉加签是正常的。 + +
+ +配置文件传递地址示例如下: ```conf # 默认的钉钉机器人地址 webhook url 格式 @@ -76,13 +84,32 @@ https://oapi.dingtalk.com/robot/send?access_token=XXX # 带上加签参数: secret=mysecret https://oapi.dingtalk.com/robot/send?access_token=XXX&secret=mysecret -# 程序加签处理后生成的加签地址 -https://oapi.dingtalk.com/robot/send?access_token=XXXXXX×tamp=XXX&sign=XXX +# 程序加签处理后生成的加签地址: https://oapi.dingtalk.com/robot/send?access_token=XXXXXX×tamp=XXX&sign=XXX # 如果配置文件中启用了钉钉加签认证,但 webhook url 并没有传递 parm secret,那么程序将返回不加签的地址 https://oapi.dingtalk.com/robot/send?access_token=XXX ``` +
+ +自定义模板 URL 参数传递地址配置如下: + +```conf +# 使用告警组配置地址 +http://prometheusalert:8080/prometheusalert?type=dd&tpl=prometheus-dd&alertgroup=xxx&at=xxx + +# 需要把 & 特殊字符转义为 %26 编码字符 +# 单个地址 +http://prometheusalert:8080/prometheusalert?type=dd&tpl=prometheus-dd&ddurl=加签地址%26secret=xxx&at=xxx + +# 多个地址 +http://prometheusalert:8080/prometheusalert?type=dd&tpl=prometheus-dd&ddurl=加签地址%26secret=xxx,加签地址%26secret=xxx + +# 混合加签和不加签地址 +http://prometheusalert:8080/prometheusalert?type=dd&tpl=prometheus-dd&ddurl=不加签地址,加签地址%26secret=xxx +``` + +

From f300866a339d61c7839fa4dfa59a830b49577ce6 Mon Sep 17 00:00:00 2001 From: zhang21 Date: Thu, 6 Jun 2024 14:13:23 +0800 Subject: [PATCH 12/19] fix: es 7.x and es 8.x --- Dockerfile | 4 +- README.MD | 100 +++++++++++++++++++------ controllers/prometheus.go | 10 ++- controllers/prometheusalert.go | 6 +- doc/readme/alertgroup.md | 4 +- doc/readme/conf-dingding.md | 5 +- doc/readme/conf-es.md | 15 +++- go.mod | 35 ++++++++- go.sum | 53 +++---------- models/elastic/elasticsearch.go | 128 +++++++++++++++----------------- 10 files changed, 208 insertions(+), 152 deletions(-) diff --git a/Dockerfile b/Dockerfile index 4386cd7d..3934a323 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.20.6-alpine3.18 as builder +FROM golang:1.21-alpine3.20 as builder WORKDIR $GOPATH/src/github.com/feiyu563/PrometheusAlert @@ -14,7 +14,7 @@ COPY . $GOPATH/src/github.com/feiyu563/PrometheusAlert RUN make build # ----------------------------------------------------------------------------- -FROM alpine:3.18 +FROM alpine:3.20 LABEL maintainer="jikun.zhang" diff --git a/README.MD b/README.MD index 09fe5abe..2a03f60b 100644 --- a/README.MD +++ b/README.MD @@ -1,7 +1,5 @@ # PrometheusAlert全家桶 ---------------------------------------- - ![author](https://img.shields.io/badge/author-jikun.zhang-blueviolet.svg) ![license](https://img.shields.io/github/license/feiyu563/PrometheusAlert.svg) ![last commit](https://img.shields.io/github/last-commit/feiyu563/PrometheusAlert.svg) @@ -16,23 +14,70 @@ [![Travis](https://img.shields.io/badge/language-JavaScript-yellow.svg)]() [![Travis](https://img.shields.io/badge/language-Shell-blue.svg)]() ---------------------------------------- +
+ +## 项目介绍 PrometheusAlert是开源的运维告警中心消息转发系统,支持主流的监控系统Prometheus、Zabbix,日志系统Graylog2,Graylog3、数据可视化系统Grafana、SonarQube。阿里云-云监控,以及所有支持WebHook接口的系统发出的预警消息,支持将收到的这些消息发送到钉钉,微信,email,飞书,腾讯短信,腾讯电话,阿里云短信,阿里云电话,华为短信,百度云短信,容联云电话,七陌短信,七陌语音,TeleGram,百度Hi(如流)等。 ![it](doc/images/it.png) ----------------------------------------- +-------------------------------------- * 如果这个项目能为您带来帮助,我将感到非常荣幸!同时非常欢迎您加入PrometheusAlert全家桶的微信群一起探讨关于PrometheusAlert新一期的开发计划。 - * PrometheusAlert的成长离不开所有爱好运维和开发的朋友们的支持!如果您也对这个项目感兴趣,请点击一下 Star 以示鼓励,谢谢 ----------------------------------------- +
-## 构建 +## 项目架构 -应用信息和构建相关的命令都写入了Makefile,请确保安装`make`, `git`, `go`命令。如有特定需要,请自行修改Makefile。 +PrometheusAlert 后端使用了 [beego](https://github.com/beego/beego) 框架,前端使用了 [AdminLTE](https://github.com/ColorlibHQ/AdminLTE) (基于 Bootstrap 和 Jquery)模板。 + +项目文件: + +``` +├── cmd: 脚本 +├── conf: 配置 +├── controllers:控制器 +├── db:默认的 sqlite 数据 +├── doc:文档 +├── docker-entrypoint.sh:容器运行入口文件 +├── Dockerfile +├── example:示例文件 +├── go.mod +├── go.sum +├── LICENSE +├── main.go +├── Makefile +├── models:模型 +├── PrometheusAlert:二进制文件 +├── PrometheusAlertVoicePlugin +├── README.MD +├── routers:路由 +├── static:静态资源 +├── swagger +├── tests:测试 +├── views:前端模板 +└── zabbixclient +``` + +
+ +## 快速开始 + +你可以通过以下方式快速开始: + +- 通过源代码构建 +- 下载发行版本 +- 通过 Docker 运行 + +
+ +### 构建 + +应用信息和构建相关的命令都写入了 Makefile,请确保安装`make`, `git`, `go`命令。如有特定需要,请自行修改 Makefile。 + +默认构建生成的文件是 `./PrometheusAlert`。 ```sh # 默认 @@ -61,9 +106,9 @@ curl http://localhost:8080/health
-------------------------------------- +### 下载发行版本 -## 启动 +通过下载编译好的发行版本,解压后运行。 ```sh #打开PrometheusAlert releases页面,根据需要选择需要的版本下载到本地解压并进入解压后的目录 @@ -82,7 +127,9 @@ curl http://localhost:8080/health # 如果需要将日志输出到控制台,请修改 app.conf 中 logtype=console ``` -## Docker 启动 +
+ +### 通过 Docker 启动 配置文件 app.conf 的内容可以使用环境变量的方式初始化。 @@ -92,7 +139,7 @@ curl http://localhost:8080/health 示例 -``` +```sh docker run -d \ -p 8080:8080 \ -e PA_LOGIN_USER=prometheusalert \ @@ -104,18 +151,29 @@ docker run -d \ feiyu563/prometheus-alert:latest ``` -所有的配置文件内容请[点击此处](https://github.com/feiyu563/PrometheusAlert/blob/master/conf/app-example.conf)查看 +
+ +### 配置文件 + +配置文件位于 `conf/app.conf`,默认采用 INI 格式解析。 + +所有的配置文件内容请[点击此处](https://github.com/feiyu563/PrometheusAlert/blob/master/conf/app-example.conf)查看。 + +
+ +### 运行效果图 ---------------------------------------- +程序运行后,访问默认地址 `http://localhost:8080` 的效果如下。 ![dashboard](doc/images/dashboard.png) + ![dashboard-test](doc/images/template.png) --------------------------------------- +
-## PrometheusAlert具备如下特性 +## 特性 --------------------------------------- +PrometheusAlert 具备如下特性: - 支持任意包含WebHook接口系统的消息作为消息来源,常见的如Prometheus,Zabbix,Graylog2,Graylog3,Grafana,SonarQube和其他WebHook接口的系统。 - 支持多种类型的发送目标,支持钉钉,企业微信,email,飞书,腾讯短信,腾讯语音,阿里云短信,阿里云语音,华为短信,百度云短信,容联云电话,七陌短信,七陌语音,TeleGram,百度Hi(如流)。 @@ -129,7 +187,7 @@ feiyu563/prometheus-alert:latest - 增加支持钉钉,企业微信的@某人功能 - 增加支持阿里云-云监控告警 - 增加随机轮询,目前仅针对ddurl,fsurl,wxurl有效,默认情况下如果上述Url配置的是多个地址,则多个地址全部发送,如开启该选项,则从多个地址中随机取一个地址发送,主要是为了避免消息发送频率过高导致触发部分机器人拦截消息 - - 增加支持将Prometheus告警记录写入到Elasticsearch7.x,可通过Kibana进行界面查看告警记录和配置表格导出。 + - 增加支持将 Prometheus 告警记录写入到 ES7.x 和 ES 8.x,可通过 Kibana 进行界面查看告警记录和配置表格导出。 - 增加支持将Gitlab webhook event推送到企微和钉钉。 - 增加告警路由和告警记录功能,可通过页面查看告警历史和操作告警消息路由。 - 增加告警语音播报插件。 @@ -138,12 +196,10 @@ feiyu563/prometheus-alert:latest - 增加热加载配置接口 - 增加钉钉加签 -------------------------------------- +
## 致谢以下伙伴对PrometheusAlert的贡献 --------------------------------------- - - [@cyancow](https://github.com/cyancow) - [@birkh8792](https://github.com/birkh8792) - [@minibear2333](https://github.com/minibear2333) @@ -154,7 +210,7 @@ feiyu563/prometheus-alert:latest - [@guvmao](https://github.com/guvmao) - [@lusson-luo](https://github.com/lusson-luo) --------------------------------------- +
## PrometheusAlert全家桶新手入门 diff --git a/controllers/prometheus.go b/controllers/prometheus.go index 6670caff..8a3b19ce 100644 --- a/controllers/prometheus.go +++ b/controllers/prometheus.go @@ -4,6 +4,7 @@ import ( "PrometheusAlert/models" "PrometheusAlert/models/elastic" "encoding/json" + "fmt" "sort" "strconv" "strings" @@ -30,6 +31,7 @@ type Labels struct { Job string `json:"job"` Hostgroup string `json:"hostgroup,omitempty"` Hostname string `json:"hostname,omitempty"` + Cloud string `json:"cloud"` } // Annotations are promtheus annotions. @@ -376,8 +378,7 @@ func SendMessageR(message Prometheus, rwxurl, rddurl, rfsurl, rphone, remail, rg dt := time.Now() dty, dtm := dt.Year(), int(dt.Month()) // example esIndex: prometheusalert-202112 - esIndex := "prometheusalert-" + strconv.Itoa(dty) + strconv.Itoa(dtm) - // Index a prometheusalert (using JSON serialization) + esIndex := fmt.Sprintf("prometheusalert-%d%02d", dty, dtm) alert := &elastic.AlertES{ Alertname: RMessage.Labels.Alertname, Status: RMessage.Status, @@ -389,8 +390,11 @@ func SendMessageR(message Prometheus, rwxurl, rddurl, rfsurl, rphone, remail, rg StartsAt: At, EndsAt: Et, Created: dt, + Cloud: RMessage.Labels.Cloud, + Hostgroup: RMessage.Labels.Hostgroup, + Hostnmae: RMessage.Labels.Hostname, } - elastic.Insert(esIndex, alert) + go elastic.Insert(esIndex, *alert) } } return "告警消息发送完成." diff --git a/controllers/prometheusalert.go b/controllers/prometheusalert.go index a4b30994..573825f1 100644 --- a/controllers/prometheusalert.go +++ b/controllers/prometheusalert.go @@ -5,9 +5,9 @@ import ( "PrometheusAlert/models/elastic" "bytes" "encoding/json" + "fmt" tmplhtml "html/template" "regexp" - "strconv" "strings" "text/template" "time" @@ -362,7 +362,7 @@ func SetRecord(AlertValue interface{}) { if beego.AppConfig.DefaultString("alert_to_es", "0") == "1" { dt := time.Now() dty, dtm := dt.Year(), int(dt.Month()) - esIndex := "prometheusalert-" + strconv.Itoa(dty) + strconv.Itoa(dtm) + esIndex := fmt.Sprintf("prometheusalert-%d%02d", dty, dtm) alert := &elastic.AlertES{ Alertname: Alertname, Status: Status, @@ -375,7 +375,7 @@ func SetRecord(AlertValue interface{}) { EndsAt: EndAt, Created: dt, } - elastic.Insert(esIndex, alert) + go elastic.Insert(esIndex, *alert) } } diff --git a/doc/readme/alertgroup.md b/doc/readme/alertgroup.md index c14191f8..89291419 100644 --- a/doc/readme/alertgroup.md +++ b/doc/readme/alertgroup.md @@ -43,7 +43,7 @@ open-alertgroup=1 # sa 组 [ag-sa] wxurl=wxurl1,wxurl2 -ddurl=ddurl1 +ddurl=https://oapi.dingtalk.com/robot/send?access_token=xxx&secret=xx phone=13x,15x # 自定义的告警组配置 @@ -70,7 +70,7 @@ phone=13x,17x,18x # 自定义模板告警组示例,目前仅处理了以下这些参数 [customtpl] wxurl=wxurl1,wxurl2 -ddurl=ddurl1,ddurl2 +ddurl=ddurl1,https://oapi.dingtalk.com/robot/send?access_token=xxx&secret=xx fsurl=fsurl1,fsurl2 email=email1,email2 phone=phone1,phone2 diff --git a/doc/readme/conf-dingding.md b/doc/readme/conf-dingding.md index 09e5a3b0..4028d2c2 100644 --- a/doc/readme/conf-dingding.md +++ b/doc/readme/conf-dingding.md @@ -62,6 +62,10 @@ ## 钉钉加签配置 +**建议使用 [告警组](alertgroup.md) 来配置钉钉地址和加签配置**。 + +
+ 增加钉钉加签的配置。创建自定义机器人的时候,选择加签,并复制加签内容组装到到机器人地址参数(webhook url parm secret)。程序会获取这个 `secret` 参数,进行加签处理之后生成对应的加签地址。 如果配置文件中启用了钉钉加签认证,但 webhook url 并没有传递 parm secret,那么程序将返回不加签的地址。也就是说,PrometheusAlert 配置中启用钉钉加签并不会影响不加签的机器人。 @@ -109,7 +113,6 @@ http://prometheusalert:8080/prometheusalert?type=dd&tpl=prometheus-dd&ddurl=加 http://prometheusalert:8080/prometheusalert?type=dd&tpl=prometheus-dd&ddurl=不加签地址,加签地址%26secret=xxx ``` -

diff --git a/doc/readme/conf-es.md b/doc/readme/conf-es.md index 08fdf001..254c70bd 100644 --- a/doc/readme/conf-es.md +++ b/doc/readme/conf-es.md @@ -1,8 +1,12 @@ # 告警记录写入Elasticsearch **注意**: -- 客户端适配的是ES7.x版本! -- 索引根据年月动态创建`prometheusalert-YYMM`(如prometheusalert-202112) + +- 支持 ES 7.x 和 8.x 版本。(ES 从 v7 到 v8 有一些变化,但主要的 API 设计上是保持兼容的。) +- 索引根据年月动态创建 `prometheusalert-YYMM`(如prometheusalert-202112) + +
+
## es相关配置 @@ -10,8 +14,7 @@ # 是否将告警记录写入es7,0为关闭,1为开启 alert_to_es=0 -# es地址,是[]string -# beego.AppConfig.Strings读取配置为[]string,使用";"而不是"," +# es地址,是[]string,beego.AppConfig.Strings读取配置为[]string,使用";"而不是"," # 单个地址 to_es_url=http://localhost:9200 # 多个地址 @@ -22,11 +25,15 @@ to_es_url=http://localhost:9200 # to_es_pwd=password ``` +
+
+ ## Kibana展示效果 可直接创建索引模式展示告警记录。还可以自行创建表格、柱状图等展示。 ![kibana-index](../images/kibana-index.png) +
![kibana-table](../images/kibana-table.png) diff --git a/go.mod b/go.mod index 18b7a885..cde9eb19 100644 --- a/go.mod +++ b/go.mod @@ -1,22 +1,53 @@ module PrometheusAlert -go 1.16 +go 1.21 require ( github.com/aliyun/alibaba-cloud-sdk-go v1.61.1537 github.com/astaxie/beego v1.12.3 github.com/baidubce/bce-sdk-go v0.9.111 + github.com/elastic/go-elasticsearch/v7 v7.17.10 github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df github.com/go-sql-driver/mysql v1.6.0 github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 github.com/lib/pq v1.10.4 github.com/mattn/go-sqlite3 v2.0.3+incompatible - github.com/olivere/elastic/v7 v7.0.32 github.com/prometheus/client_golang v1.12.1 github.com/robfig/cron/v3 v3.0.1 github.com/smartystreets/goconvey v1.7.2 github.com/stretchr/testify v1.8.4 github.com/ysicing/workwxbot v1.1.0 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/jtolds/gls v4.20.0+incompatible // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_model v0.2.0 // indirect + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect + github.com/smartystreets/assertions v1.2.0 // indirect + golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect + golang.org/x/net v0.0.0-20210525063256-abc453219eb5 // indirect + golang.org/x/sys v0.14.0 // indirect + golang.org/x/text v0.3.6 // indirect + google.golang.org/protobuf v1.26.0 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect + gopkg.in/ini.v1 v1.66.2 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 7e6d211d..2e855e43 100644 --- a/go.sum +++ b/go.sum @@ -45,7 +45,6 @@ github.com/aliyun/alibaba-cloud-sdk-go v1.61.1537 h1:R6hnGHYn3jLXgv5lGi2vUvmTENd github.com/aliyun/alibaba-cloud-sdk-go v1.61.1537/go.mod h1:RcDobYh8k5VP6TNybz9m++gL3ijVI5wueVr0EM10VsU= github.com/astaxie/beego v1.12.3 h1:SAQkdD2ePye+v8Gn1r4X6IKZM1wd28EyUOVQ3PDSOOQ= github.com/astaxie/beego v1.12.3/go.mod h1:p3qIm0Ryx7zeBHLljmd7omloyca1s4yu1a8kM1FkpIA= -github.com/aws/aws-sdk-go v1.43.21/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= github.com/baidubce/bce-sdk-go v0.9.111 h1:yGgtPpZYUZW4uoVorQ4xnuEgVeddACydlcJKW87MDV4= github.com/baidubce/bce-sdk-go v0.9.111/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= @@ -75,14 +74,14 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elastic/go-elasticsearch/v7 v7.17.10 h1:TCQ8i4PmIJuBunvBS6bwT2ybzVFxxUhhltAs3Gyu1yo= +github.com/elastic/go-elasticsearch/v7 v7.17.10/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4= github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= -github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= @@ -96,8 +95,6 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= @@ -111,7 +108,6 @@ github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfU github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= @@ -148,11 +144,10 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= -github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -164,7 +159,6 @@ github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= @@ -175,13 +169,8 @@ github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+l github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= @@ -207,8 +196,6 @@ github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDu github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.10.4 h1:SO9z7FRPzA03QhHKJrH5BXA6HU1rS4V2nIVrrNC1iYk= github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= @@ -224,12 +211,9 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/olivere/elastic/v7 v7.0.32 h1:R7CXvbu8Eq+WlsLgxmKVKPox0oOwAE/2T9Si5BnvK6E= -github.com/olivere/elastic/v7 v7.0.32/go.mod h1:c7PVmLe3Fxq77PIfY/bZmxY/TAamBhCzZ8xDOE09a9k= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= @@ -273,25 +257,17 @@ github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -github.com/smartystreets/assertions v1.1.1/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM= github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM= -github.com/smartystreets/gunit v1.4.2/go.mod h1:ZjM1ozSIMJlAz/ay4SG8PeKF00ckUp+zMHZXV9/bvak= github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= @@ -309,9 +285,6 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= -go.opentelemetry.io/otel v1.5.0/go.mod h1:Jm/m+rNp/z0eqJc74H7LPwQ3G87qkU/AnnAydAjSAHk= -go.opentelemetry.io/otel/trace v1.5.0/go.mod h1:sq55kfhjXYr1zVSyexg0w1mpa03AYXR5eyTkB9NPPdE= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -378,10 +351,8 @@ golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210525063256-abc453219eb5 h1:wjuX4b5yYQnEQHzd+CBcrcC6OVR2J1CN6mUy0oSxIPo= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -430,25 +401,21 @@ golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= +golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -496,7 +463,6 @@ golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= @@ -561,7 +527,6 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/models/elastic/elasticsearch.go b/models/elastic/elasticsearch.go index 6a29ca3b..f2168f34 100644 --- a/models/elastic/elasticsearch.go +++ b/models/elastic/elasticsearch.go @@ -1,15 +1,21 @@ package elastic import ( + "bytes" "context" + "encoding/json" "time" "github.com/astaxie/beego" "github.com/astaxie/beego/logs" - es7 "github.com/olivere/elastic/v7" + "github.com/elastic/go-elasticsearch/v7" + "github.com/elastic/go-elasticsearch/v7/esapi" ) -var esCli *es7.Client +var ( + r map[string]interface{} + esClient *elasticsearch.Client +) // AlertES is a alert structure used for serializing data in ES. type AlertES struct { @@ -23,28 +29,11 @@ type AlertES struct { StartsAt string `json:"startsAt"` EndsAt string `json:"endsAt"` Created time.Time `json:"created"` + Cloud string `json:"cloud"` + Hostgroup string `json:"hostgroup"` + Hostnmae string `json:"hostname"` } -// es mapping field datatypes -const mapping = `{ - "mappings": { - "prometheusalert": { - "properties": { - "alertname": {"type": "keyword"}, - "status": {"type": "keyword"}, - "instance": {"type": "keyword"}, - "level": {"type": "keyword"}, - "labels": {"type": "keyword"}, - "startsAt": {"type": "date"}, - "endsAt": {"type": "date"}, - "created": {"type": "date"}, - "summary": {"type": "text", "store": true, "fielddata": true}, - "description": {"type": "text", "store": true, "fielddata": true} - } - } - } -}` - func init() { alertToES := beego.AppConfig.DefaultString("alert_to_es", "0") if alertToES == "1" { @@ -52,63 +41,64 @@ func init() { esUser := beego.AppConfig.DefaultString("to_es_user", "") esPwd := beego.AppConfig.DefaultString("to_es_pwd", "") - err := NewESClient(esURL, esUser, esPwd) + var err error + cfg := elasticsearch.Config{ + Addresses: esURL, + Username: esUser, + Password: esPwd, + } + esClient, err = elasticsearch.NewClient(cfg) + if err != nil { - logs.Error("[elasticsearch] Connecting to es %s error: %s", esURL, err) + logs.Error("[elasticsearch] Error creating the client: %s", err) + } + + // 如果 ES 不可用或连接异常等问题,获取 ES 集群信息会 panic 导致程序崩溃,因此使用 return 提前退出 + res, err := esClient.Info() + if err != nil { + logs.Critical("[elasticsearch] Error getting response: %s from cluster %s", err, esURL) + return + } + // 避免 res 为空(连接错误)时 panic 导致崩溃 + if res != nil { + defer res.Body.Close() + if res.IsError() { + logs.Error("[elasticsearch] Connection error: %s", res.String()) + return + } + if err := json.NewDecoder(res.Body).Decode(&r); err != nil { + logs.Error("[elasticsearch] Error parsing the response body: %s", err) + } + logs.Info("[elasticsearch] Successfully connected to ES Server Version: %s", r["version"].(map[string]interface{})["number"]) } } } -// NewESClient creates a new es client. -func NewESClient(url []string, user, pwd string) error { - ctx := context.Background() - var err error - esCli, err = es7.NewClient( - es7.SetURL(url...), - es7.SetBasicAuth(user, pwd), - es7.SetSniff(false), - es7.SetHealthcheck(false), - ) +func Insert(index string, alert AlertES) { + doc, err := json.Marshal(alert) if err != nil { - return err + logs.Error("[elasticsearch] error marshaling document: %w", err) + return } - info, code, err := esCli.Ping(url[0]).Do(ctx) - if err != nil { - return err + req := esapi.IndexRequest{ + Index: index, + Body: bytes.NewReader(doc), + Refresh: "true", } - logs.Info("[elasticsearch] ES returned with code: %d and version: %s", code, info.Version.Number) - - return nil -} - -// Insert writes prometheus alert to es. -func Insert(index string, value interface{}) { - ctx := context.Background() - /* - exists, err := esCli.IndexExists(index).Do(ctx) - if err != nil { - logs.Error("[elasticsearch] ES index: %s is not exist: %s", index, err) - } - if !exists { - createIndex, err := esCli.CreateIndex(index).Do(ctx) - if err != nil { - logs.Error("[elasticsearch] Create es index: %s error: %s", index, err) - } - if !createIndex.Acknowledged { - // Not acknowledge - } - } - */ - res, err := esCli.Index(). - Index(index). - Type("prometheusalert"). - BodyJson(value). - Do(ctx) + res, err := req.Do(context.Background(), esClient) if err != nil { - logs.Error("[elasticsearch] Index a prometheusalert alert to es error: %s", err) - } else { - logs.Info("[elasticsearch] Index a prometheusalert alert id: %s to index: %s succesful.", res.Id, res.Index) + logs.Critical("[elasticsearch] Error getting response: %s", err) + return } + if res != nil { + defer res.Body.Close() + if res.IsError() { + logs.Error("[elasticsearch] Error indexing alert document: %s", err) + return + } + } + + logs.Info("[elasticsearch] alert document indexed successfully in index %s", index) } From 38263ed7b55df40e96594ae20731ccf0105cbcae Mon Sep 17 00:00:00 2001 From: zhang21 Date: Fri, 7 Jun 2024 17:45:54 +0800 Subject: [PATCH 13/19] fix: es 8.x date format --- models/elastic/elasticsearch.go | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/models/elastic/elasticsearch.go b/models/elastic/elasticsearch.go index f2168f34..611221cf 100644 --- a/models/elastic/elasticsearch.go +++ b/models/elastic/elasticsearch.go @@ -13,11 +13,13 @@ import ( ) var ( - r map[string]interface{} - esClient *elasticsearch.Client + r map[string]interface{} + esClient *elasticsearch.Client + PCstTime, _ = beego.AppConfig.Int("prometheus_cst_time") ) // AlertES is a alert structure used for serializing data in ES. +// 将 created 定义为 es 默认的 @timestamp 时间戳字段 type AlertES struct { Alertname string `json:"alertname"` Status string `json:"status"` @@ -28,7 +30,7 @@ type AlertES struct { Description string `json:"description"` StartsAt string `json:"startsAt"` EndsAt string `json:"endsAt"` - Created time.Time `json:"created"` + Created time.Time `json:"@timestamp"` Cloud string `json:"cloud"` Hostgroup string `json:"hostgroup"` Hostnmae string `json:"hostname"` @@ -75,6 +77,13 @@ func init() { } func Insert(index string, alert AlertES) { + // GetCSTtime 将日期格式从 "2024-06-06T11:00:00Z" 转成了 "2024-06-06 11:00:00" + // 插入 es 时默认把 starsat 和 endsat 识别为 date,导致格式不匹配的错误。 + if PCstTime == 1 { + alert.StartsAt = timeConvert(alert.StartsAt) + alert.EndsAt = timeConvert(alert.EndsAt) + } + doc, err := json.Marshal(alert) if err != nil { logs.Error("[elasticsearch] error marshaling document: %w", err) @@ -95,10 +104,23 @@ func Insert(index string, alert AlertES) { if res != nil { defer res.Body.Close() if res.IsError() { - logs.Error("[elasticsearch] Error indexing alert document: %s", err) + logs.Error("[elasticsearch] Error indexing alert document: %s", res.String()) return } } logs.Info("[elasticsearch] alert document indexed successfully in index %s", index) } + +func timeConvert(csttime string) string { + loc, _ := time.LoadLocation("Asia/Shanghai") + t, err := time.ParseInLocation("2006-01-02 15:04:05", csttime, loc) + if err != nil { + return "" + } + + _, offset := t.Zone() + utcTime := t.Add(time.Duration(-offset) * time.Second) + + return utcTime.Format("2006-01-02T15:04:05Z") +} From 0937e84282aba6941d752581ea2b4af197b56290 Mon Sep 17 00:00:00 2001 From: JustDoIt Date: Sun, 9 Jun 2024 17:18:10 +0800 Subject: [PATCH 14/19] Update telegram.go Make Telegram support markdown --- controllers/telegram.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/controllers/telegram.go b/controllers/telegram.go index f47d7ce8..4516e125 100644 --- a/controllers/telegram.go +++ b/controllers/telegram.go @@ -27,10 +27,12 @@ func SendTG(msg, logsign string) string { if tgmsgmode == "0" { // 推送给个人 tgusermsg := tgbotapi.NewMessage(tguserid, msg) + tgusermsg.ParseMode = "Markdown" // 设置解析模式为Markdown _, err = botapi.Send(tgusermsg) } else { // 推送给channel tgchanmsg := tgbotapi.NewMessageToChannel(tgchanname, msg) + tgchanmsg.ParseMode = "Markdown" // 设置解析模式为Markdown _, err = botapi.Send(tgchanmsg) } if err != nil { From cbeac61b04f09996e13b7eeb2ed4e157d9174200 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=81=AA=E6=98=8E=E5=A4=A7=E7=94=B7=E5=AD=A9?= Date: Tue, 11 Jun 2024 15:16:57 +0800 Subject: [PATCH 15/19] Update app-example.conf Change the image path --- conf/app-example.conf | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/conf/app-example.conf b/conf/app-example.conf index a7265ef5..2fa89f5e 100644 --- a/conf/app-example.conf +++ b/conf/app-example.conf @@ -18,9 +18,9 @@ title=PrometheusAlert #链接到告警平台地址 GraylogAlerturl=http://graylog.org #钉钉告警 告警logo图标地址 -logourl=https://raw.githubusercontent.com/feiyu563/PrometheusAlert/master/doc/alert-center.png +logourl=https://raw.githubusercontent.com/feiyu563/PrometheusAlert/master/doc/images/alert-center.png #钉钉告警 恢复logo图标地址 -rlogourl=https://raw.githubusercontent.com/feiyu563/PrometheusAlert/master/doc/alert-center.png +rlogourl=https://raw.githubusercontent.com/feiyu563/PrometheusAlert/master/doc/images/alert-center.png #短信告警级别(等于3就进行短信告警) 告警级别定义 0 信息,1 警告,2 一般严重,3 严重,4 灾难 messagelevel=3 #电话告警级别(等于4就进行语音告警) 告警级别定义 0 信息,1 警告,2 一般严重,3 严重,4 灾难 From e28b3bb5ad414b27aa55420a308747437aaaced5 Mon Sep 17 00:00:00 2001 From: "jikun.zhang" Date: Wed, 19 Jun 2024 19:44:06 +0800 Subject: [PATCH 16/19] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E8=BD=AC=E5=8F=91=E8=87=B3kafka=E6=B8=A0=E9=81=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: jikun.zhang --- README.MD | 9 +- conf/app-example.conf | 9 + controllers/kafka.go | 54 ++ controllers/prometheusalert.go | 3 + db/PrometheusAlertDB.db | Bin 61440 -> 61440 bytes doc/readme/base-install.md | 8 +- doc/readme/conf-kafka.md | 37 ++ doc/readme/conf.md | 34 +- example/helm/prometheusalert/config/app.conf | 268 --------- example/helm/prometheusalert/values.yaml | 2 +- .../PrometheusAlert-Deployment.yaml | 36 +- go.mod | 64 ++- go.sum | 514 +++++------------- views/alertrouter.html | 1 + views/template.html | 1 + views/template_add.html | 11 + views/template_edit.html | 9 + views/test.html | 12 +- 18 files changed, 395 insertions(+), 677 deletions(-) create mode 100644 controllers/kafka.go create mode 100644 doc/readme/conf-kafka.md delete mode 100644 example/helm/prometheusalert/config/app.conf diff --git a/README.MD b/README.MD index 09fe5abe..4f821bac 100644 --- a/README.MD +++ b/README.MD @@ -18,7 +18,7 @@ --------------------------------------- -PrometheusAlert是开源的运维告警中心消息转发系统,支持主流的监控系统Prometheus、Zabbix,日志系统Graylog2,Graylog3、数据可视化系统Grafana、SonarQube。阿里云-云监控,以及所有支持WebHook接口的系统发出的预警消息,支持将收到的这些消息发送到钉钉,微信,email,飞书,腾讯短信,腾讯电话,阿里云短信,阿里云电话,华为短信,百度云短信,容联云电话,七陌短信,七陌语音,TeleGram,百度Hi(如流)等。 +PrometheusAlert是开源的运维告警中心消息转发系统,支持主流的监控系统Prometheus、Zabbix,日志系统Graylog2,Graylog3、数据可视化系统Grafana、SonarQube。阿里云-云监控,以及所有支持WebHook接口的系统发出的预警消息,支持将收到的这些消息发送到钉钉,微信,email,飞书,腾讯短信,腾讯电话,阿里云短信,阿里云电话,华为短信,百度云短信,容联云电话,七陌短信,七陌语音,TeleGram,百度Hi(如流),Kafka等。 ![it](doc/images/it.png) @@ -67,9 +67,9 @@ curl http://localhost:8080/health ```sh #打开PrometheusAlert releases页面,根据需要选择需要的版本下载到本地解压并进入解压后的目录 -如linux版本(https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9/linux.zip) +如linux版本(https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9.1/linux.zip) -# wget https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9/linux.zip && unzip linux.zip &&cd linux/ +# wget https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9.1/linux.zip && unzip linux.zip &&cd linux/ #运行PrometheusAlert # ./PrometheusAlert (#后台运行请执行 nohup ./PrometheusAlert &) @@ -101,7 +101,7 @@ docker run -d \ -e PA_OPEN_FEISHU=1 \ -e PA_OPEN_DINGDING=1 \ -e PA_OPEN_WEIXIN=1 \ -feiyu563/prometheus-alert:latest +feiyu563/prometheus-alert:v4.9.1 ``` 所有的配置文件内容请[点击此处](https://github.com/feiyu563/PrometheusAlert/blob/master/conf/app-example.conf)查看 @@ -198,6 +198,7 @@ feiyu563/prometheus-alert:latest * [告警记录-ES接入配置](doc/readme/conf-es.md) * [语音播报](doc/readme/conf-voice.md) * [飞书机器人应用](doc/readme/conf-feishuapp.md) + * [告警消息转发至Kafka配置](doc/readme/conf-kafka.md) * [告警组配置](doc/readme/alertgroup.md) * [热加载配置](doc/readme/hotreload.md) diff --git a/conf/app-example.conf b/conf/app-example.conf index a7265ef5..2fe3b2c7 100644 --- a/conf/app-example.conf +++ b/conf/app-example.conf @@ -289,3 +289,12 @@ open-alertgroup=0 # 自定义的告警组既可以写在这里,也可以写在单独的文件里。 # 写在单独的告警组配置里更便于修改。 # include "alertgroup.conf" + +#---------------------↓kafka地址----------------------- +# kafka服务器的地址 +open-kafka=1 +kafka_server = 127.0.0.1:9092 +# 写入消息的kafka topic +kafka_topic = devops +# 用户标记该消息是来自PrometheusAlert,一般无需修改 +kafka_key = PrometheusAlert \ No newline at end of file diff --git a/controllers/kafka.go b/controllers/kafka.go new file mode 100644 index 00000000..6809acd6 --- /dev/null +++ b/controllers/kafka.go @@ -0,0 +1,54 @@ +package controllers + +import ( + "github.com/IBM/sarama" + "github.com/astaxie/beego" + "time" +) + +func GetKafkaProducer() sarama.SyncProducer { + kafka_server := beego.AppConfig.Strings("kafka_server") + config := sarama.NewConfig() + config.Producer.RequiredAcks = sarama.WaitForAll // 等待所有follower都回复ack,确保Kafka不会丢消息 + config.Producer.Return.Successes = true + config.Producer.Partitioner = sarama.NewHashPartitioner + + // 对Key进行Hash,同样的Key每次都落到一个分区,这样消息是有序的 + producer, err := sarama.NewSyncProducer(kafka_server, config) + + if err != nil { + panic(err.Error()) + } + + return producer +} + +func SendKafka(message, logsign string) string { + //发送kafka + open := beego.AppConfig.String("open-kafka") + if open != "1" { + beego.Info(logsign, "[kafka]", "kafka未配置未开启状态,请先配置open-kafka为1") + return "kafka未配置未开启状态,请先配置open-kafka为1" + } + t1 := time.Now().UnixMilli() + producer := GetKafkaProducer() + kafka_topic := beego.AppConfig.String("kafka_topic") + Key_string := beego.AppConfig.String("kafka_key") + "-" + logsign + msg := &sarama.ProducerMessage{ + Topic: kafka_topic, + Value: sarama.StringEncoder(message), + Key: sarama.StringEncoder(Key_string), + } + + partition, offset, err := producer.SendMessage(msg) + defer producer.Close() + t2 := time.Now().UnixMilli() + if err == nil { + beego.Debug("发送kafka消息:", Key_string, "成功, partition:", partition, ",offset:", offset, ",cost:", t2-t1, " ms") + return "发送kafka消息:" + Key_string + "成功" + } else { + beego.Error(err) + return err.Error() + } + +} diff --git a/controllers/prometheusalert.go b/controllers/prometheusalert.go index a4b30994..1f6a6dd4 100644 --- a/controllers/prometheusalert.go +++ b/controllers/prometheusalert.go @@ -527,6 +527,9 @@ func SendMessagePrometheusAlert(message string, pmsg *PrometheusAlertMsg, logsig //飞书APP渠道 case "fsapp": ReturnMsg += PostToFeiShuApp(Title, message, pmsg.AtSomeOne, logsign) + //kafka渠道 + case "kafka": + ReturnMsg += SendKafka(message, logsign) //异常参数 default: ReturnMsg = "参数错误" diff --git a/db/PrometheusAlertDB.db b/db/PrometheusAlertDB.db index e48ca36eaf74f51b4fbdafda3d2ac78b794dcd3b..8ac76575914b1555a888720e59c0be4a90f0663a 100644 GIT binary patch delta 654 zcmZp8z})bFd4e?Kg^4oGj2AX0B{fd%9A&2|Riypkf! zx{L)y`MIej8L6eky4i_o*@=dd%;t=fKemW&K5A?4#K+32#lVxw<;n4jwSrY^W8+>% z1?JTZ;)=Sx+Wrs?3=GV(AOgO;U=t=UEE8n~vo=rYkzy7D+8YYg;A6-EQYMb1N(-#2 zx>~Qc*2uufMAyJf*U(bI(9p`**vi;M&(gxc(%4Mfz`)ADU~@%l4;K#$hZF0(QqQ(1j!(|dD@n}EOD&2|EK4m)OiztZ zE+~yJEy>KutV%4&%+HI@$V|^LMz+?-%Gkonz#Lh~*vh~ZDD-sQ&Zje1Jl(nZ>D+eb zfY2v<_dlPq;(1^Di*5C-FZQ>;oH^lX$F}FQS}aXfbrha%-}J1f@%iqxh6YbN+FnkY z4;0!v`DthG(}q1(3YM077OGs%FxOcrl%y7y=w{}n>F4C9>lS3@mRI*ZnyKVBl hDGCZe*8=4W@>7syAg)%bZQ&A}{Ck4*=8rS^!vNez+{*v} delta 132 zcmV-~0DJ#{-~)i*1CSd5$dMdF0m!jnVJ`s@lfo}O2rvo&001Ektdj>YII}@8Rt=Gm z7qhHASV9a01$Y1qWeQ0M`UQBgfyo381S0?!AvcdTO=fdpaB!2Mb`_JIg?zJkg^UUe m0}0ar4ebly3DXB;vk;I92(ucvxd8)&3K5h0kQ=k{nGaS2l`Mw< diff --git a/doc/readme/base-install.md b/doc/readme/base-install.md index 555cbe4d..2c665436 100644 --- a/doc/readme/base-install.md +++ b/doc/readme/base-install.md @@ -14,7 +14,7 @@ mkdir /etc/prometheusalert-center/ wget https://raw.githubusercontent.com/feiyu563/PrometheusAlert/master/conf/app-example.conf -O /etc/prometheusalert-center/app.conf #启动PrometheusAlert并挂载配置文件 -docker run -d -p 8080:8080 -v /etc/prometheusalert-center:/app/conf --name prometheusalert-center feiyu563/prometheus-alert:latest +docker run -d -p 8080:8080 -v /etc/prometheusalert-center:/app/conf --name prometheusalert-center feiyu563/prometheus-alert:v4.9.1 #启动后可使用浏览器打开以下地址查看:http://127.0.0.1:8080 #默认登录帐号和密码在app.conf中有配置 @@ -24,9 +24,9 @@ docker run -d -p 8080:8080 -v /etc/prometheusalert-center:/app/conf --name prome ``` #打开PrometheusAlert releases页面,根据需要选择需要的版本下载到本地解压并进入解压后的目录 -如linux版本(https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9/linux.zip) +如linux版本(https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9.1/linux.zip) -# wget https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9/linux.zip && unzip linux.zip && cd linux/ +# wget https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9.1/linux.zip && unzip linux.zip && cd linux/ #,下载好后解压并进入解压后的文件夹 @@ -42,7 +42,7 @@ docker run -d -p 8080:8080 -v /etc/prometheusalert-center:/app/conf --name prome ``` #打开PrometheusAlert releases页面,根据需要选择需要的版本下载到本地解压并进入解压后的目录 -如windows版本(https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9/windows.zip) +如windows版本(https://github.com/feiyu563/PrometheusAlert/releases/download/v4.9.1/windows.zip) #进入程序目录并双击运行 PrometheusAlert.exe即可 cd windows/ diff --git a/doc/readme/conf-kafka.md b/doc/readme/conf-kafka.md new file mode 100644 index 00000000..3b9de8d6 --- /dev/null +++ b/doc/readme/conf-kafka.md @@ -0,0 +1,37 @@ +# PrometheusAlert全家桶Kafka配置说明 + +----------------- + +PrometheusAlert支持将收到的json消息通过模板渲染后转发给Kafka集群,使用前需要在配置文件app.conf中配置好Kafka服务的连接信息 + +``` +#---------------------↓kafka地址----------------------- +# kafka服务器的地址 +open-kafka=1 +kafka_server = 127.0.0.1:9092 +# 写入消息的kafka topic +kafka_topic = devops +# 用户标记该消息是来自PrometheusAlert,一般无需修改 +kafka_key = PrometheusAlert +``` + +**如何使用** + +以Prometheus配合自定义模板为例: + +Prometheus配置参考: + +``` +global: + resolve_timeout: 5m +route: + group_by: ['instance'] + group_wait: 10m + group_interval: 10s + repeat_interval: 10m + receiver: 'web.hook.prometheusalert' +receivers: +- name: 'web.hook.prometheusalert' + webhook_configs: + - url: 'http://[prometheusalert_url]:8080/prometheusalert?type=kafka&tpl=prometheus-kafka' +``` \ No newline at end of file diff --git a/doc/readme/conf.md b/doc/readme/conf.md index 11af2e0d..b11d3d9d 100644 --- a/doc/readme/conf.md +++ b/doc/readme/conf.md @@ -68,6 +68,10 @@ to_es_url=http://localhost:9200 # es用户和密码 # to_es_user=username # to_es_pwd=password +# 长连接最大空闲数 +maxIdleConns=100 +# 热更新配置文件 +open-hotreload=0 #---------------------↓webhook----------------------- #是否开启钉钉告警通道,可同时开始多个通道0为关闭,1为开启 @@ -76,6 +80,9 @@ open-dingding=1 ddurl=https://oapi.dingtalk.com/robot/send?access_token=xxxxx #是否开启 @所有人(0为关闭,1为开启) dd_isatall=1 +#是否开启钉钉机器人加签,0为关闭,1为开启 +# 使用方法:https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&secret=mysecret +open-dingding-secret=0 #是否开启微信告警通道,可同时开始多个通道0为关闭,1为开启 open-weixin=1 @@ -83,9 +90,11 @@ open-weixin=1 wxurl=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxx #是否开启飞书告警通道,可同时开始多个通道0为关闭,1为开启 -open-feishu=0 +open-feishu=1 #默认飞书机器人地址 fsurl=https://open.feishu.cn/open-apis/bot/hook/xxxxxxxxx +# webhook 发送 http 请求的 contentType, 如 application/json, application/x-www-form-urlencoded,不配置默认 application/json +wh_contenttype=application/json #---------------------↓腾讯云接口----------------------- #是否开启腾讯云短信告警通道,可同时开始多个通道0为关闭,1为开启 @@ -277,4 +286,27 @@ FEISHU_APPID=cli_xxxxxxxxxxxxx FEISHU_APPSECRET=xxxxxxxxxxxxxxxxxxxxxx # 可填飞书 用户open_id、user_id、union_ids、部门open_department_id AT_USER_ID="xxxxxxxx" + + +#---------------------↓告警组----------------------- +# 有其他新增的配置段,请放在告警组的上面 +# 暂时仅针对 PrometheusContronller 中的 /prometheus/alert 路由 +# 告警组如果放在了 wx, dd... 那部分的上分,beego section 取 url 值不太对。 +# 所以这里使用 include 来包含另告警组配置 + +# 是否启用告警组功能 +open-alertgroup=0 + +# 自定义的告警组既可以写在这里,也可以写在单独的文件里。 +# 写在单独的告警组配置里更便于修改。 +# include "alertgroup.conf" + +#---------------------↓kafka地址----------------------- +# kafka服务器的地址 +open-kafka=1 +kafka_server = 127.0.0.1:9092 +# 写入消息的kafka topic +kafka_topic = devops +# 用户标记该消息是来自PrometheusAlert,一般无需修改 +kafka_key = PrometheusAlert ``` diff --git a/example/helm/prometheusalert/config/app.conf b/example/helm/prometheusalert/config/app.conf deleted file mode 100644 index 68f3c212..00000000 --- a/example/helm/prometheusalert/config/app.conf +++ /dev/null @@ -1,268 +0,0 @@ -#---------------------↓全局配置----------------------- -appname = PrometheusAlert -#登录用户名 -login_user=prometheusalert -#登录密码 -login_password=prometheusalert -#监听地址 -httpaddr = "0.0.0.0" -#监听端口 -httpport = 8080 -runmode = dev -#设置代理 proxy = http://123.123.123.123:8080 -proxy = -#开启JSON请求 -copyrequestbody = true -#告警消息标题 -title=PrometheusAlert -#链接到告警平台地址 -GraylogAlerturl=http://graylog.org -#钉钉告警 告警logo图标地址 -logourl=https://raw.githubusercontent.com/feiyu563/PrometheusAlert/master/doc/alert-center.png -#钉钉告警 恢复logo图标地址 -rlogourl=https://raw.githubusercontent.com/feiyu563/PrometheusAlert/master/doc/alert-center.png -#短信告警级别(等于3就进行短信告警) 告警级别定义 0 信息,1 警告,2 一般严重,3 严重,4 灾难 -messagelevel=3 -#电话告警级别(等于4就进行语音告警) 告警级别定义 0 信息,1 警告,2 一般严重,3 严重,4 灾难 -phonecalllevel=4 -#默认拨打号码(页面测试短信和电话功能需要配置此项) -defaultphone=xxxxxxxx -#故障恢复是否启用电话通知0为关闭,1为开启 -phonecallresolved=0 -#是否前台输出file or console -logtype=file -#日志文件路径 -logpath=logs/prometheusalertcenter.log -#转换Prometheus,graylog告警消息的时区为CST时区(如默认已经是CST时区,请勿开启) -prometheus_cst_time=0 -#数据库驱动,支持sqlite3,mysql,postgres如使用mysql或postgres,请开启db_host,db_port,db_user,db_password,db_name的注释 -db_driver=sqlite3 -#db_host=127.0.0.1 -#db_port=3306 -#db_user=root -#db_password=root -#db_name=prometheusalert -#是否开启告警记录 0为关闭,1为开启 -AlertRecord=0 -#是否开启告警记录定时删除 0为关闭,1为开启 -RecordLive=0 -#告警记录定时删除周期,单位天 -RecordLiveDay=7 -# 是否将告警记录写入es7,0为关闭,1为开启 -alert_to_es=0 -# es地址,是[]string -# beego.Appconfig.Strings读取配置为[]string,使用";"而不是"," -to_es_url=http://localhost:9200 -# to_es_url=http://es1:9200;http://es2:9200;http://es3:9200 -# es用户和密码 -# to_es_user=username -# to_es_pwd=password - -#---------------------↓webhook----------------------- -#是否开启钉钉告警通道,可同时开始多个通道0为关闭,1为开启 -open-dingding=1 -#默认钉钉机器人地址 -ddurl=https://oapi.dingtalk.com/robot/send?access_token=xxxxx -#是否开启 @所有人(0为关闭,1为开启) -dd_isatall=1 - -#是否开启微信告警通道,可同时开始多个通道0为关闭,1为开启 -open-weixin=1 -#默认企业微信机器人地址 -wxurl=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxx - -#是否开启飞书告警通道,可同时开始多个通道0为关闭,1为开启 -open-feishu=0 -#默认飞书机器人地址 -fsurl=https://open.feishu.cn/open-apis/bot/hook/xxxxxxxxx - -#---------------------↓腾讯云接口----------------------- -#是否开启腾讯云短信告警通道,可同时开始多个通道0为关闭,1为开启 -open-txdx=0 -#腾讯云短信接口key -TXY_DX_appkey=xxxxx -#腾讯云短信模版ID 腾讯云短信模版配置可参考 prometheus告警:{1} -TXY_DX_tpl_id=xxxxx -#腾讯云短信sdk app id -TXY_DX_sdkappid=xxxxx -#腾讯云短信签名 根据自己审核通过的签名来填写 -TXY_DX_sign=腾讯云 - -#是否开启腾讯云电话告警通道,可同时开始多个通道0为关闭,1为开启 -open-txdh=0 -#腾讯云电话接口key -TXY_DH_phonecallappkey=xxxxx -#腾讯云电话模版ID -TXY_DH_phonecalltpl_id=xxxxx -#腾讯云电话sdk app id -TXY_DH_phonecallsdkappid=xxxxx - -#---------------------↓华为云接口----------------------- -#是否开启华为云短信告警通道,可同时开始多个通道0为关闭,1为开启 -open-hwdx=0 -#华为云短信接口key -HWY_DX_APP_Key=xxxxxxxxxxxxxxxxxxxxxx -#华为云短信接口Secret -HWY_DX_APP_Secret=xxxxxxxxxxxxxxxxxxxxxx -#华为云APP接入地址(端口接口地址) -HWY_DX_APP_Url=https://rtcsms.cn-north-1.myhuaweicloud.com:10743 -#华为云短信模板ID -HWY_DX_Templateid=xxxxxxxxxxxxxxxxxxxxxx -#华为云签名名称,必须是已审核通过的,与模板类型一致的签名名称,按照自己的实际签名填写 -HWY_DX_Signature=华为云 -#华为云签名通道号 -HWY_DX_Sender=xxxxxxxxxx - -#---------------------↓阿里云接口----------------------- -#是否开启阿里云短信告警通道,可同时开始多个通道0为关闭,1为开启 -open-alydx=0 -#阿里云短信主账号AccessKey的ID -ALY_DX_AccessKeyId=xxxxxxxxxxxxxxxxxxxxxx -#阿里云短信接口密钥 -ALY_DX_AccessSecret=xxxxxxxxxxxxxxxxxxxxxx -#阿里云短信签名名称 -ALY_DX_SignName=阿里云 -#阿里云短信模板ID -ALY_DX_Template=xxxxxxxxxxxxxxxxxxxxxx - -#是否开启阿里云电话告警通道,可同时开始多个通道0为关闭,1为开启 -open-alydh=0 -#阿里云电话主账号AccessKey的ID -ALY_DH_AccessKeyId=xxxxxxxxxxxxxxxxxxxxxx -#阿里云电话接口密钥 -ALY_DH_AccessSecret=xxxxxxxxxxxxxxxxxxxxxx -#阿里云电话被叫显号,必须是已购买的号码 -ALY_DX_CalledShowNumber=xxxxxxxxx -#阿里云电话文本转语音(TTS)模板ID -ALY_DH_TtsCode=xxxxxxxx - -#---------------------↓容联云接口----------------------- -#是否开启容联云电话告警通道,可同时开始多个通道0为关闭,1为开启 -open-rlydh=0 -#容联云基础接口地址 -RLY_URL=https://app.cloopen.com:8883/2013-12-26/Accounts/ -#容联云后台SID -RLY_ACCOUNT_SID=xxxxxxxxxxx -#容联云api-token -RLY_ACCOUNT_TOKEN=xxxxxxxxxx -#容联云app_id -RLY_APP_ID=xxxxxxxxxxxxx - -#---------------------↓邮件配置----------------------- -#是否开启邮件 -open-email=0 -#邮件发件服务器地址 -Email_host=smtp.qq.com -#邮件发件服务器端口 -Email_port=465 -#邮件帐号 -Email_user=xxxxxxx@qq.com -#邮件密码 -Email_password=xxxxxx -#邮件标题 -Email_title=运维告警 -#默认发送邮箱 -Default_emails=xxxxx@qq.com,xxxxx@qq.com - -#---------------------↓七陌云接口----------------------- -#是否开启七陌短信告警通道,可同时开始多个通道0为关闭,1为开启 -open-7moordx=0 -#七陌账户ID -7MOOR_ACCOUNT_ID=Nxxx -#七陌账户APISecret -7MOOR_ACCOUNT_APISECRET=xxx -#七陌账户短信模板编号 -7MOOR_DX_TEMPLATENUM=n -#注意:七陌短信变量这里只用一个var1,在代码里写死了。 -#----------- -#是否开启七陌webcall语音通知告警通道,可同时开始多个通道0为关闭,1为开启 -open-7moordh=0 -#请在七陌平台添加虚拟服务号、文本节点 -#七陌账户webcall的虚拟服务号 -7MOOR_WEBCALL_SERVICENO=xxx -# 文本节点里被替换的变量,我配置的是text。如果被替换的变量不是text,请修改此配置 -7MOOR_WEBCALL_VOICE_VAR=text - -#---------------------↓telegram接口----------------------- -#是否开启telegram告警通道,可同时开始多个通道0为关闭,1为开启 -open-tg=0 -#tg机器人token -TG_TOKEN=xxxxx -#tg消息模式 个人消息或者频道消息 0为关闭(推送给个人),1为开启(推送给频道) -TG_MODE_CHAN=0 -#tg用户ID -TG_USERID=xxxxx -#tg频道name或者id, 频道name需要以@开始 -TG_CHANNAME=xxxxx -#tg api地址, 可以配置为代理地址 -#TG_API_PROXY="https://api.telegram.org/bot%s/%s" - -#---------------------↓workwechat接口----------------------- -#是否开启workwechat告警通道,可同时开始多个通道0为关闭,1为开启 -open-workwechat=0 -# 企业ID -WorkWechat_CropID=xxxxx -# 应用ID -WorkWechat_AgentID=xxxx -# 应用secret -WorkWechat_AgentSecret=xxxx -# 接受用户 -WorkWechat_ToUser="zhangsan|lisi" -# 接受部门 -WorkWechat_ToParty="ops|dev" -# 接受标签 -WorkWechat_ToTag="" -# 消息类型, 暂时只支持markdown -# WorkWechat_Msgtype = "markdown" - -#---------------------↓百度云接口----------------------- -#是否开启百度云短信告警通道,可同时开始多个通道0为关闭,1为开启 -open-baidudx=0 -#百度云短信接口AK(ACCESS_KEY_ID) -BDY_DX_AK=xxxxx -#百度云短信接口SK(SECRET_ACCESS_KEY) -BDY_DX_SK=xxxxx -#百度云短信ENDPOINT(ENDPOINT参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为) -BDY_DX_ENDPOINT=http://smsv3.bj.baidubce.com -#百度云短信模版ID,根据自己审核通过的模版来填写(模版支持一个参数code:如prometheus告警:{code}) -BDY_DX_TEMPLATE_ID=xxxxx -#百度云短信签名ID,根据自己审核通过的签名来填写 -TXY_DX_SIGNATURE_ID=xxxxx - -#---------------------↓百度Hi(如流)----------------------- -#是否开启百度Hi(如流)告警通道,可同时开始多个通道0为关闭,1为开启 -open-ruliu=0 -#默认百度Hi(如流)机器人地址 -BDRL_URL=https://api.im.baidu.com/api/msg/groupmsgsend?access_token=xxxxxxxxxxxxxx -#百度Hi(如流)群ID -BDRL_ID=123456 -#---------------------↓bark接口----------------------- -#是否开启telegram告警通道,可同时开始多个通道0为关闭,1为开启 -open-bark=0 -#bark默认地址, 建议自行部署bark-server -BARK_URL=https://api.day.app -#bark key, 多个key使用分割 -BARK_KEYS=xxxxx -# 复制, 推荐开启 -BARK_COPY=1 -# 历史记录保存,推荐开启 -BARK_ARCHIVE=1 -# 消息分组 -BARK_GROUP=PrometheusAlert - -#---------------------↓语音播报----------------------- -#语音播报需要配合语音播报插件才能使用 -#是否开启语音播报通道,0为关闭,1为开启 -open-voice=1 -VOICE_IP=127.0.0.1 -VOICE_PORT=9999 - -#---------------------↓飞书机器人应用----------------------- -#是否开启feishuapp告警通道,可同时开始多个通道0为关闭,1为开启 -open-feishuapp=1 -# APPID -FEISHU_APPID=cli_xxxxxxxxxxxxx -# APPSECRET -FEISHU_APPSECRET=xxxxxxxxxxxxxxxxxxxxxx -# 可填飞书 用户open_id、user_id、union_ids、部门open_department_id -AT_USER_ID="xxxxxxxx" \ No newline at end of file diff --git a/example/helm/prometheusalert/values.yaml b/example/helm/prometheusalert/values.yaml index 8dcbcf07..d5a58fbe 100644 --- a/example/helm/prometheusalert/values.yaml +++ b/example/helm/prometheusalert/values.yaml @@ -10,7 +10,7 @@ replicaCount: 1 image: # 支持配置自定义模版需要重出镜像,或者使用本人构建镜像:lusson/prometheusalert:v1.0 - repository: feiyu563/prometheus-alert:v4.8 + repository: feiyu563/prometheus-alert:v4.9.1 pullPolicy: IfNotPresent nameOverride: "" diff --git a/example/kubernetes/PrometheusAlert-Deployment.yaml b/example/kubernetes/PrometheusAlert-Deployment.yaml index cd2e4988..64fd84bd 100644 --- a/example/kubernetes/PrometheusAlert-Deployment.yaml +++ b/example/kubernetes/PrometheusAlert-Deployment.yaml @@ -65,6 +65,10 @@ data: # es用户和密码 # to_es_user=username # to_es_pwd=password + # 长连接最大空闲数 + maxIdleConns=100 + # 热更新配置文件 + open-hotreload=0 #---------------------↓webhook----------------------- #是否开启钉钉告警通道,可同时开始多个通道0为关闭,1为开启 @@ -73,6 +77,9 @@ data: ddurl=https://oapi.dingtalk.com/robot/send?access_token=xxxxx #是否开启 @所有人(0为关闭,1为开启) dd_isatall=1 + #是否开启钉钉机器人加签,0为关闭,1为开启 + # 使用方法:https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&secret=mysecret + open-dingding-secret=0 #是否开启微信告警通道,可同时开始多个通道0为关闭,1为开启 open-weixin=1 @@ -80,9 +87,11 @@ data: wxurl=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxx #是否开启飞书告警通道,可同时开始多个通道0为关闭,1为开启 - open-feishu=0 + open-feishu=1 #默认飞书机器人地址 fsurl=https://open.feishu.cn/open-apis/bot/hook/xxxxxxxxx + # webhook 发送 http 请求的 contentType, 如 application/json, application/x-www-form-urlencoded,不配置默认 application/json + wh_contenttype=application/json #---------------------↓腾讯云接口----------------------- #是否开启腾讯云短信告警通道,可同时开始多个通道0为关闭,1为开启 @@ -274,6 +283,29 @@ data: FEISHU_APPSECRET=xxxxxxxxxxxxxxxxxxxxxx # 可填飞书 用户open_id、user_id、union_ids、部门open_department_id AT_USER_ID="xxxxxxxx" + + + #---------------------↓告警组----------------------- + # 有其他新增的配置段,请放在告警组的上面 + # 暂时仅针对 PrometheusContronller 中的 /prometheus/alert 路由 + # 告警组如果放在了 wx, dd... 那部分的上分,beego section 取 url 值不太对。 + # 所以这里使用 include 来包含另告警组配置 + + # 是否启用告警组功能 + open-alertgroup=0 + + # 自定义的告警组既可以写在这里,也可以写在单独的文件里。 + # 写在单独的告警组配置里更便于修改。 + # include "alertgroup.conf" + + #---------------------↓kafka地址----------------------- + # kafka服务器的地址 + open-kafka=1 + kafka_server = 127.0.0.1:9092 + # 写入消息的kafka topic + kafka_topic = devops + # 用户标记该消息是来自PrometheusAlert,一般无需修改 + kafka_key = PrometheusAlert user.csv: | 2019年4月10日,15888888881,小张,15999999999,备用联系人小陈,15999999998,备用联系人小赵 2019年4月11日,15888888882,小李,15999999999,备用联系人小陈,15999999998,备用联系人小赵 @@ -305,7 +337,7 @@ spec: alertname: prometheus-alert-center spec: containers: - - image: feiyu563/prometheus-alert + - image: feiyu563/prometheus-alert:v4.9.1 name: prometheus-alert-center env: - name: TZ diff --git a/go.mod b/go.mod index 18b7a885..d66f7c10 100644 --- a/go.mod +++ b/go.mod @@ -1,22 +1,70 @@ module PrometheusAlert -go 1.16 +go 1.20 require ( - github.com/aliyun/alibaba-cloud-sdk-go v1.61.1537 + github.com/IBM/sarama v1.43.2 + github.com/aliyun/alibaba-cloud-sdk-go v1.62.771 github.com/astaxie/beego v1.12.3 - github.com/baidubce/bce-sdk-go v0.9.111 + github.com/baidubce/bce-sdk-go v0.9.183 github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df - github.com/go-sql-driver/mysql v1.6.0 + github.com/go-sql-driver/mysql v1.8.1 github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 - github.com/lib/pq v1.10.4 + github.com/lib/pq v1.10.9 github.com/mattn/go-sqlite3 v2.0.3+incompatible github.com/olivere/elastic/v7 v7.0.32 - github.com/prometheus/client_golang v1.12.1 + github.com/prometheus/client_golang v1.19.1 github.com/robfig/cron/v3 v3.0.1 - github.com/smartystreets/goconvey v1.7.2 - github.com/stretchr/testify v1.8.4 + github.com/smartystreets/goconvey v1.8.1 + github.com/stretchr/testify v1.9.0 github.com/ysicing/workwxbot v1.1.0 +) + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/eapache/go-resiliency v1.6.0 // indirect + github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect + github.com/eapache/queue v1.1.0 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/gopherjs/gopherjs v1.17.2 // indirect + github.com/hashicorp/errwrap v1.0.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/jcmturner/aescts/v2 v2.0.0 // indirect + github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect + github.com/jcmturner/gofork v1.7.6 // indirect + github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect + github.com/jcmturner/rpc/v2 v2.0.3 // indirect + github.com/jmespath/go-jmespath v0.4.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/jtolds/gls v4.20.0+incompatible // indirect + github.com/klauspost/compress v1.17.8 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b // indirect + github.com/pierrec/lz4/v4 v4.1.21 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_model v0.5.0 // indirect + github.com/prometheus/common v0.48.0 // indirect + github.com/prometheus/procfs v0.12.0 // indirect + github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect + github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect + github.com/smarty/assertions v1.15.0 // indirect + golang.org/x/crypto v0.22.0 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/sys v0.19.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/protobuf v1.33.0 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 7e6d211d..5eefe75e 100644 --- a/go.sum +++ b/go.sum @@ -1,53 +1,25 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= +github.com/IBM/sarama v1.43.2 h1:HABeEqRUh32z8yzY2hGB/j8mHSzC/HA9zlEjqFNCzSw= +github.com/IBM/sarama v1.43.2/go.mod h1:Kyo4WkF24Z+1nz7xeVUFWIuKVV8RS3wM8mkvPKMdXFQ= github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= -github.com/aliyun/alibaba-cloud-sdk-go v1.61.1537 h1:R6hnGHYn3jLXgv5lGi2vUvmTENdwuQVjakzZEiAfex4= -github.com/aliyun/alibaba-cloud-sdk-go v1.61.1537/go.mod h1:RcDobYh8k5VP6TNybz9m++gL3ijVI5wueVr0EM10VsU= +github.com/aliyun/alibaba-cloud-sdk-go v1.62.771 h1:/3CAW5lTlOLiB+4klPJg+ZXxp0M4r08iGNuwFB8e7Qs= +github.com/aliyun/alibaba-cloud-sdk-go v1.62.771/go.mod h1:SOSDHfe1kX91v3W5QiBsWSLqeLxImobbMX1mxrFHsVQ= github.com/astaxie/beego v1.12.3 h1:SAQkdD2ePye+v8Gn1r4X6IKZM1wd28EyUOVQ3PDSOOQ= github.com/astaxie/beego v1.12.3/go.mod h1:p3qIm0Ryx7zeBHLljmd7omloyca1s4yu1a8kM1FkpIA= -github.com/aws/aws-sdk-go v1.43.21/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= -github.com/baidubce/bce-sdk-go v0.9.111 h1:yGgtPpZYUZW4uoVorQ4xnuEgVeddACydlcJKW87MDV4= -github.com/baidubce/bce-sdk-go v0.9.111/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= +github.com/baidubce/bce-sdk-go v0.9.183 h1:7FORBGdPOkakL4OBgLskG4vrH7k1AE8OhRFK4+mbgis= +github.com/baidubce/bce-sdk-go v0.9.183/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= @@ -56,162 +28,127 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= -github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30= +github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws= +github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3/go.mod h1:YvSRo5mw33fLEx1+DlK6L2VV43tJt5Eyel9n9XBcR+0= +github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= -github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df h1:Bao6dhmbTA1KFVxmJ6nBoMuOJit2yjEgLJpIMYpop0E= github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df/go.mod h1:GJr+FCSXshIwgHBtLglIg9M2l2kQSi6QjVAngtzI08Y= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= -github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= -github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g= +github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= +github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= +github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= +github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= +github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= +github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= +github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= +github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= +github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8= +github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= +github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= +github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= -github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= +github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.10.4 h1:SO9z7FRPzA03QhHKJrH5BXA6HU1rS4V2nIVrrNC1iYk= -github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= -github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= @@ -221,18 +158,19 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/olivere/elastic/v7 v7.0.32 h1:R7CXvbu8Eq+WlsLgxmKVKPox0oOwAE/2T9Si5BnvK6E= github.com/olivere/elastic/v7 v7.0.32/go.mod h1:c7PVmLe3Fxq77PIfY/bZmxY/TAamBhCzZ8xDOE09a9k= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b h1:FfH+VrHHk6Lxt9HdVS0PXzSXFyS2NbZKXv33FYPol0A= +github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b/go.mod h1:AC62GU6hc0BrNm+9RK9VSiwa/EUe1bkIeFORAMcHvJU= github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= +github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -242,29 +180,27 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.12.1 h1:ZiaPsmm9uiBeaSMRznKsCDNtPCS0T3JVDGF+06gjBzk= -github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= +github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE= +github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= +github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= -github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= -github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= +github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE= +github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= -github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= +github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= @@ -272,14 +208,10 @@ github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKz github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -github.com/smartystreets/assertions v1.1.1/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= -github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM= -github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= -github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM= -github.com/smartystreets/gunit v1.4.2/go.mod h1:ZjM1ozSIMJlAz/ay4SG8PeKF00ckUp+zMHZXV9/bvak= +github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY= +github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec= +github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY= +github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -288,116 +220,64 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o= +github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= +github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg= +github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U= github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= github.com/ysicing/workwxbot v1.1.0 h1:FMWFN7GIjWL47epEc8DR/tKvURAi8p48pBjny+/0vFg= github.com/ysicing/workwxbot v1.1.0/go.mod h1:HVdUWKQW6w76dAtwGuERPCOn3bJ6/5MXkCXFAgpSBBY= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= -go.opentelemetry.io/otel v1.5.0/go.mod h1:Jm/m+rNp/z0eqJc74H7LPwQ3G87qkU/AnnAydAjSAHk= -go.opentelemetry.io/otel/trace v1.5.0/go.mod h1:sq55kfhjXYr1zVSyexg0w1mpa03AYXR5eyTkB9NPPdE= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -405,190 +285,58 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0= -golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= +gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= +gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= -gopkg.in/ini.v1 v1.66.2 h1:XfR1dOYubytKy4Shzc2LHrrGhU0lDCfDGG1yLPmpgsI= -gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -596,20 +344,10 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/views/alertrouter.html b/views/alertrouter.html index 72ce2ef4..481ea332 100644 --- a/views/alertrouter.html +++ b/views/alertrouter.html @@ -110,6 +110,7 @@

** 告警路由目前仅支持 Promethe {{if eq $v.Tpl.Tpltype "bark"}}Bark(iPhone推送){{end}} {{if eq $v.Tpl.Tpltype "voice"}}语音播报{{end}} {{if eq $v.Tpl.Tpltype "fsapp"}}飞书机器人应用{{end}} + {{if eq $v.Tpl.Tpltype "kafka"}}Kafka{{end}} {{$v.Tpl.Tpluse}} diff --git a/views/template.html b/views/template.html index cdbd59d0..45c6410c 100644 --- a/views/template.html +++ b/views/template.html @@ -101,6 +101,7 @@

{{if eq .Tpltype "bark"}}Bark(iPhone推送){{end}} {{if eq .Tpltype "voice"}}语音播报{{end}} {{if eq .Tpltype "fsapp"}}飞书机器人应用{{end}} + {{if eq .Tpltype "kafka"}}Kafka{{end}} {{if eq .Tpluse "ALiYun"}}阿里云-云监控{{else}}{{.Tpluse}}{{end}} diff --git a/views/template_add.html b/views/template_add.html index 84ddd6c9..f3ae6fe3 100644 --- a/views/template_add.html +++ b/views/template_add.html @@ -85,6 +85,7 @@

+ {{if eq .Template.Tpltype "webhook"}} @@ -269,6 +270,12 @@

document.getElementById("Pat").style.display="none"; document.getElementById("Party").style.display=""; document.getElementById("Tag").style.display=""; + } else if(typeSelect=="kafka"){ + typeStr.innerText="Kafka"; + document.getElementById("Purl").style.display="none"; + document.getElementById("Pat").style.display="none"; + document.getElementById("Party").style.display="none"; + document.getElementById("Tag").style.display="none"; } else{ typeStr.innerText="手机号"; document.getElementById("Purl").style.display=""; @@ -335,6 +342,8 @@

sendurl='{{ urlfor "PrometheusAlertController.PrometheusAlert"}}?type='+utype.value+'&tpl='+uname.value+'&groupid='+upurl.value; } else if(utype.value=="workwechat"){ sendurl='{{ urlfor "PrometheusAlertController.PrometheusAlert"}}?type='+utype.value+'&tpl='+uname.value+'&wxuser='+upurl.value+'&wxparty='+upparty.value+'&wxtag='+uptag.value; + } else if(utype.value=="kafka"){ + sendurl='{{ urlfor "PrometheusAlertController.PrometheusAlert"}}?type='+utype.value+'&tpl='+uname.value; } else{ sendurl='{{ urlfor "PrometheusAlertController.PrometheusAlert"}}?type='+utype.value+'&tpl='+uname.value+'&phone='+upurl.value; } diff --git a/views/test.html b/views/test.html index a78ad1aa..23f8d3ca 100644 --- a/views/test.html +++ b/views/test.html @@ -244,7 +244,17 @@

** 告警测试功能主要是通过发 - + + + 20 + Kafka + + + 告警测试 + + + + From decf62cc4b1ee8e681ad623a2e421afc2370bc59 Mon Sep 17 00:00:00 2001 From: feiyu563 <244217140@qq.com> Date: Wed, 19 Jun 2024 20:15:12 +0800 Subject: [PATCH 17/19] Update go.mod --- go.mod | 7 ------- 1 file changed, 7 deletions(-) diff --git a/go.mod b/go.mod index 3344701a..d66f7c10 100644 --- a/go.mod +++ b/go.mod @@ -1,25 +1,19 @@ module PrometheusAlert - go 1.20 - require ( github.com/IBM/sarama v1.43.2 github.com/aliyun/alibaba-cloud-sdk-go v1.62.771 github.com/astaxie/beego v1.12.3 - github.com/baidubce/bce-sdk-go v0.9.183 - github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df github.com/go-sql-driver/mysql v1.8.1 github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 github.com/lib/pq v1.10.9 github.com/mattn/go-sqlite3 v2.0.3+incompatible - github.com/olivere/elastic/v7 v7.0.32 github.com/prometheus/client_golang v1.19.1 - github.com/robfig/cron/v3 v3.0.1 github.com/smartystreets/goconvey v1.8.1 github.com/stretchr/testify v1.9.0 @@ -27,7 +21,6 @@ require ( ) require ( - filippo.io/edwards25519 v1.1.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect From ee7e0b61bed29a7bdda20025485c740e066cab6f Mon Sep 17 00:00:00 2001 From: feiyu563 <244217140@qq.com> Date: Wed, 19 Jun 2024 20:16:01 +0800 Subject: [PATCH 18/19] Delete go.sum --- go.sum | 378 --------------------------------------------------------- 1 file changed, 378 deletions(-) delete mode 100644 go.sum diff --git a/go.sum b/go.sum deleted file mode 100644 index cf2613a4..00000000 --- a/go.sum +++ /dev/null @@ -1,378 +0,0 @@ -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= -filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= -github.com/IBM/sarama v1.43.2 h1:HABeEqRUh32z8yzY2hGB/j8mHSzC/HA9zlEjqFNCzSw= -github.com/IBM/sarama v1.43.2/go.mod h1:Kyo4WkF24Z+1nz7xeVUFWIuKVV8RS3wM8mkvPKMdXFQ= -github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= -github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= -github.com/aliyun/alibaba-cloud-sdk-go v1.62.771 h1:/3CAW5lTlOLiB+4klPJg+ZXxp0M4r08iGNuwFB8e7Qs= -github.com/aliyun/alibaba-cloud-sdk-go v1.62.771/go.mod h1:SOSDHfe1kX91v3W5QiBsWSLqeLxImobbMX1mxrFHsVQ= -github.com/astaxie/beego v1.12.3 h1:SAQkdD2ePye+v8Gn1r4X6IKZM1wd28EyUOVQ3PDSOOQ= -github.com/astaxie/beego v1.12.3/go.mod h1:p3qIm0Ryx7zeBHLljmd7omloyca1s4yu1a8kM1FkpIA= - -github.com/baidubce/bce-sdk-go v0.9.183 h1:7FORBGdPOkakL4OBgLskG4vrH7k1AE8OhRFK4+mbgis= -github.com/baidubce/bce-sdk-go v0.9.183/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= - -github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= -github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= -github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= -github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= -github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= -github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= -github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30= -github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= -github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws= -github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3/go.mod h1:YvSRo5mw33fLEx1+DlK6L2VV43tJt5Eyel9n9XBcR+0= -github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= -github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= -github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= -github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= -github.com/elastic/go-elasticsearch/v7 v7.17.10 h1:TCQ8i4PmIJuBunvBS6bwT2ybzVFxxUhhltAs3Gyu1yo= -github.com/elastic/go-elasticsearch/v7 v7.17.10/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4= -github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= -github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= - -github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= -github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= - -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df h1:Bao6dhmbTA1KFVxmJ6nBoMuOJit2yjEgLJpIMYpop0E= -github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df/go.mod h1:GJr+FCSXshIwgHBtLglIg9M2l2kQSi6QjVAngtzI08Y= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= - -github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= -github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= -github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= -github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= - -github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= - -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= -github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= - -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g= -github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k= -github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= -github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= -github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= -github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= -github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= -github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= -github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= -github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= -github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= -github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= -github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= -github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8= -github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= -github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= -github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= - -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= -github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= -github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= -github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= - -github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= -github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= - -github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= -github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= - -github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b h1:FfH+VrHHk6Lxt9HdVS0PXzSXFyS2NbZKXv33FYPol0A= -github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b/go.mod h1:AC62GU6hc0BrNm+9RK9VSiwa/EUe1bkIeFORAMcHvJU= - -github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= -github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= -github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE= -github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= -github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE= -github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= -github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= -github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= -github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= -github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= -github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= -github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= -github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= -github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= -github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= - -github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY= -github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec= -github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY= -github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= - -github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= - -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= - -github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= -github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= -github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o= -github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= -github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg= -github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U= -github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= -github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= -github.com/ysicing/workwxbot v1.1.0 h1:FMWFN7GIjWL47epEc8DR/tKvURAi8p48pBjny+/0vFg= -github.com/ysicing/workwxbot v1.1.0/go.mod h1:HVdUWKQW6w76dAtwGuERPCOn3bJ6/5MXkCXFAgpSBBY= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= - -go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= -go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= - -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= -golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= -golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= - -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= -golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= - -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= - -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= -golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= - -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= - -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= - -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= - -gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= -gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= -gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= -gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= - -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= -google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= -gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= -gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= From ad82443febd2ba0dc1a1b3bb280a3aa89def9355 Mon Sep 17 00:00:00 2001 From: feiyu563 <244217140@qq.com> Date: Wed, 19 Jun 2024 20:20:30 +0800 Subject: [PATCH 19/19] Update Dockerfile --- Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 3934a323..4386cd7d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.21-alpine3.20 as builder +FROM golang:1.20.6-alpine3.18 as builder WORKDIR $GOPATH/src/github.com/feiyu563/PrometheusAlert @@ -14,7 +14,7 @@ COPY . $GOPATH/src/github.com/feiyu563/PrometheusAlert RUN make build # ----------------------------------------------------------------------------- -FROM alpine:3.20 +FROM alpine:3.18 LABEL maintainer="jikun.zhang"